Here is the simple question: Please use recursion to revert 12345 to 54321
def reverse(val, new_val): if val == '': print(new_val) else: 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) else: 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 reverse_num.py Please provide any number: 12345 54321
But if you provide the number that end with 0, it will cause problem.
$ python reverse_num.py Please provide any number: 1343500 53431
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.