# count21.py # A function to count all the 21's in a list of numbers # P. Conrad for CS5nm 11/17/08 # 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) # consume: a list of anything # produce: boolean, True if the list is empty, otherwise False def isEmpty(myList): return len(myList)==0 def first(myList): return myList[0] def rest(myList): return myList[1:] # consumes: a list of numbers # produce: an int, how many 21s are in the list def count21(myList): if (isEmpty(myList)): return 0 else: if (first(myList) == 21): return 1 + count21(rest(myList)) else: return 0 + count21(rest(myList)) check_expect("count21([21, 3, 4, 5, 21]", count21([21, 3, 4, 5, 21]), 2) check_expect("count21([21, 3, 4])", count21([21, 3, 4]), 1) check_expect("count21([])", count21([]), 0)