Skip to content

Instantly share code, notes, and snippets.

@sergiors
Last active May 21, 2020 11:26
Show Gist options
  • Save sergiors/b7055749aaf779b0c5d8406ad8bfa154 to your computer and use it in GitHub Desktop.
Save sergiors/b7055749aaf779b0c5d8406ad8bfa154 to your computer and use it in GitHub Desktop.
import re
"""
Head=1
|
| __________Tail=[2,3,4,5]
||
[1,2,3,4,5]
[1,2,3,4]=Init________||
|
|
5=Last
"""
def palindrome(data: str):
# remove all non-alphanumeric from input data
# and become it lowercase
# https://docs.python.org/3/howto/regex.html
# ex: 'Rotor %$#' -> 'rotor'
data = re.sub(r'\W+', '', data).lower()
# checks if first (head) and last (last) letter is the same
# ex: 'r' == 'r'
eq = data[0] == data[-1]
# ex: 'rotor' -> 'oto'
mid = data[1:-1]
# if has mid, checks if head and last is the same
# and check the rest (mid), if there it
if mid:
# just to know how the recursion works
# ex: palindrome('rotor') -> palindrome('oto') -> palindrome('t')
return eq & palindrome(mid)
return eq
if __name__ == '__main__':
# if nothing is printed when you try it on terminal, it's means that works
assert(True == palindrome('Rotor'))
assert(True == palindrome('Racecar'))
assert(True == palindrome('Arara'))
assert(True == palindrome('my gym'))
assert(True == palindrome('Red rum, sir, is murder'))
assert(False == palindrome('Lincoln'))
@sergiors
Copy link
Author

>>> 'rotor'[1:-1]
'oto'
>>> 'oto'[1:-1]
't'
>>> 't'[1:-1]
''

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment