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.

8
  • As-is, your code doesn't care about capitalization or spaces. How have you tried accounting for those? Commented Sep 8, 2017 at 0:21
  • 1
    Remove all the spaces and convert everything to the same case, then do the test. Commented Sep 8, 2017 at 0: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? Commented Sep 8, 2017 at 0:23
  • See stackoverflow.com/questions/20991605/… for how to remove spaces. See stackoverflow.com/questions/6797984/… for how to convert to the same case. Commented Sep 8, 2017 at 0: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) Commented Sep 8, 2017 at 0:25

2 Answers 2

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")

Sign up to request clarification or add additional context in comments.

Comments

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])

1 Comment

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).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.