purple21
purple21

Reputation: 9

how to define a palindrome

I'm trying to define a palindrome. This is what I have so far but I'm not sure what is next can someone please help me.

def palindrome(x):

    if x % 2==0:
        index1=0
        index2=0
        aString=str(x)
        number=len(aString)
        index1=number / 2
        index2=number / 2 -1
    else:
        index1=0
        index2=0
        aString=str(aString)
        number=len(aString)
        index1=number / 2 +1
        index2=number / 2 -1

Upvotes: 0

Views: 745

Answers (3)

Ricardo Altamirano
Ricardo Altamirano

Reputation: 15198

For checking if a word/string is a palindrome, this is sufficient, although as others have pointed out, it's a memory-expensive solution:

def ispal(s):
    return s == s[::-1]

To check if a number is a palindrome, several solutions exist (and my list is by no means exhaustive):

import math

def ispal(n):
    return str(n) == str(n)[::-1]

def ispal2(n):
    digits = math.floor(math.log10(n) + 1)
    for ex in range(1, math.ceil(digits/2)):
        leftdigit = math.floor(n / 10**(digits - ex)) % 10
        rightdigit = math.floor(n / 10**(ex - 1)) % 10
        if not(leftdigit == rightdigit):
            return False

    return True

Upvotes: 1

user1786283
user1786283

Reputation:

Try this:

def palindrone(x):
    return x == x[::-1]

For example:

>>palindrone("dad")
True

Upvotes: 1

lokoko
lokoko

Reputation: 5803

You could just try something like this :

sampleString[::-1] == sampleString

Upvotes: 2

Related Questions