Mohammad Areeb Siddiqui Mohammad Areeb Siddiqui - 3 months ago 8x
Python Question

Python - variable not updating in loop

I am trying to solve the 'Love-Letter' mystery problem of HackerRank using Python, but I am stuck at a place where in my loop a variable is not getting updated.

s = input()
first_char = s[0]
last_char = s[-1]
ascii_first_char = ord(first_char)
ascii_last_char = ord(last_char)
count = 0
i = 1
while ascii_first_char < ascii_last_char:
count += abs((ascii_last_char-ascii_first_char))
ascii_first_char = ord(s[i])
ascii_last_char = ord(s[-i])
i += 1


If you try to run that, you would see that alc is not changing it's value according to
where I keeps incrementing. Why is that happening?


You get the first letter with s[0] and the last with s[-1]. In your loop you take the next letters with the same index i.

I don't understand your condition in the while loop. Instead of "ascii_first_char < ascii_last_char" you should test if you have looked at every element of the string. For that we have to loop len(s)/2 times. Something like:

while i < len(s) - i:

or equivalent

while 2*i < len(s):

And this conditions only work for even length. I prefer for-loops when I know how many times I will loop

current_line = input()
# if length is even, we don't care about the letter in the middle
# abcde <-- just need to look for first and last 2 values
# 5 // 2 == 2
half_length = len(current_line) // 2
changes = 0
for i in range(index):
    changes += abs(
        ord(current_line[i]) - ord(current_line[-(i+1)])
print (changes)