recursion function | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

recursion function

con anyone explain to my why this function did not work def isPalindrome(str, first=0, last=-1): if first >= len(str)/2: return True if str[first] != str[last]: return False isPalindrome(l, first+1, last-1) l am try to use the recursion function to know if the string is palindrome or not

3rd Dec 2020, 8:59 PM
Ali Hesham
Ali Hesham - avatar
4 Answers
+ 4
https://code.sololearn.com/cW0Ly3HBUi5n/?ref=app 1. The variable l doesn't exist, you're meant to pass str as the argument. 2. You have to put a return before the recursive function call.
3rd Dec 2020, 10:23 PM
inxanedev!
inxanedev! - avatar
+ 2
Angelo Yeah I assume it's only for practice, I myself understand how recursion works but I try to stay away from them as far as possible. Checking if something is a palindrome is as simple as this: def isPalindrome(x): return x == x[::-1]
3rd Dec 2020, 10:36 PM
inxanedev!
inxanedev! - avatar
0
This is sooo wrong... Just the fact you want to do it recursively is wrong (all that poor stack memory wasted) First: isPalindrome("abcd... ", 3) will return True when it's not supposed to Second: you should at least return the function in some way to make it recursive So... if first >= last: return True if str[first] != str[last]: return False return isPalindrome(str, first+1, last-1)
3rd Dec 2020, 10:34 PM
Angelo
Angelo - avatar
0
That, inxanedev!, is a Python code worth of that name!
3rd Dec 2020, 10:44 PM
Angelo
Angelo - avatar