repl.it
@charles2588/

Recursive_SumofList

Python

No description

fork
loading
Files
  • main.py
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#Calculate the sum of list of numbers
def sumoflist(list,count):
	if len(list)==1:
		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
#Probable right way below:-
def sumoflistrecursive(listofitems):
	if len(listofitems)==1:
		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