File tree Expand file tree Collapse file tree 2 files changed +29
-0
lines changed Expand file tree Collapse file tree 2 files changed +29
-0
lines changed Original file line number Diff line number Diff line change 1+ ### Is it a Palindrome?
2+ A word (or sentence) is a palindrome when reading it from right to left is the same as from left to right.
3+ For example: ** level** is a palindrome.
4+
5+ The code uses recursion in order to iteratively compare the first and last element of the string,
6+ gradually reducing the string until the middle of it.
7+ Recursion is used when you do not know in advance how many iterations you need in order to get a solution.
Original file line number Diff line number Diff line change 1+ def isPalindrome (s ):
2+ s = s .lower ().replace (' ' , '' ) # this allows working on sentences as well
3+ if s == '' or len (s ) == 1 :
4+ return True
5+ else :
6+ if s [0 ] != s [- 1 ]:
7+ return False
8+ s = s [1 :- 1 ]
9+ return isPalindrome (s ) # note: we might delete s = s[1:-1] and write directly return isPalindrome(s[1:-1])
10+
11+
12+ def main ():
13+ word = input ('enter a string: ' )
14+ print ('is that a palindrome?' )
15+ if isPalindrome (word ):
16+ print ("Yep" )
17+ else :
18+ print ("Nope" )
19+
20+
21+ if __name__ == '__main__' :
22+ main ()
You can’t perform that action at this time.
0 commit comments