1

An online MIT course which I downloaded ask's its students to create a function to test if a string is a palindrome. They mention len and only taking a slice of the string. As I understand the assignment I used neither, but my code seems to work. Is there something I am missing?

def test_word():
    question = input("Do you want to see if a word or sentence is a 
palindrome? (y/n)")
    question = question.lower()
    if question == "y":
        sample = input("Provide test word or sentence: \n>>>")
        sample = sample.lower()
        print(is_palindrome(sample))
        test_word()
    elif question == "n":
        print("Goodbye!")
        quit()
    else:
        print("Y for yes or N for no, please.")
        test_word()


def is_palindrome(x):
    # Use negative 1 step to reverse order
    y = x[::-1]

    if x == y:
        return True
    elif x != y:
        return False



test_word()
Ishpreet
  • 5,230
  • 2
  • 19
  • 35
Ruark
  • 15
  • 3

1 Answers1

0

Your is_palindrome(x) function is working well, but you can shorten it.

def is_palindrome(x):
    return x == x[::-1]

Also, you can use for an alternative to the rather unintuitive [::-1] syntax(Source). But, this can be slower, specially when strings get longer(Check the comment of mata):

def is_palindrome(x):
    return x == ''.join(reversed(x))

And, your test_word() method calls itself again and again(recursively). Recursion is not necessary and, actually, a little bit problematic here. You should use loop:

def test_word():
    while True:
        question = input("Do you want to see if a word or sentence is a palindrome? (y/n)")
        question = question.lower()
        if question == "y":
            sample = input("Provide test word or sentence: \n>>>")
            sample = sample.lower()
            print(is_palindrome(sample))
        elif question == "n":
            print("Goodbye!")
            break
        else:
            print("Y for yes or N for no, please.")

I hope, this helps.

Alperen
  • 3,772
  • 3
  • 27
  • 49
  • Thanks! As I am self studying it is great to get advice like this. – Ruark Oct 18 '17 at 07:17
  • 1
    Unintuitive is a matter of tase, I don't find `''.join(reversed(x))` better then `x[::-1]`, joining the reversed object of a string on the empty string isn't really intuitive. Also, it can be [way slower](https://pastebin.com/jrkdHrDX), specially when strings get longer. The strength of `reversed()` is that it doesn't have to create the whole reversed sequence in memory. – mata Oct 18 '17 at 09:44
  • @mata I don't have enough knowledge about this, I just shared what [the source link](https://stackoverflow.com/a/17331369/6900838) says. But, thanks to you, now we know `x[::-1]` is away faster. – Alperen Oct 18 '17 at 09:58
  • One note, you actually only have to compare the first half of the string to the reversed second half. – user2390182 Oct 18 '17 at 10:10