Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where's the bug in this function to check for palindrome?

Given below is the code to check if a list is a palindrome or not. It is giving correct output 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
like image 416
praxmon Avatar asked Nov 29 '22 01:11

praxmon


2 Answers

You should return as soon as there is a mismatch. Also, you just need to iterate till half the length:

def function(...):
    ...
    for i in range (0, (len(num) + 1) / 2):
        if r[i] != num[i]:
            return False
    return True

BTW, you don't need that loop. You can simply do:

def palindrome(num):
    return num == num[::-1]
like image 82
Rohit Jain Avatar answered Dec 03 '22 08:12

Rohit Jain


This would be easier:

def palindrome(num):
    if num[::-1] == num:
       return True
    else:
       return False
like image 35
Synthetica Avatar answered Dec 03 '22 10:12

Synthetica