'''lecture_34_sum_list.py Use recursion to sum a list Oliver W. Layton CS 151: Computational Thinking: Visual Media Fall 2020 ''' def sum(list): if len(list) == 1: # base case return list[0] else: # first item + sum of the rest return list[0] + sum(list[1:]) if __name__ == '__main__': # print(sum([1, 4, 3])) # print(sum([4, 1, 95, 100])) # print(sum([4])) # one function symbol table # print(sum([4, 1])) # two function symbol tables print(sum([4, 1, 3])) # three function symbol tables (see below) # 1st call: list = [4, 1, 3], list[0] = 4, list[1:] = [1, 3] # 2nd call: list = [1, 3], list[0] = 1, list[1:] = [3] # 3rd call: list = [3], list[0] = 3, -> we hit return list[0] and backtrack