George Putin
George Putin

Reputation: 29

How to do check for a palindrome in Python?

Hi I'm working on a python function isPalindrome(x) for integers of three digits that returns True if the hundreds digit equals the ones digit and false otherwise. I know that I have to use strings here and this is what I have:

def isPal(x):
    if str(1) == str(3):
        return "True"

    else:
        return "False"

the str(0) is the units place and str(2) is the hundreds place. All I'm getting is False? Thanks!

Upvotes: 1

Views: 1651

Answers (11)

Mithun B
Mithun B

Reputation: 21

A smaller solution for this would be:

def isPalindrome(x):    
    return str(x) == str(x)[::-1]

This will work for words and integer values.

Upvotes: 0

user3886969
user3886969

Reputation: 1

def is_palindrome() :
a=(raw_input("enter the name : "))
b=a[::-1]
    if b == a:
    print " it is palindarome"
    else:
    print "  it is not palindarome"

is_palindrome()

Upvotes: -1

aaronlevin
aaronlevin

Reputation: 1443

str() casts a value into a str. You want to access each character. You might want to benchmark a few different techniques.

>>> t1 = timeit.Timer(stmt="""\
... def isPal(x):
...     return x//100 == x%10
... isPal(434)
... isPal(438)
... """)
>>> t2 = timeit.Timer(stmt="""\
... def isPal(x):
...     return str(x)[0] == str(x)[2]
... isPal(434)
... isPal(438)
... """)
>>> print "%.2f usec/pass" % (1000000 * t1.timeit(number=100000)/100000)
0.97 usec/pass
>>> print "%.2f usec/pass" % (1000000 * t2.timeit(number=100000)/100000)
2.04 usec/pass

So, it looks like the mod technique works:

def isPal(x):
    return x//100 == x%10

Upvotes: 1

Mattie B
Mattie B

Reputation: 21309

Your problem is that str(1) == '1' and str(3) == '3'. You're also returning string values reading 'True' and 'False' instead of using the actual True and False values.

Let me propose a much simpler function for you:

def isPal(x):
    s = str(x)          # convert int to str
    return s == s[::-1] # return True if s is equal to its reverse

s[::-1] creates a reverse of the string; e.g. 'foo'[::-1] == 'oof'. This works because of extended slice notation.

Upvotes: 3

jmetz
jmetz

Reputation: 12803

Not sure why people are sticking to the string idea when division and modulo will do:

def isPal(x):
    return (x/100)%10 == x%10

if the number is no larger than 999 (3 digits as the OP stated) then it simplifies to

def isPal(x):
    return x/100 == x%10

Upvotes: 1

jamylak
jamylak

Reputation: 133744

Array access is done with [], not (). Also if you are looking for hundreds and units, remember that arrays are 0 indexed, here is a shortened version of the code.

def is_pal(num):
    return num[0] == num[2]

>>> is_pal('123')
False
>>> is_pal('323')
True

You might want to take in the number as a parameter and then convert it to a string:

def is_pal(num):
    x = str(num)
    return x[0] == x[2]

Note that you can simply just check if string is equal to it's reverse which works for any number of digits:

>>> x = '12321'
>>> x == x[::-1]
True

Upvotes: 6

codeling
codeling

Reputation: 11438

str(x) delivers the string value of whatever you pass to it, so in your case the string "1" or the string "3". But what you actually want is to access the 1st and 3rd digit of the given number. So, first you want to convert that number to string (e.g. with str(num)), and then you have to consider that indices in strings begin with 0, not with 1. So working code culd e.g. look like this:

def isPal(x):
  if str(x)[0] == str(x)[2]:
    return 'true'
  else:
    return 'false'

Output:

> isPal(101)
true
> isPal (203)
false

Upvotes: 0

Alexis Huet
Alexis Huet

Reputation: 765

It looks like you still need to study Python syntax

Here is a way to achieve what you need :

>>> def isPal(x):
...     x_as_str = str(x)
...     if len(x_as_str) != 3:
...         raise Exception("{} is not of length 3".format(x))
...     return x_as_str[0] == x_as_str[2]
...
>>> isPal(42)
Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "<input>", line 4, in isPal
Exception: 42 is not of length 3
>>> isPal(420)
False
>>> isPal(424)
True

Upvotes: 0

Jon Clements
Jon Clements

Reputation: 142236

str(1) will create a string of the integer value 1. Which won't equal the string value of the integer value 3 - so it's always False.

You should return True and False, rather than strings of "True" and "False"...

This is what you're aiming for taking into account the above... (which works with any length)

def pal(num):
    forward = str(num)
    backward = ''.join(reversed(forward))
    return forward == backward

Upvotes: 3

yedpodtrzitko
yedpodtrzitko

Reputation: 9359

you compare number 1 and 3, but you needt to compare index of input variable.

x = 1000
def isPal(x):
    return str(x[-1]) == str(x[-3]):

Upvotes: 0

Claudiu
Claudiu

Reputation: 229561

str(1) just gives you the string representation of the number 1:

>>> x = 357
>>> str(1)
'1'

What you want is the first index of the string representation of x.

>>> x = 357
>>> str(x)    #string representation of x
'357'
>>> str(x)[0] #first index of that
'3'
>>> str(x)[2] #third index of that
'7'
>>> str(x)[0]==str(x)[2] #compare 1st and last
False
>>> x = 525
>>> str(x)[0]==str(x)[2] #compare 1st and last
True

Upvotes: 0

Related Questions