Skip to content

Commit 8c1948b

Browse files
committed
Create sum_list.py
1 parent 69ad6bd commit 8c1948b

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

sum_list.py

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
def sum_list(nums):
2+
""" Using recursion, return the sum of numbers in a list.
3+
4+
>>> sum_list([5, 5])
5+
10
6+
7+
>>> sum_list([-5, 10, 4])
8+
9
9+
10+
>>> sum_list([20])
11+
20
12+
13+
>>> sum_list([])
14+
0
15+
"""
16+
17+
# Runtime: O(n)
18+
# Spacetime: O(1)
19+
20+
if not nums:
21+
return 0
22+
23+
return nums[0] + sum_list(nums[1:])
24+
25+
26+
27+
if __name__ == '__main__':
28+
import doctest
29+
results = doctest.testmod()
30+
31+
if results.failed == 0:
32+
print "ALL TESTS PASSED!"

0 commit comments

Comments
 (0)