rggod
rggod

Reputation: 629

using recursion to reverse order of number in python

How would I use recursion to reverse the order of numbers. I have no idea where to even start off. Could someone help me a bit here. For example input =1,2,3,4 output=4,3,2,1

I've tried and this is what I've got, but it's still not working.

def reverseDisplay(number):
    new_list=" "
    if len(number)==1:
            new_list=number
    else:
            new_list=reverseDisplay(number[1:]) + number[0] + " "
            return new_list    

def main():
    number=float(input("Enter a number :"))
    print(reverseDisplay(number))
main()

Upvotes: 1

Views: 5478

Answers (6)

Seetha Lakshmi
Seetha Lakshmi

Reputation: 1

def revr(n,r=0):
    if n==0:
        return r
    else :
        r=(r*10)+n%10
        return revr(n//10,r)

Upvotes: 0

GIRISH RAMNANI
GIRISH RAMNANI

Reputation: 624

In python 3,

def revRecur(n,ro=0):
if n//10==0:
    return (ro*10)+n
else:
    return revRecur(n//10,(10*ro)+(n%10))

print(revRecur(12345))

Upvotes: 1

uselpa
uselpa

Reputation: 18917

The reasoning goes like this:

  1. if the list is empty, rev([]) is also [] - this is called the "base case"
  2. otherwise, reverse the rest (the list except the first element) and append the first element to that

so that

  rev ([1, 2, 3, 4])
= rev (   [2, 3, 4])                   + [1]
= rev (      [3, 4])             + [2] + [1]
= rev (         [4])       + [3] + [2] + [1]
= rev (          []) + [4] + [3] + [2] + [1]
=                []  + [4] + [3] + [2] + [1]

or, in Python

def rev(lst):
    if lst: # list is not empty
        return rev(lst[1:])+[lst[0]]
    else:   # list is empty
        return []

Upvotes: 4

user2555451
user2555451

Reputation:

Your question is a little ambiguous. People don't know if you mean to reverse a list of integers or a string of digits (since you are using input, I think it is the later).

However, I made a solution for each, so you can pick whichever you want:

>>> # For the list
>>> def rev(l):
...     return l and rev(l[1:]) + [l[0]]
...
>>> rev([1, 2, 3, 4])
[4, 3, 2, 1]
>>> rev([1, 2, 3, 4, 5, 6, 7, 8, 9])
[9, 8, 7, 6, 5, 4, 3, 2, 1]
>>>
>>> # For the digits
>>> def rev(n):
...     return n and rev(n[1:]) + n[0]
...
>>> rev('123')
'321'
>>> rev('123456789')
'987654321'
>>>

Upvotes: 0

c1phr
c1phr

Reputation: 590

This looks like homework, so I won't really give a full solution, but I'll provide a way to get there. If the numbers are being taken in as a list, then we can break down our solution as such:

if rest(lst).length == 0: #Check to see if we're down the first item
    return lst
else: #We need to break the list down some more
    return "call the method again on the rest of the list" + [first(lst)]
  1. Break down the list into individual values
  2. When we get down to a single item, start building the list back up (Base Case)

With Python, using stuff + [item] will concatenate lists together (so long as "stuff" is another list). The else block above will call the recursive function to break down the list, and as it begins to return up the recursive dive, it will concatenate on the first item in the list in reverse order. This return up the dive occurs when the you get down to the singleton list, which the if block catches.

Upvotes: 0

James McDonnell
James McDonnell

Reputation: 3710

Write a method to take a number or list. If the length of that parameter is one, return the number, if not call the same method with the list without the first digit. Then return whatever that call returns plus the first digit appended to the end.

Upvotes: 0

Related Questions