+ 3
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.
6 Respuestas
+ 7
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.
+ 6
For recursion you can find here a code that is doing flattening of lists
https://code.sololearn.com/cXmQkFaVugME/?ref=app
+ 3
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".
+ 2
Thanks everyone.
+ 1
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.