2

I'm trying to check if a number is a palindrome or not. To do that I'm counting the number of times the kth element is equal to the (n-k)th element. If that number is equal to the length of the string , then it is a palindrome. I do get correct output for palindromes but absolutely no output(k) when the number is not a palindrome. Code for reference :

T = int(raw_input())
L = []
for i in range(0,T):
    alpha = int(raw_input())
    L.append(alpha)
print L

for i in range(0,len(L)):
    L[i] = str(L[i])
print L

for i in range(0,len(L)):
    k = 0
    while k < len(L[i]) :
        if L[i][k] == L[i][len(L[i])-(k)-1]:
            k = k + 1
    print k
ChaosPredictor
  • 3,777
  • 1
  • 36
  • 46
Devesh Lohumi
  • 362
  • 2
  • 15

4 Answers4

3

Don't use such complex logic. Use simple pythonic [::-1] to reverse the string.

In [1]: a = 1234554321

In [2]: def pal(a):
   ...:     if a == a[::-1]:
   ...:         return True
   ...:     else:
   ...:         return False
   ...:

In [3]: pal(str(a))
Out[3]: True
Osman Mamun
  • 2,864
  • 1
  • 16
  • 22
3

Maybe you can try something more succint. How about this:

def is_palindrome(n):
    return str(n) == str(n)[::-1]

n = int(raw_input("Enter a number: "))

print(is_palindrome(n))
1

You should listen to the advice from the other answers on how to properly solve this.

However, no one answered the actual question you asked: Why do I get correct output for palindromes but no output for regular numbers?

Take a look at this while loop:

k = 0
while k < len(L[i]) :
    if L[i][k] == L[i][len(L[i])-(k)-1]:
        k = k + 1

If L is not a palindrome, the condition in the if sentence evaluates to false, and k is never incremented. So k remains zero, and the condition in the while loop is always true.

You've got yourself an infinite while loop!

Anders Carstensen
  • 2,949
  • 23
  • 23
0

My advice for you is to go through the basics of python first. Moreover, have a look on python3. It's so easy. Your algorithm is not bad and its implementation is not done properly. Here is what you want to do. (it's in python3)

L = input('Enter a word: ')        

print ('Your word is:', L)

# As per your algorithm
count = 0
size = len(L)

for i in enumerate(L):
#   since if the size is 7, then the last index will be 6(=  7-1)
    if L[i] == L[size -1 -i]:
            count += 1


if count == size:
    print(L, 'is palindrome')
else:
    print(L, 'is not palindrome')
Mohith7548
  • 1,282
  • 2
  • 16
  • 24
  • you were creating a 2D array type for a give string and is not correct. Moreover your way of taking input is poor – Mohith7548 Oct 22 '18 at 14:24