Below is the code to check if the list is a palindrome or not. It gives the correct result for 983. Where am I going wrong?
def palindrome(num): flag=0 r=num[::-1] for i in range (0, len(num)-1): if(r[i]==num[i]): flag=1 else: flag=0 return flag
You must return as soon as a mismatch occurs. In addition, you just need to repeat up to half the length:
def function(...): ... for i in range (0, (len(num) + 1) / 2): if r[i] != num[i]: return False return True
By the way, you do not need this loop. You can simply do:
def palindrome(num): return num == num[::-1]
That would be easier:
def palindrome(num): if num[::-1] == num: return True else: return False
for , , . , "38113" True, flag ββ True "38113" "31183" ( 3, )., False , ; - True, :
for
True
flag
False
def palindrome(num): r = num[::-1] for i in range (0, len(num)-1): if(r[i] != num[i]): return False return True
, -, python - .
For writing purposes only, and for those who are looking for a more algorithmic way to check if a given line is a palindrome, there are two ways to achieve the same (using whileand loops for):
while
def is_palindrome(word): letters = list(word) is_palindrome = True i = 0 while len(letters) > 0 and is_palindrome: if letters[0] != letters[-1]: is_palindrome = False else: letters.pop(0) if len(letters) > 0: letters.pop(-1) return is_palindrome
And .... second:
def is_palindrome(word): letters = list(word) is_palindrome = True for letter in letters: if letter == letters[-1]: letters.pop(-1) else: is_palindrome = False break return is_palindrome
str1=str(input('enter string:')) save=str1 revstr=str1[::-1] if save==revstr: print("string is pailandrom") else: print("not pailadrom")
# We are taking input from the user. # Then in the function we are reversing the input i.e a using # slice [::-1] and # storing in b # It is palindrome if both a and b are same. a = raw_input("Enter to check palindrome:") def palin(): #Extended Slices to reverse order. b = a[::-1] if a == b: print "%s is palindrome" %a else: print "%s is not palindrome" %a palin()
this would be much simpler:
def palindrome(num): a=num[::-1] if num==a: print (num,"is palindrome") else: print (num,"is not palindrome") x=input("Enter to check palindrome:") palindrome(x)
a="mom" b='mom'[::-1] # reverse the string if a==b: # if original string equals to reversed print ("palindrome ") else: print ("not a palindrome ")
def palindrome(a): a=raw_input('Enter :') b=a[::-1] return a==b