# File: recurSumLists.py # Author: Dr. Gibson # Date: 11/10/2017 # Section: N/A # E-mail: k.gibson@umbc.edu # Description: # This file contains python code that has multiple # implementations of a recursive "list summer" function #################################################################### # recSumList1() sums a list by adding the first element to the rest # of the list recursively # Input: currList; a list of integers # Output: total of the list's contents def recSumList1(currList): # BASE CASE: list is empty, nothing more to sum together if len(currList) == 0: return 0 # RECURSIVE CASE: list is not empty, keep going else: # helps trace what's going on, but not necessary print("Adding", currList[0], "to", currList[1:] ) # RECURSIVE CALL: add first element to sum of rest of list return currList[0] + recSumList1( currList[ 1: ] ) ################################################################## # recSumList2() sums a list by keeping track of what index # we're at when adding the entire list together # Input: theList; a list of integers # currIndex; index of contents to be added in next # Output: total of the list's contents def recSumList2(theList, currIndex): # BASE CASE: reached the end of the list, stop adding if currIndex == len(theList): return 0 # RECURSIVE CASE: not at the end of the list, keep going else: # helps trace what's going on, but not necessary print("Now adding", theList[currIndex], "at index", currIndex) # RECURSIVE CALL: add current element, call on next one return theList[currIndex] + recSumList2(theList, currIndex + 1) def main(): myList = [3, 5, 8, 7, 2, 6, 1] print("\tAdding the list", myList, "together:") ans1 = recSumList1(myList) print("The sum of the list is", ans1) print("\n\tAdding a different way: ") # requires that we give starting index, so start at position 0 ans2 = recSumList2(myList, 0) print("The sum of the list is", ans2) main()