Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
https://repl.it/C6wn/2 created by charles2588
#Calculate the sum of list of numbers
def sumoflist(list,count):
if len(list)==1:#Escape Clause
print(count+list[0])
return count+list[0]
else:
count+=list[0]
sumoflist(list[1:],count)
print(sumoflist([1,2,3,4,5],0))
#Wrong way of using recursion above
#Right way below:-
def sumoflistrecursive(listofitems):
if len(listofitems)==1:#Escape Clause
return listofitems[0]
return listofitems[0]+sumoflistrecursive(listofitems[1:])
print(sumoflistrecursive([1,2,3,4,5]))
#Time Complexity O(n) function calls
#Space Complexity Stack to save function call n return
Python 3.5.1 (default, Dec 2015, 13:05:11)
[GCC 4.8.2] on linux
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.