Sunday, August 21, 2011

python: reverse numbers

Recently i've looked for a nice way to reverse an int variable in python. I wanted to have a function which transforms for example "1234" into "4321". At the internet, i've found a nice math solution which worked flawless. It's code look's like:

def rev(val):
  if val < 10: return val
  else:
    expon = int(math.log10(val))
    ival = val%10
    dval = val/10
    return int(ival*math.pow(10,expon)) + rev(dval)

But today i tryed to make another, shorter solution. It has nothing todo with math. Actually i just take an int variable, convert it into string, reverse it, and convert it back into int. Really simple and it also works flawless:

def strrev(sval):
  if len(str(sval)) == 1: return sval
  else:
    strcon = str(sval)
    return int(strcon[::-1])


Now i'm wondering which function would be better and for what reason. I made some benchmarks and found out that the second solution is about 25% faster than the first one, but i just stoped these two version with "time". I think it's not good enough to take is as a benchmark. Besides that, i don't know anything about memory consumption. Anyway, i'll keep the second, since it's faster...

If someone wants to try it out, i've uploaded both "benchmark" script's. The scirpt generates every number from 1 to 100000, reverses every number and subtracts every number with it's reversed version. 

Download: Link

3 comments:

  1. شكرا لك واضيفلك اني كود اخر وسهل

    def reverse(strorint):
    if type(strorint) == str:
    return strorint[::-1]
    else:
    return int(str(strorint)[::-1])


    ReplyDelete
    Replies
    1. اي هذا الكود الكود يعكس ال str and int

      الارقام والكلمات

      Delete