-4

I am doing a palindrome check program for school, but there is a twist.

Now I already know that I could use a reverse function or something like:

[-1::-1]

However, the program specifically calls for no string slicing or use of the .reverse() function. So, my question is how would I go about doing this if I cannot use these two simple methods?

Blair
  • 15,356
  • 7
  • 46
  • 56
user2257342
  • 43
  • 1
  • 2
  • 3

3 Answers3

5

It's clear that this is for academic purposes only because using reversed function this code would be trivial.

def is_palindrome(string):
    for i,char in enumerate(string):
        if char != string[-i-1]:
            return False
    return True

>>> is_palindrome('hello')
False    
>>> is_palindrome('helloolleh')
True
>>> is_palindrome('')
True
>>> is_palindrome(' ')
True
>>> is_palindrome('a')
True
Diego Herranz
  • 2,857
  • 2
  • 19
  • 34
  • a little more overhead, but `p = lambda s: sum([s[i] != s[-i-1] for i in range(len(s)/2)]) == 0` – jozxyqk Sep 23 '13 at 13:23
4

Canonical solution would be:

def is_palindrome(string):
    result = True
    str_len = len(string)
    for i in range(0, int(str_len/2)): # you need to check only half of the string
        if string[i] != string[str_len-i-1]:
            result = False
            break
    return result # single return statement is considered a good practice
J0HN
  • 26,063
  • 5
  • 54
  • 85
  • 2
    Good solution, but I have to dispute the assertion that a single return statement is considered good practice in Python. In fact I'll say the `break` is unnecessary and two return statements make more sense. – Asclepius Jul 13 '16 at 06:08
1

You actually don't need any reverse function at all to check if something is a palindrome. Consider:

  • an empty string is a palindrome
  • a string of length 1 is a palindrome
  • every other string is a palindrome if its first and last characters are equal and the "middle" part (without the first and the last chars) is a palindrome, recursively.

Try to implement this in python - it's easy! (Hint: the last char is str[-1] and the middle is str[1:-1]).

georg
  • 211,518
  • 52
  • 313
  • 390