I want to have a function that will return the reverse of a list that it is given -- using recursion. How can I do that?
相关问题
- how to define constructor for Python's new Nam
- streaming md5sum of contents of a large remote tar
- How to get the background from multiple images by
- PHP Recursively File Folder Scan Sorted by Modific
- Evil ctypes hack in python
Append the first element of the list to a reversed sublist:
Using Mutable default argument and recursion :
additional info
Recursion part is
hello(x[:-1])
where its calling hello function again afterx[:-1]
I know it's not a helpful answer (though this question has been already answered), but in any real code, please don't do that. Python cannot optimize tail-calls, has slow function calls and has a fixed recursion depth, so there are at least 3 reasons why to do it iteratively instead.
Use the Divide & conquer strategy. D&C algorithms are recursive algorithms. To solve this problem using D&C, there are two steps:
Step 1: Figure out the base case. What’s the simplest list you could get? If you get an list with 0 or 1 element, that’s pretty easy to sum up.
Step 2: You need to move closer to an empty list with every recursive call
for example
Source : Grokking Algorithms
A bit more explicit:
This turns into:
Which turns into:
Which is the same as another answer.
Tail recursive / CPS style (which python doesn't optimize for anyway):
This will reverse a nested lists also!
Padmal's BLOG