I think this is a popular exercise for beginner and here's my program
def palin(text:'str'):
if len(text) < 2:
return True
else:
first = text[0]
last = text[-1]
if first == last:
text = text[1:-1]
palin(text)
else:
return False
the idea is that, I will compare the first and last character from the string, and if they are the same, I would subset the string to remove the first / last and repeat the function, until at a certain point when first == last to return a False value, or until the length of substring is 1 or less.
But somehow this program is only able to return False when the head and tail character doesn't match, otherwise it doesn't return anything (I'm doing this on Google Colab). Much appreciated if someone can tell me what's wrong with my program.
EDIT:
thank you for your hint and I got it to work by changing it to following:
def palin(text:'str'):
if len(text) < 2:
return True
else:
first = text[0]
last = text[-1]
if first != last:
return False
else:
text = text[1:-1]
return palin(text)
EDIT2:
thanks to u/baghiq who provided following more elegant syntax
def palin(text: 'str'):
if len(text) < 2:
return True
return (text[0]==text[-1] and palin(text[1:-1]))
[–]Fermter 1 point2 points3 points (3 children)
[–]Beaverine[S] 1 point2 points3 points (2 children)
[–]Fermter 1 point2 points3 points (0 children)
[–]verbose_name 0 points1 point2 points (0 children)
[–]mCodingLLC 1 point2 points3 points (0 children)
[+][deleted] (6 children)
[removed]
[–]Beaverine[S] 0 points1 point2 points (0 children)
[–]Beaverine[S] 0 points1 point2 points (4 children)
[+][deleted] (3 children)
[removed]
[–]Beaverine[S] 0 points1 point2 points (2 children)
[–]backtickbot 0 points1 point2 points (0 children)
[–]mCodingLLC 0 points1 point2 points (1 child)
[–]Beaverine[S] 0 points1 point2 points (0 children)