Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reverse an int in python?

Tags:

python

reverse

I'm creating a python script which prints out the whole song of '99 bottles of beer', but reversed. The only thing I cannot reverse is the numbers, being integers, not strings.

This is my full script,

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

def plural(word, b):
    if b != 1:
        return word + 's'
    else:
        return word

def line(b, ending):
    print b or reverse('No more'), plural(reverse('bottle'), b), reverse(ending)

for i in range(99, 0, -1):
    line(i, "of beer on the wall")
    line(i, "of beer"
    print reverse("Take one down, pass it around")
    line(i-1, "of beer on the wall \n")

I understand my reverse function takes a string as an argument, however I do not know how to take in an integer, or , how to reverse the integer later on in the script.

like image 605
Matthew C Avatar asked Jul 25 '14 10:07

Matthew C


People also ask

How do you reverse input in Python?

Use reversed() Method to Reverse a String in Python The program created above has a function that takes the input string as a parameter, and then you have used the reversed() method on the input string to return a reversed iterator or object.

How do you reverse an integer?

Reverse an Integer In each iteration of the loop, the remainder when n is divided by 10 is calculated and the value of n is reduced by 10 times. Inside the loop, the reversed number is computed using: reverse = reverse * 10 + remainder; Let us see how the while loop works when n = 2345 .

How do you reverse an int list in Python?

Using reversed() we can reverse the list and a list_reverseiterator object is created, from which we can create a list using list() type casting. Or, we can also use list. reverse() function to reverse list in-place.


2 Answers

Without converting the number to a string:

def reverse_number(n):
    r = 0
    while n > 0:
        r *= 10
        r += n % 10
        n /= 10
    return r

print(reverse_number(123))
like image 107
Alberto Avatar answered Sep 29 '22 03:09

Alberto


You are approaching this in quite an odd way. You already have a reversing function, so why not make line just build the line the normal way around?

def line(bottles, ending):
    return "{0} {1} {2}".format(bottles, 
                                plural("bottle", bottles), 
                                ending)

Which runs like:

>>> line(49, "of beer on the wall")
'49 bottles of beer on the wall'

Then pass the result to reverse:

>>> reverse(line(49, "of beer on the wall"))
'llaw eht no reeb fo selttob 94'

This makes it much easier to test each part of the code separately and see what's going on when you put it all together.

like image 36
jonrsharpe Avatar answered Sep 29 '22 04:09

jonrsharpe