Can someone give some examples for recursion function in python in addition to factorial? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 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.

25th Aug 2019, 2:26 PM
thilina
5 Answers
+ 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.
25th Aug 2019, 2:37 PM
HonFu
HonFu - avatar
+ 6
For recursion you can find here a code that is doing flattening of lists https://code.sololearn.com/cXmQkFaVugME/?ref=app
25th Aug 2019, 3:01 PM
Lothar
Lothar - avatar
+ 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".
25th Aug 2019, 3:05 PM
Schindlabua
Schindlabua - avatar
+ 2
Thanks everyone.
25th Aug 2019, 6:23 PM
thilina
+ 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.
25th Aug 2019, 6:29 PM
thilina