I am trying to find the longest palindrome in a given string. I came across a strange behavior of if
statement. posting both the codes here, in 1st code when I tried debugging everything is working fine till if statement, but even after getting True
, it is not accessing the further code inside.
Whereas in the second code I stored the return value of palindrome function in the boolean var and then used it in if statement. now it is accessing the inside code.
I guess I am missing something very fundamental in python. Please can someone tell why is this happening?
Code 1:
def palindrom(temp):
if(temp==temp[::-1]):
return True
else:
return False
word=input("enter the string to check ")
maxx="" #to store the longest palindrome till now
l=len(word)
for i in range(0,l):
# if(len(maxx)>l-i): ## to check if remaining string is smaller than maxx
# print(maxx)
# break
temp=word[i] ## testing by adding one letter at a time
for j in range(i+1,l):
temp=temp+word[j]
if(temp is palindrom(temp) and len(temp)>len(maxx) ):
maxx=temp ##updating the maxx
print(maxx)
Code 2:
def palindrom(temp):
if(temp==temp[::-1]):
return True
else:
return False
word=input("enter the string to check ")
maxx=""
l=len(word)
for i in range(0,l):
# if(len(maxx)>l-i): ## to check if remaining string is smaller than maxx
# print(maxx)
# break
temp=word[i]
for j in range(i+1,l):
temp=temp+word[j]
bul=palindrom(temp) ##storting the return value of palindrome() in a boolean.
if(bul and len(temp)>len(maxx)):
maxx=temp
print(maxx)
Aucun commentaire:
Enregistrer un commentaire