I have tried two methods to make a palindrome check that uses input but neither work. [Python]

Viewed 29

I am trying to make a script that checks if input is a palindrome or not. I'm confused as to why neither of them work. In the first attempt, I printed reversed_phrase but it printed <list_reverseiterator object at 0x000001DDD1E27D60>. In the second attempt, I printed phrase[i] and reverse_phrase[i] in each iteration and they printed the same thing.

First Attempt:

original_phrase = input()
phrase = list(original_phrase)
reversed_phrase = reversed(phrase)

if phrase == reversed_phrase:
    print(original_phrase, 'is a palindrome')
else:
    print(original_phrase, 'is not a palindrome')

Second Attempt:

original_input= input()
phrase = list(original_input)

reversed_phrase = phrase
reversed_phrase.reverse()

is_palindrome = False
for i in range(0, len(phrase)):
    print(phrase[i], reversed_phrase[i])
    if phrase[i] != reversed_phrase[i]:
        break
    elif i >= len(phrase) - 1:
        is_palindrome = True


if is_palindrome:
    print(original_input, 'is a palindrome')
else:
    print(original_input, 'is not a palindrome')
1 Answers

Your first solution is misusing the reversed(array) function as it returns a pointer to the end of the array so that you can iterate through it in reverse. What you want here is to actually reverse the array which is done with array.reverse();

Your second solution incorrectly always returns true because when you do this: reversed_phrase = phrase both reversed_phrase and phrase reference the same object, so any changes made to one appear when referencing either. What you want to do is reversed_phrase = phrase.copy() so that they are each individual versions of the array

Related