Newb18
Newb18

Reputation: 167

Python Palindrome

So my task is to see and check a positive integer if its a palindrome. I've done everything correctly but need help on the final piece. And that the task of generating a new a palindrome from the one given given by the user. Am i on the right track with the while loop or should i use something else? So the result is if you put 192 it would give back Generating a palindrome.... 483 867 1635 6996

"""Checks if the given, positive number, is in fact a palindrome"""

def palindrome(N):
    x = list(str(N))
    if (x[:] == x[::-1]):
        return True
    else: return False 

"""Reverses the given positive integer"""

def reverse_int(N):
    r = str(N)
    x = r[::-1]
    return int(x)


def palindrome_generator():
    recieve = int(input("Enter a positive integer. "))
    if (palindrome(recieve) == True):
        print(recieve, " is a palindrome!")
    else:
        print("Generating a palindrome...")
        while palindrome(recieve) == False:
            reverse_int(recieve) + recieve

Upvotes: 4

Views: 1919

Answers (3)

ART GALLERY
ART GALLERY

Reputation: 540

I've been using this solution for many years now to check for palindromes of numbers and text strings.

    def is_palindrome(s):
        s = ''.join(e for e in str(s).replace(' ','').lower() if e.isalnum())
        _len = len(s)
        if _len % 2 == 0:
            if s[:int(_len/2)] == s[int(_len/2):][::-1]:
                return True
        else:
            if s[int(_len/2+1):][::-1] == s[:int(_len/2)]:
                return True
        return False

Upvotes: 1

u-betcha
u-betcha

Reputation: 1

This one is using Complement bitwise and Logical AND and OR operators

_input = 'Abba'                    # _input = 1221

def isPalindrome(_):
    in_str = str(_).casefold()      # Convert number to string + case insensitive
    for _ in range(int(len(in_str) / 2)): # Loop from 0 till halfway
        if in_str[_] != in_str[~_]:
            return False
        return True

print(_input, isPalindrome(_input) and ' is palindrome' or ' is not palindrome')

Abba is palindrome

Upvotes: -1

Jasper
Jasper

Reputation: 3947

If I understand your task correctly, the following should do the trick:

def reverse(num):
    return num[::-1]

def is_pal(num):
    return num == reverse(num)

inp = input("Enter a positive number:")

if is_pal(inp):
    print("{} is a palindrome".format(inp))
else:
    print("Generating...")
    while not is_pal(inp):
        inp = str(int(inp) + int(reverse(inp)))
        print(inp)

The variable inp is always a string and only converted to int for the arithmetic.

Upvotes: 4

Related Questions