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?

Vu TrongNghia
  • 140
  • 2
  • 9

2 Answers2

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

mgilson
  • 300,191
  • 65
  • 633
  • 696
  • 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? – Vu TrongNghia Jan 30 '16 at 16:13
1

This task, doesn't require recursion:

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

Solve it simply and move on.

Dima Tisnek
  • 11,241
  • 4
  • 68
  • 120