Python Forum
Input a number with any number of digits and output it in reverse order of digits.
Thread Rating:
  • 1 Vote(s) - 4 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Input a number with any number of digits and output it in reverse order of digits.
#1
hi, i'm a python beginner. few months ago i've started learning python and it's getting interesting to me everyday. So, today i need some help on an interesting problem. "Write a program to reverse the digits of a input number and check if the both numbers are equal or not". Now, i've written a code for "Reverse the digits of a five digit number", but i want to generalize this code for any digit number input. so, how to do it? i've learned so far operators, functions, decision making statements, looping, exception handling and modules to some extent. here is the code i've written for a number upto five digits-

sum1=0
n=int(input("Please enter five digit Number:"))
num=n
a=n%10
n=n//10
sum1=(sum1+(a*10000))

a=n%10
n=n//10
sum1=(sum1+(a*1000))

a=n%10
n=n//10
sum1=(sum1+(a*100))

a=n%10
n=n//10
sum1=(sum1+(a*10))


a=n%10
n=n//10
sum1=(sum1+(a*1))

print("Number:",sum1)
if (num==sum1):
    print("Input number and the reverse number are equal")
else:
    print("Input number and the reverse number are not equal")
    
please provide your valuable suggestions.. Smile
Reply
#2
num = 1234567
num1 = int(str(num)[::-1])
print('num: {}, num1: {}'.format(num, num1))
1st line you can replace this with your input statement.
2nd line - 1st convert num to  a string str(num)
then reverse the string with slice operation [::-1]
next re-convert result back to int int()


result:
Output:
num: 1234567, num1: 7654321
Reply
#3
thnx @Larz60+ for your kind response. though i haven't use this 'slicing' method or '.format()' function before, but i got the logic and that's pretty awesome. having said that, i'm wondering what other methods can be used also to solve this problem?
Reply
#4
If you for some reason do not want to use Larz60+ suggestion, you can do it directly by "removing" either first or last digit of the input number and use it to construct new "reversed" number.

num = 12345

rev_num = 0
while num:
    rev_num = 10 * rev_num + num % 10   # extracts last digit of num and "appends" to "shifted" rev_num
    num //= 10                          # just shortcut for num = num // 10 - removes "used" digit

print("num = {}, reversed num = {}".format(num, rev_num))
Output:
num = 0, reversed num = 54321
As you can see, it destroys the input number in a process of reverting it. If you need to keep your number, you need to use other variable (or you can put that reverting code into a function).

And if your only problem is to check whether number is a palindrome, then simple check based on Larz60+ code is enough:
str(num) == str(num)[::-1]
Reply
#5
Probably not what you're looking for, but howz about:

orig_num = [1, 2, 3, 4, 5]
list.sort(orig_num, reverse=True)

print("Reversed number = {}".format(orig_num))
Output:
Reversed number = [5, 4, 3, 2, 1]
If it ain't broke, I just haven't gotten to it yet.
OS: Windows 10, openSuse 42.3, freeBSD 11, Raspian "Stretch"
Python 3.6.5, IDE: PyCharm 2018 Community Edition
Reply
#6
Little necronitpicking:

sort with reverse keyword gives a list ordered in a reverse order, not a reversed list. For the number/list used as an example it does not matter, as it was ordered, but otherwise it could. Beside [::-1] it could be done with .reverse() or reversed().

As "reversing" list is equivalent to sorting it on index in decreasing order, I tried to abuse sort/sorted to get such result and ended with:

In [38]: a = [1, 2, 5, 3]

In [39]: sorted(a, key = lambda x, i=iter(range(len(a))) : -next(i))
Out[39]: [3, 5, 2, 1]
it looks ugly, but probably less ugly than:

In [41]: list(map(lambda x:x[1], sorted(enumerate(a), reverse=True)))
Out[41]: [3, 5, 2, 1]
Perhaps there are other ways how to reverse list with sort/sorted one-liner and built-ins ...
Reply
#7
Nitpicking the nitpicking, we are dealing with (immutable, by essence) strings here, without reverse or reversed methods. Since we need a new string to print the result anyway [::-1] is as good as it gets.
Unless noted otherwise, code in my posts should be understood as "coding suggestions", and its use may require more neurones than the two necessary for Ctrl-C/Ctrl-V.
Your one-stop place for all your GIMP needs: gimp-forum.net
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  If a set element has digits in the element tester_V 3 263 Mar-25-2024, 04:43 PM
Last Post: deanhystad
Brick Number stored as text with openpyxl CAD79 1 275 Mar-19-2024, 08:31 PM
Last Post: deanhystad
  [SOLVED] Pad strings to always get three-digit number? Winfried 2 326 Jan-27-2024, 05:23 PM
Last Post: Winfried
  Prime number detector Mark17 5 786 Nov-27-2023, 12:53 PM
Last Post: deanhystad
  Create X Number of Variables and Assign Data RockBlok 8 920 Nov-14-2023, 08:46 AM
Last Post: perfringo
  find the sum of a series of values that equal a number ancorte 1 490 Oct-30-2023, 05:41 AM
Last Post: Gribouillis
  capturing multiline output for number of parameters jss 3 805 Sep-01-2023, 05:42 PM
Last Post: jss
  Sequential number for rows retrieved and storing the Primary UKey to the line number GYKR 2 571 Aug-22-2023, 10:14 AM
Last Post: GYKR
  doubling a number Skaperen 8 1,206 Jul-25-2023, 10:20 PM
Last Post: Skaperen
Question Extracting Version Number from a String britesc 2 1,083 May-31-2023, 10:20 AM
Last Post: britesc

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020