# addingUpElementsOfAList.py # P. Conrad for CS5nm, 11/17/08 # Show how to add up all elements of a list of numbers using recursion # check_expect checks whether a function produces the expected result # consumes: # test: a string describing the test # check: the value we are testing (typically result of a function call) # expect: the value we are expecting (typically a literal value) # produces: # nothing (there is no return value) # side effect: # prints a message indicating whether the test passed or failed def check_expect(test,check,expect): if (check == expect): print "Test " + test + " passed." else: print "Test " + test + " failed: expected " + str(expect) + \ " but I got " + str(check) def isEmpty(myList): return len(myList)==0 def first(myList): return myList[0] def rest(myList): return myList[1:] # consumes: a list of numbers # produces: the sum of those numbers def sumListNums(myList): if (isEmpty(myList)): return 0 elif len(myList)==1: return first(myList) else: return first(myList) + sumListNums(rest(myList)) check_expect("sumListNums([2,3,4])", sumListNums([2,3,4]), 9) check_expect("sumListNums([])", sumListNums([]), 0)