this question has answer here:
- python recursion list returns none 1 answer
ps: question marked duplicate , there answer. thing is, question not same other one. in problem, know code wrong. im asking why wrong.
this problem on udacity asked solve:
define procedure is_palindrome, takes input string, , returns boolean indicating if input string palindrome.
hint:
base case:
''
=>true
recursive case: if first , last characters don't match =>
false
if match, middle 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 3 input cases try:
print is_palindrome('') #>>> true print is_palindrome('abab') #>>> false print is_palindrome('abba') #>>> true
if leave code that, return none case 'abba'. can fixed changing last line of function into
return is_palindrome(s[1:-1])
may ask why return
matter? without return, shouldn't run function is_palindrome()
on again , again?
even without return, shouldnt run function is_palindrome() on again , again?
sure -- it'll run on , over, won't return useful, you'll never see result. because first is_palindrome
call return none
independent of return values of recursing calls is_palindrome
(none
python's default when don't specify return value).
Comments
Post a Comment