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!
2 ответов
+ 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]))
+ 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!