Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reversing a list using recursion in python [duplicate]

def revlist(lst):
    if len(lst) == 1:
        return lst
    else:
        return lst[(len(lst) - 1)

I have come as far as this but I don't know what to do next. I'm practicing recursion for my exams. If anyone could help I'd be grateful.

like image 378
Ariel Waters Avatar asked Dec 15 '15 16:12

Ariel Waters


People also ask

How do you reverse a list without reverse method in Python?

In order to reverse a list without using the built-in reverse() function, we use the Slicing Operator. The slicing operator is another method used for reversing the data elements.

How do you reverse a list quickly in Python?

You can reverse a list in Python using the built-in reverse() or reversed() methods. These methods will reverse the list without creating a new list. Python reverse() and reversed() will reverse the elements in the original list object. Reversing a list is a common part of any programming language.

How do you reverse a list in Python indexing?

Python comes with a number of methods and functions that allow you to reverse a list, either directly or by iterating over the list object. You'll learn how to reverse a Python list by using the reversed() function, the . reverse() method, list indexing, for loops, list comprehensions, and the slice method.


1 Answers

Your simple case is fine, if the length of the list is 1 (or smaller), simply return the list. In fact, we can simply check whether the list is empty (by issueing if not lst). If the list is larger, you have to think about how to simplify the problem in the recursive case. In words, you can formulate it like this: If the list is longer than 1, give me the last element of that list extended by the list I get when I reverse the given list without the last element in it. The latter list is one smaller than the original list, thus the problem is simplified.

In code:

def reverse(lst):
    if not lst: # this will be true if lst == []
        return lst
    return lst[-1:] + reverse(lst[:-1]) # recursive case

# Demo
print(reverse([1,2,3,4,5])) # [5, 4, 3, 2, 1]
like image 130
timgeb Avatar answered Nov 15 '22 20:11

timgeb