0

I am currently taking a course on Python and am currently struggling with one portion of my homework.

The question is asking us to construct a function that checks a string to see if it is a palindrome. The problem I am having is that for one of the tests my instructor has provided is for the palindrome "Never odd or even" which contains spaces. The spaces are causing my function to fail because it won't just use the letters in the phrase.

My current code is:

def is_palindrome(phrase):

    return phrase == phrase[::-1]

She is testing with the code:

assert is_palindrome("Never odd or even")

Any help would be appreciated! Thanks.

Barmar
  • 741,623
  • 53
  • 500
  • 612
JDF
  • 23
  • 5
  • As-is, your code doesn't care about capitalization or spaces. How have you tried accounting for those? – Blender Sep 08 '17 at 00:21
  • 1
    Remove all the spaces and convert everything to the same case, then do the test. – Barmar Sep 08 '17 at 00:22
  • I'm not sure how I would edit my code to account for that. Would I have to convert the string into a list? – JDF Sep 08 '17 at 00:23
  • See https://stackoverflow.com/questions/20991605/how-to-remove-white-spaces-from-a-string-in-python for how to remove spaces. See https://stackoverflow.com/questions/6797984/how-to-convert-string-to-lowercase-in-python for how to convert to the same case. – Barmar Sep 08 '17 at 00:24
  • You could just google "python remove spaces from string" – Barmar Sep 08 '17 at 00:24
  • 1
    You don't need to convert your string into a list. It's already iterable (strings are really just arrays of characters under the hood) – Soviut Sep 08 '17 at 00:25
  • Sanitize the string: `string.replace(' ', '').lower()` and use that. – Christian Dean Sep 08 '17 at 00:27
  • Thank you so much guys, I didn't know you could use multiple methods on one string. That did the trick! – JDF Sep 08 '17 at 00:31

2 Answers2

1

I think this is what you want:-
is_palindrome("Never odd or even".replace(" ", "").lower())

Or

If you want to change your function then your function look like:

def is_palindrome(phrase):
    phrase=phrase.replace(" ","").lower()
    return phrase == phrase[::-1]   

and you can call it using is_palindrome("Never odd or even")

Vineet Jain
  • 1,515
  • 4
  • 21
  • 31
0

First remove the spaces, then use recursion, checking only if the first and last characters are the same, recursing on the inner part.

def is_palindrome(x):
    x = "".join(x.split()).lower()
    if (len(x) <= 1): return True
    if x[0] != x[-1]: return False
    return is_palindrome(x[1:-1])
Jon Deaton
  • 3,943
  • 6
  • 28
  • 41
  • This is unlikely to be more efficient compared to simply reverse the full string, since you are effectively copying (creting new string objects) on every recursive call (`x[1:-1]` is a new string with its ow memory). – Hannes Ovrén Oct 03 '17 at 10:16