0

ps: This question was just marked as duplicate and there was already an answer. The thing is, this question is not the same as the other one. In this problem, I already know where my code was wrong. Im asking WHY it was wrong.

This is a problem on udacity that I was asked to solve:

Define a procedure is_palindrome, that takes as input a string, and returns a Boolean indicating if the input string is a palindrome.

Hint:

Base Case: '' => True

Recursive Case: if first and last characters don't match => False

If they do match, is the middle a palindrome?

def is_palindrome(s):
    if s=='':
        return True
    else:
        if s[0]!=s[-1]:
            return False
        else:
            s=s[1:-1]
            is_palindrome(s)

And the 3 input cases to try:

print is_palindrome('')
#>>> True
print is_palindrome('abab')
#>>> False
print is_palindrome('abba')
#>>> True

If I leave my code like that, it will return None for case 'abba'. It can be fixed by changing the last line of the function into

return is_palindrome(s[1:-1])

May I ask why the return matter? Even without the return, shouldn't it just run the function is_palindrome() over again and again?

0

2 Answers 2

7

Even without the return, shouldnt it just run the function is_palindrome() over again and again?

Sure -- It'll run it over and over, but it won't return anything useful, so you'll never get to see the result. This is because the first is_palindrome call will return None independent of the return values of the recursing calls to is_palindrome (None is Python's default when you don't specify a return value).

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

1 Comment

When is_palindrome is run again and checked again, there're already some return in it, but these run-again-inner return wont be returned?
1

This task, doesn't require recursion:

In [2]: "aloof"[::-1]
Out[2]: 'foola'

Solve it simply and move on.

1 Comment

I know how to do it easy way. The lesson just used the problem as an example of how Recursive Functions can be useful

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.