-1

I am beginner in programming, So can you please tell me what's wrong with my code?

I want to print next palindrome number if the number entered by the user (n) is not palindrome

n = int(input("Enter any number :- "))

reverse = 0
temp = n

while (n!=0):
    reverse = reverse * 10
    reverse = reverse + n%10
    n=n//10 
if(temp==reverse):
    print ("Already palindrome:: ")

if(temp != reverse):
     new_temp = temp
     new_reverse = 0
     for i in range(new_temp,new_temp+10):
        while(temp != 0):
            new_reverse = new_reverse * 10
            new_reverse = new_reverse + temp%10
            temp = temp//10
         if(new_temp==new_reverse):
             print ("Next pallindrome is :- ",new_temp)
             break
         if(new_temp != new_reverse):
             temp = new_temp+1
AMC
  • 2,642
  • 7
  • 13
  • 35
J.Smith.JJJ
  • 199
  • 2
  • 2
  • 9
  • 1
    What input are you giving it, and what is the expected output and the actual output? – David Grayson Sep 02 '14 at 05:34
  • Let say 'n' is 210 So, the next palindrome should be 212 but the output is none. – J.Smith.JJJ Sep 02 '14 at 05:35
  • And what about your indentation? Is it just here or even while compiling it? – Nabin Sep 02 '14 at 05:35
  • @Nabin Just here.. let me correct it.. – J.Smith.JJJ Sep 02 '14 at 05:36
  • 2
    No you still don't have correct indentation. Check after _if_ where you are printing "NExt pallindrome is" – Nabin Sep 02 '14 at 05:38
  • And also next _if_ where you increment temp – Nabin Sep 02 '14 at 05:39
  • You're getting pretty mixed up between new_temp and temp in that loop. For example, notice that `new_temp` is never changing (you're just changing temp). – David Robinson Sep 02 '14 at 05:54
  • Your life will be easier if you write a function that tests if a number is a palindrome. This will make the loop to test the next number very simple. – M Oehm Sep 02 '14 at 06:00
  • 1. code debug is offtopic here you can try it on code review 2. if you convert n to string and test/increment the string directly ... the code will be smaller,simpler and also more efficient – Spektre Sep 02 '14 at 06:05
  • In your logic, `reverse = n`, because at any point you are taking the LSB and making it the LSB of `reverse`. Try again. Also, your indentation is incorrect. Please go through the indentation first. – ssm Sep 02 '14 at 06:35
  • http://stackoverflow.com/a/40329385/4785824 please have a look on my python code – quintin Oct 30 '16 at 13:02

12 Answers12

4

To check if a number is a palindrome, you don't need to convert it to a number. In fact, its a lot simpler if you just check the string equivalent of your number.

>>> i = '212'
>>> i == i[::-1]
True
>>> i = '210'
>>> i == i[::-1]
False

Use this to your advantage, and create a function:

def is_palindrome(foo):
   return str(foo) == str(foo)[::-1]

Next, to find the next palindrome, simply increment the number till your palindrome check is true.

Combine all that, and you have:

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

n = raw_input('Enter a number: ')
if is_palindrome(n):
   print('Congratulations! {0} is a palindrome.'.format(n))
else:
   n1 = n
   while not is_palindrome(n1):
       n1 = int(n1)+1
   print('You entered {0}, but the next palindrome is {1}'.format(n, n1))

Here is how it works:

$ python t.py
Enter a number: 123
You entered 123, but the next palindrome is 131
$ python t.py
Enter a number: 121
Congratulations! 121 is a palindrome.
Burhan Khalid
  • 169,990
  • 18
  • 245
  • 284
4

There are two problems with your code.

1) Your "for i in range" loop calculates the reverse of the temp variable, but you don't change the temp variable's value. You do

 new_temp = temp
 for i in range(new_temp,new_temp+10):
    [SNIP]
    if(new_temp != new_reverse):
         temp = new_temp+1 #this value never changes.

So you're making 10 iterations with one and the same value.

2) Ten iterations might not be enough to find a palindrome. Keep going until you find a palindrome.

Working code:

def reverse(num):
    reverse= 0
    while num:
        reverse= reverse*10 + num%10
        num= num//10
    return reverse

num= int(input("Enter any number :- "))
if num==reverse(num):
    print ("Already palindrome.")
else:
    while True:
        num+= 1
        if num==reverse(num):
            print ("Next palindrome is : %s"%num)
            break
Aran-Fey
  • 39,665
  • 11
  • 104
  • 149
  • it will not work if the number is large like this "1740948824551711527614232216857618927954312334113874277931986502860248650900613893446066184963788291" – Sibaram Sahu Sep 04 '22 at 03:55
2

If it helps, I believe it's possible to solve this problem with n/2 iterations where n is the length of the input number. Here's my solution in Python:

def next_palin_number(number):
    number+=1
    # Convert the number to a list of its digits.
    number = list(str(number))
    # Initialize two indices for comparing symmetric digits.
    i = 0
    j = len(number) - 1
    while i < j:
        # If the digits are different:
        if number[i] != number[j]:
            # If the lower-power digit is greater than the higher-power digit:
            if int(number[j]) > int(number[i]):
                if number[j-1]!='9':
                    number[j - 1] = str(int(number[j - 1]) + 1)
                    number[j] = number[i]
                else:
                    number = list(str(int(''.join(number[:j]))+1))+number[j:]
            else:
                number[j] = number[i]
        i += 1
        j -= 1
    # Concatenate and return the result.
    return "".join(number)
Deepak Sai
  • 33
  • 6
  • Nice. But you don't need to convert the digits to `int` to compare them. – PM 2Ring Jul 19 '15 at 09:00
  • True you don't, but I like the fact that you do - it makes the point explicit rather than relying on the fact that lexicographic ordering gives the same order as int comparison for digits. I have a bee in my bonnet about `<` or `>` on strings... :) However, abandoning the conversion ***may*** be quicker... – J Richard Snape Jul 19 '15 at 09:25
0

If a definite range is given:

# function to check if the number is  a palindrome
def palin(x):                 
    s=str(x)
    if s==s[::-1]:
        return True
    else:
        return False

n=int(input("Enter the number"))
# Putting up range from the next number till 15 digits
for i in range(n+1,int(10e14)):
    if palin(i) is True:
        print(i)
        break
tripleee
  • 175,061
  • 34
  • 275
  • 318
Abhishek Roy
  • 89
  • 1
  • 3
0

This problem has a wonderful number of ways to solve them.

One of them is

def nearest_palindrome(number):
    #start writitng your code here
    while True:
        number+=1
        if str(number) == str(number)[::-1]:
            return number 

number=12300
print(nearest_palindrome(number))

Thanks for your time to read my answer : )

Ash Upadhyay
  • 1,796
  • 2
  • 15
  • 20
0
def nearest_palindrome(number):
    n = len(str(number))//2
    if(len(str(number)) % 2 == 0):
        #number like 1221
        number_1 = int((str(number))[:n]) #12
        number_2 = int((str(number))[n:]) #21
        if(number_1 < number_2):
            number_1 += 1
            number_2 = int(str(number_1)[::-1])
        else:
            number_2 = int(str(number_1)[::-1])
        # if last half part is zero then just reverse the first number
        if number_2 == 0:
            number_2 = str(number_1)[::-1]
        #combining the both parts
        ans = int(str(number_1) + str(number_2))
        return ans
    else:
        #numer like 12510   n=2
        nu = int((str(number))[:n+1]) #add in this number
        number_1 = int((str(number))[:n])  # 12
        number_2 = int((str(number))[n+1:])  # 21
        if (number_1 < number_2):
            nu += 1
            number_2 = int((str(nu))[::-1][1:])
        else:
            number_2 = int((str(nu))[::-1][1:])
        #if last half part is zero then just reverse the first number
        if number_2 == 0:
            number_2 = str(nu)[::-1]
            number_2 = number_2[1:]
        #combinning both parts
        ans = int(str(nu) + str(number_2))
        return ans
number=12331
print(nearest_palindrome(number))
tripleee
  • 175,061
  • 34
  • 275
  • 318
0

I have written this for finding next pallindrome number given a pallindrome number.

def palindrome(num):
    bol=False
    #x=len(str(num))
    num=num+1
    while(bol==False):
        if(check_palindrome(num)):
            bol=True
        else:
            num=num+1
    return num
def check_palindrome(n):
    temp=n
    rev=0
    while(n>0):
        dig=n%10
        rev=rev*10+dig
        n=n//10
    if(temp==rev):
        return True

b=palindrome(8)
print(b)
0
def next_palin_drome(n):
    while True:
        n+=1
        if str(n) == str(n)[::-1]:
            return n 

n=12231
print(next_palin_drome(n))

output:12321

DennisLi
  • 3,915
  • 6
  • 30
  • 66
  • 2
    Please explain why your solution works and how it helps those who are also encountering the same issue as the OP. https://stackoverflow.com/help/how-to-answer – Marcello B. Feb 18 '20 at 04:00
0
def nearest_palindrome(number):

    for i in range(1,number):
        number=number+1
        tem=str(number)
        tem1=tem[-1::-1]
        if(tem==tem1):
            return number
        else:
            continue

number=12997979797979797

print(nearest_palindrome(number))
0

A brute force method:

def math(n):
    while not var:
        n += 1   
        if str(n) == str(n)[::-1] : f = 'but next is : '+str(n); return f
n = int(input()); t = math(n); print('Yes',t) if str(n) == str(n)[::-1] else print('No',t); global var; var = False
Hexay
  • 1
  • 1
0

This is a good fast solution. I saw that the other solutions were iterating and checking through every +1 they did, but this is really slow for big numbers.

This solution has O(n) time if you look at the length of the number

beginNumber = 123456789101112131415161718 #insert number here for next palidrome
string = str(beginNumber + 1) 
length = len(string)
number= [int(x) for x in list(string)]

for i in range(length//2):
    if (number[i] != number[length-1-i]):
        if (number[i]<number[length-1-i]):
            number[length-2-i] += 1
            
        number[length-1-i] = number[i]
            
print("".join([str(x) for x in number]))
jeff
  • 1
  • 1
-2

I have written this for finding next pallindrome number given a pallindrome number.. #given a pallindrome number ..find next pallindrome number input=999 inputstr=str(input)

inputstr=inputstr
#append 0 in beginning and end of string ..in case like 99 or 9999
inputstr='0'+inputstr+'0'
length=len(inputstr)
halflength=length/2;
#if even length
    if(length%2==0):
    #take left part and reverse it(which is equal as the right part )
    temp=inputstr[:length/2]
    temp=temp[::-1]
    #take right part of the string ,move towards lsb from msb..If msb is 9 turn it to zero and move ahead
    for j,i in enumerate(temp):
        #if number is not 9 then increment it and end loop
        if(i!="9"):
            
            substi=int(i)+1
            temp=temp[:j]+str(substi)+temp[j+1:]
            break;
        else:
            
            temp=temp[:j]+"0"+temp[j+1:]
    #now you have right hand side...mirror it and append left and right part
    output=temp[::-1]+temp
#if the length is odd
    if(length%2!=0 ):
    #take the left part with the mid number(if length is 5 take 3 digits
        temp=inputstr[:halflength+1]
    #reverse it
        temp=temp[::-1]
    #apply same algoritm as in above
    #if 9 then make it 0 and move on
    #else increment number and break the loop
        for j,i in enumerate(temp):
        
            if(i!="9"):
            
                substi=int(i)+1
                temp=temp[:j]+str(substi)+temp[j+1:]
                break;
            else:
            
                temp=temp[:j]+"0"+temp[j+1:]
    #now the msb is the middle element so skip it and copy the rest
        temp2=temp[1:]
    #this is the right part mirror it to get left part then left+middle+right isoutput
        temp2=temp2[::-1]
        output=temp2+temp
    print(output)


    

similarly for this problem take the left part of given number ...reverse it..store it in temp

  inputstr=str(number)
    if(inputstr==inputstr[::-1])
        print("Pallindrome")
    else:
        temp=inputstr[:length/2]
        temp=temp[::-1]
        for j,i in enumerate(temp):
                
                if(i!="9"):
                
                    substi=int(i)+1
                    temp=temp[:j]+str(substi)+temp[j+1:]
                    break;
                else:
                
                    temp=temp[:j]+"0"+temp[j+1:]
    now depending on length of your number odd or even generate the output..as in the code
    if even then output=temp[::-1]+temp
    if odd then  temp2=temp1[1:]
                 output=temp2[::-1]+temp

    

I am not sure about this solution..but hope it helps

Saif
  • 1
  • 1