Can someone give some examples for recursion function in python in addition to factorial?

I understand how this recursion func works.but i don't know what are the uses.

8/25/2019 2:26:12 PM


6 Answers

New Answer


It is said that you can rewrite every loop as a recursion. Loops are usually quicker and more memory-efficient (although some languages seem to be optimized for recursion), but recursion is usually easier to read and write - if you have a firm grasp of recursion, that is. ;-) I had a bit of trouble myself understanding and writing recursion, so I have written quite a few of recursive mini codes for practice. Just search my codes with 'recursive' and you should get them all: max, pow, permutations etc.


For recursion you can find here a code that is doing flattening of lists https://code.sololearn.com/cXmQkFaVugME/?ref=app


It's one of those things you rarely need until you need it. Imagine you are writing a calculator and it has a function called `evaluate` that takes an expression like `4*(1+2+3)/8` and returns a number. Obviously you have to do the stuff in parentheses first, and that is just another calculation. So probably `evaluate("4*(1+2+3)/8")` will call itself recursively, like `evaluate("1+2+3")`. Then you are left with `4*6/8` which should be easy. Through recursion your calculator can do parentheses "for free".


def func(x): if x==0: return 0 else: return x +=func(x-1) func(5) # x == x+func(4)+func(3)+func(2)+func(1) # x == 5+4+3+2+1+0 # this is the example of recursion


Thanks everyone.


Found this one from the comment section. The one who pasted this is Werikas 7. return 5 * factorial(4) | return 4 * factorial(3) | return 3 * factorial(2) | return 2 * factorial(1) | return 1 | return 2 * 1 | return 3 * 2 | return 6 * 4 | return 24 * 5 | return 120 It was really helpful for me to understand what recursion is.