So i'm trying to write a function that checks if a string is palindrome or not ( palindrome if it spells the same backwards e.g.: hannah)
This is a solution i saw online and i don't quite understand it, any simple explanation would be appreciated
def isPalindrome(string):
left_pos = 0
right_pos = len(string) - 1
while right_pos >= left_pos:
if not string[left_pos] == string[right_pos]:
return False
left_pos += 1
right_pos -= 1
return True
print(isPalindrome('hannah'))
Edit: Sorry for my lack of clarity, i mostly dont understand the condition set in the while loop and the logic behind the if statement.
It compares the last character with the first and moves inside the string as follows:
hannah
^ ^
check the two letters are equal: (return False if not) move the index by 1
hannah
^ ^
Do the same check
hannah
^^
right index = left index at this point
return True in this case