Skip to content

Commit 12f7f03

Browse files
authored
Add files via upload
1 parent ba6f5cc commit 12f7f03

File tree

1 file changed

+85
-0
lines changed

1 file changed

+85
-0
lines changed

palindrome checker 4 methods.py

Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,85 @@
1+
# -*- coding: utf-8 -*-
2+
"""
3+
Created on Sun Apr 8 18:10:50 2018
4+
5+
@author: Administrator
6+
"""
7+
#check if a string is a palindrome
8+
#reversing a string is extremely easy
9+
#at first i was thinking about using pop function
10+
#however, for an empty string, pop function is still functional
11+
#it would not stop itself
12+
#it would show errors of popping from empty list
13+
#so i have to use the classic way, slicing
14+
#each time we slice the final letter
15+
#to remove the unnecessary marks, we have to use regular expression
16+
17+
import re
18+
19+
def f(n):
20+
#this is the base case, when string is empty
21+
#we just return empty
22+
if n=='':
23+
return n
24+
else:
25+
return n[-1]+f(n[:-1])
26+
27+
def check(n):
28+
#this part is the regular expression to get only characters
29+
#and format all of em into lower cases
30+
c1=re.findall('[a-zA-Z0-9]',n.lower())
31+
c2=re.findall('[a-zA-Z0-9]',(f(n)).lower())
32+
if c1==c2:
33+
return True
34+
else:
35+
return False
36+
37+
38+
39+
#alternatively, we can use deque
40+
#we pop from both sides to see if they are equal
41+
#if not return false
42+
#note that the length of string could be an odd number
43+
#we wanna make sure the pop should take action while length of deque is larger than 1
44+
45+
from collections import deque
46+
47+
def g(n):
48+
49+
c=re.findall('[a-zA-Z0-9]',n.lower())
50+
de=deque(c)
51+
while len(de) >=1:
52+
if de.pop()!=de.popleft():
53+
return False
54+
return True
55+
56+
57+
#or we can use non recursive slicing
58+
def h(n):
59+
c=re.findall('[a-zA-Z0-9]',n.lower())
60+
if c[::-1]==c:
61+
return True
62+
else:
63+
return False
64+
65+
#or creating a new list
66+
#using loop to append new list from old list s popped item
67+
def i(n):
68+
c=re.findall('[a-zA-Z0-9]',n.lower())
69+
d=[]
70+
for i in range(len(c)):
71+
d.append(c.pop())
72+
c=re.findall('[a-zA-Z0-9]',n.lower())
73+
74+
if d==c:
75+
return True
76+
else:
77+
return False
78+
79+
80+
81+
print(check('Evil is a deed as I live!'))
82+
print(g('Evil is a deed as I live!'))
83+
print(h('Evil is a deed as I live!'))
84+
print(i('Evil is a deed as I live!'))
85+
#for time and space complexity, python non recursive slicing wins

0 commit comments

Comments
 (0)