2

I'm writing a simple code to check if a number is a palindrome. Whenever the number have two consecutive zeros, print('removing',palind[-1]) targets the wrong zeros in the list.

n = 200314413002
x = n
palind = []
while n > 0:
    d = n % 10
    n = n // 10
    palind.append(d)
    
print(palind, 'is to check')    
    
actual_palind = []

for i in palind:
    if palind[0] == palind[-1] and len(palind) % 2 == 0:
        print('removing',palind[0])
        palind.remove(palind[0])
        print('removing',palind[-1])
        palind.remove(palind[-1])
        print(palind,'is still a palindrome')
        actual_palind.append(x)
    else:
        print(x,'is not a palindrome')
        break
        
print(x, 'is a palindrome')

Here is the output

[2, 0, 0, 3, 1, 4, 4, 1, 3, 0, 0, 2] is to check
removing 2
removing 2
[0, 0, 3, 1, 4, 4, 1, 3, 0, 0] is still a palindrome
removing 0
removing 0
[3, 1, 4, 4, 1, 3, 0, 0] is still a palindrome
200314413002 is not a palindrome
200314413002 is a palindrome

What am I missing ?

ripj
  • 27
  • 3

2 Answers2

3

This does not remove the last item from the list:

palind.remove(palind[-1])

It removes the first item of the list which equals palind[-1], which is a problem if there are multiple equal items.

To remove the last item of the list, do this:

del palind[-1]
zvone
  • 18,045
  • 3
  • 49
  • 77
2

Like zvone stated in their answer, the remove() doesn't remove according to index, it removes according to value. To remove according to index, use .pop():

for i in palind:
    if palind[0] == palind[-1] and len(palind) % 2 == 0:
        print('removing',palind.pop(0))
        print('removing',palind.pop(-1))
        print(palind,'is still a palindrome')
        actual_palind.append(x)
    else:
        print(x,'is not a palindrome')
        break
        

Output:

[2, 0, 0, 3, 1, 4, 4, 1, 3, 0, 0, 2] is to check
removing 2
removing 2
[0, 0, 3, 1, 4, 4, 1, 3, 0, 0] is still a palindrome
removing 0
removing 0
[0, 3, 1, 4, 4, 1, 3, 0] is still a palindrome
removing 0
removing 0
[3, 1, 4, 4, 1, 3] is still a palindrome
removing 3
removing 3
[1, 4, 4, 1] is still a palindrome
200314413002 is a palindrome
Red
  • 26,798
  • 7
  • 36
  • 58