Skip to content

Instantly share code, notes, and snippets.

@charles2588
Last active June 28, 2016 21:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save charles2588/3dfc24d746ea0fb62ebac4aa9a07e4dd to your computer and use it in GitHub Desktop.
Save charles2588/3dfc24d746ea0fb62ebac4aa9a07e4dd to your computer and use it in GitHub Desktop.
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