Python and simple recursion

This afternoon my husband and I talked about recursion, and we decided to write some recursion functions with different languages. He uses JavaScript, and I use Python.

Here is the simple question: Please use recursion to revert 12345 to 54321

def reverse(val, new_val):
    if val == '':
        reverse(val[:-1], new_val + val[-1:])

if __name__ == '__main__':
    reverse(raw_input('Please provide any number: '), '')

And the next question he gave to me is: Can you use operations to solve this problem instead of using string?

def reverse(num, new_num):
   if num/10 == 0:
     print(new_num*10 +num)
     reverse(num/10, (new_num*10 + num%10))

if __name__ == '__main__':
  reverse(input('Please provide any number: '), 0)

However, I found there’s a problem with running this function. It works when you provide a number like this:

$ python 
Please provide any number: 12345

But if you provide the number that end with 0, it will cause problem.

$ python 
Please provide any number: 1343500

Because the “Number” cannot start with zero.

Of course there’s a way to solve it, but it will be different from what we’re looking for from the second question. Not sure if I can figure out a better answer for the second question latter.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s