Archive

Posts Tagged ‘integer’

Reverse an integer

September 29, 2010 3 comments

Exercise

Take an integer and reverse its digits. The result is also an integer. Example: 83657 becomes 75638.

Solution

#!/usr/bin/env python

def reverse_int(n):
    return int(str(n)[::-1])

n = 83657
print n                 # 83657
print reverse_int(n)    # 75638

Summary: convert the number to string, reverse the string, then convert it back to integer. Details: 83657 -> str(83657) returns "83657" which is a string -> reverse it, we get "75638" -> int("75638") converts it to an integer.

Notes

If you want to concatenate a string and an integer, first you need to convert the integer to string. Example:

n = 83657
print "The value of n is " + n          # error, won't work
print "The value of n is " + str(n)     # OK
Categories: python Tags: , ,

Pretty print an integer

September 24, 2010 2 comments

Exercise: Take an integer and print it in a pretty way, i.e. use commas as thousands separators. Example: 1977 should be 1,977.

Solution:

#!/usr/bin/env python

def numberToPrettyString(n):
    """Converts a number to a nicely formatted string.
       Example: 6874 => '6,874'."""
    l = []
    for i, c in enumerate(str(n)[::-1]):
        if i%3==0 and i!=0:
            l += ','
        l += c
    return "".join(l[::-1])
#

if __name__ == "__main__":
    number = 6874
    print numberToPrettyString(number)   # '6,874'

The idea is simple. Consider the number 1977. Convert it to string ("1977") and reverse it ("7791"). Start processing it from left to right and after every third character add a comma: "7" -> "77" -> "779," (comma added) -> "779,1". Now reverse the string ("1,977"). Done.

Links

Update (20131125)
There is an easier way. You can do it with string formatting too:

>>> n = 1977
>>> "{:,}".format(n)
'1,977'

Thanks to Krisztián B. for the tip.

Categories: python Tags: , , ,
Design a site like this with WordPress.com
Get started