The Next Palindrome number

前端 未结 11 1745
走了就别回头了
走了就别回头了 2021-01-17 07:23

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 n

相关标签:
11条回答
  • 2021-01-17 07:27
    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

    0 讨论(0)
  • 2021-01-17 07:29

    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.
    
    0 讨论(0)
  • 2021-01-17 07:33
    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))
    
    0 讨论(0)
  • 2021-01-17 07:35

    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)
    
    0 讨论(0)
  • 2021-01-17 07:40

    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
    
    0 讨论(0)
  • 2021-01-17 07:43

    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

    0 讨论(0)
提交回复
热议问题