Sum using recursion | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Sum using recursion

Hello, everybody! Could you please help me to improve this code: https://code.sololearn.com/cbYh89uaC379/#py I tried to wrote a code which using recursion to get the total amount of all number in list. I know that here can be used a cycle instead, but I learn a recursion method now. Thanks in advance!

13th Oct 2017, 5:49 AM
Denis Kuznetsov
Denis Kuznetsov - avatar
2 Answers
+ 1
Not bad! But if you make the zero length case return 0 (as you do in maths, it's the "empty sum") then you can get rid of the elif. def summ2(arr): if len(arr) == 0: return 0 else: return arr.pop(0) + summ2(arr) print (summ2([1,2,3,4,5]))
13th Oct 2017, 7:00 AM
Schindlabua
Schindlabua - avatar
+ 1
Oh, that's it! Thank you! I understand my mistake. I've tried to wrote similar, but I mistakingly put "arr.pop(0) + summ2(arr)" as argument of 'print' instead of 'return'. :) Thank you very much for your help!
13th Oct 2017, 7:21 AM
Denis Kuznetsov
Denis Kuznetsov - avatar