I've been asked to write a program that tests if a given string is a palindrome or not. n is a string of length 1<=x<=10000 containing no spaces or special characters. I wrote the following in a few minutes:
def run(n):
n = n.replace('\n','')
nprime = n[::-1]
Bool = True
for i in range(0,len(n)):
if not n[i]==nprime[i]:
Bool = False
if Bool==True:
print "Y"
else:
print "N"
Apparently this fails for some test case. I don't know the test case for which it fails. I tried it out with all edge-cases I could think of and my script seems to work fine. Does anyone have any idea where it could be failing?
I would simplify your code to:
def check(inval):
val = inval.strip().lower()
lav = val[::-1]
print (val == lav) and 'Y' or 'N'
If you would like a really generalised version use:
def check(inval):
val = ''.join([l for l in inval if l.isalnum()]).lower()
lav = val[::-1]
result = (val == lav)
# print result and 'Y' or 'N' # Since comments indicate some dislike this!
return result
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.