mirror of
https://github.com/autistic-symposium/master-algorithms-py.git
synced 2025-05-02 06:46:18 -04:00
🏣 Clean up for arxiv
This commit is contained in:
parent
1b969e7db3
commit
41756cb10c
280 changed files with 2 additions and 11 deletions
58
book/ebook_src/real_interview_problems/palindome.py
Normal file
58
book/ebook_src/real_interview_problems/palindome.py
Normal file
|
@ -0,0 +1,58 @@
|
|||
#!/usr/bin/env python
|
||||
|
||||
__author__ = "bt3"
|
||||
|
||||
import string
|
||||
|
||||
def sanitize(sentence):
|
||||
array = sentence.lower()
|
||||
array = array.strip()
|
||||
array = array.strip(string.punctuation)
|
||||
return array
|
||||
|
||||
def check_if_palindrome(array):
|
||||
if len(array) < 2:
|
||||
return True
|
||||
|
||||
if array[0] == array[-1]:
|
||||
return check_if_palindrome(array[1:-1])
|
||||
else:
|
||||
return False
|
||||
|
||||
def check_if_palindrome_iter(array):
|
||||
i, j = 0, len(array)-1
|
||||
|
||||
while i <= j:
|
||||
if array[i] != array[j]:
|
||||
return False
|
||||
i += 1
|
||||
j -= 1
|
||||
|
||||
return True
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
sentence = 'hello there'
|
||||
array = sanitize(sentence)
|
||||
assert(check_if_palindrome(array) == False)
|
||||
assert(check_if_palindrome_iter(array) == False)
|
||||
|
||||
sentence = ''
|
||||
array = sanitize(sentence)
|
||||
assert(check_if_palindrome(array) == True)
|
||||
assert(check_if_palindrome_iter(array) == True)
|
||||
|
||||
sentence = 'h'
|
||||
array = sanitize(sentence)
|
||||
assert(check_if_palindrome(array) == True)
|
||||
assert(check_if_palindrome_iter(array) == True)
|
||||
|
||||
sentence = 'Noel sees Leon'
|
||||
array = sanitize(sentence)
|
||||
assert(check_if_palindrome(array) == True)
|
||||
assert(check_if_palindrome_iter(array) == True)
|
||||
|
||||
sentence = 'Noel sees Leon!'
|
||||
array = sanitize(sentence)
|
||||
assert(check_if_palindrome(array) == True)
|
||||
assert(check_if_palindrome_iter(array) == True)
|
Loading…
Add table
Add a link
Reference in a new issue