0

I'd like to know how do I check if an input is a palindrome with a while loop, using Python.

Thanks:

i tried this

i = 0
n = len(msg_list)

while i < n:
    palindrome = msg_list[i]
    if palindrome == msg_list[-1]:
        print("Palindrome? True")
        msg_list.pop(-1)
    else:
        print("Palindrome? False")
    i=i+1

but at the end I receive an error message that the list index is out of range

Aran-Fey
  • 39,665
  • 11
  • 104
  • 149
astdium
  • 11
  • 1
  • 1
  • 5

6 Answers6

1

You don't need to iterate till the end, but only till the middle character. And compare every character to the character at the same index when counted in reverse:

s = "abcca"
length = len(s)
i = 0

while i < length / 2 + 1:
    if s[i] != s[-i - 1]:
        print "Not Palindrome"
        break
    i += 1
else:
    print "Palidrome"

else part of the while loop is executed, when the loop completes its iteration without any break.


Alternatively, if you can use anything else than a while loop, then this task is just of single line in Python:

if s == s[::-1]: 
    print "Palindrome"

Oh, it became two lines.

Rohit Jain
  • 209,639
  • 45
  • 409
  • 525
1

With a while loop

import string

palin = 'a man, a plan, a canal, panama'

def testPalindrome(in_val):
    in_val = in_val.lower()
    left, right = 0, len(in_val) - 1
    while left < right:
        char_left, char_right = '#', '#'
        while char_left not in string.lowercase:
            char_left = in_val[left]
            left += 1
        while char_right not in string.lowercase:
            char_right = in_val[right]
            right -= 1
        if char_left != char_right:
            return False
    return True

print testPalindrome(palin)

Without

>>> palindrome = 'a man, a plan, a canal, panama'
>>> palindrome = palindrome.replace(',', '').replace(' ', '')
>>> palindrome
'amanaplanacanalpanama'
>>> d[::-1] == d
True
sberry
  • 128,281
  • 18
  • 138
  • 165
0

A short solution using reversed:

for c, cr in s, reversed(s):
    if c != cr:
        print("Palindrome? False")
        break
else:
    print("Palindrome? True")
nneonneo
  • 171,345
  • 36
  • 312
  • 383
0

Another way using a while loop. Once two characters don't match, the while loop stops, so it's quite efficient but of course not the best way to do it in Python.

def palindrome(word):
   chars_fw = list(word)
   chars_bw = list(reversed(word))
   chars_num = len(word)
   is_palindrome = True
   while chars_num:
       if chars_fw[chars_num-1] != chars_bw[chars_num-1]:
           is_palindrome = False
           break
       chars_num -= 1

   return is_palindrome 
pemistahl
  • 9,304
  • 8
  • 45
  • 75
0

Figured I would add another alternative for people still viewing this question. It uses a while loop, and is reasonably concise (although, I still prefer the if word = word[::-1] approach.

def is_palindrome(word):    
    word = list(word.replace(' ', ''))  # remove spaces and convert to list
    # Check input   
    if len(word) == 1:
        return True
    elif len(word) == 0:
        return False
    # is it a palindrome....    
    while word[0] == word[-1]:
        word.pop(0)
        word.pop(-1)    
        if len(word) <= 1:
            return True
    return False
Friendly King
  • 2,396
  • 1
  • 23
  • 40
0
word = "quiniuq"
pairs = zip(word,reversed(word))
a,b = next(pairs)
try:
    while a == b:
        a,b = next(pairs)
    return False # we got here before exhausting pairs
except StopIteration:
    return True # a == b was true for every pair

The use of a while loop here is contrived, but it will consume the whole list and perform the test.

If a while loop wasn't a requirement, one would do: all(a == b for a,b in zip(word,reversed(word)))

Marcin
  • 48,559
  • 18
  • 128
  • 201