# countingOddNumbers.py P. Conrad for CS5nm, 11/10/08 # Three different ways to write isEven. # All of these will produce the same results # The shortest version # consumes: n, an integer # produces: True if n is even, otherwise False def isEven(n): return (n%2==0) # consumes: n, an integer # produces: True if n is odd, otherwise False def isOdd(n): return not isEven(n) # consumes: myList, an list of integers # produces: a count of how many integers in the list are odd def countOdd(myList): if (len(myList)==0): return 0 elif (len(myList==1) and isOdd(myList[0])): return 1 elif (len(myList==1) and not isOdd(myList[0])): return 0 else: # split the list into the first and the rest, and add them together return(countOdd([myList[0]]) + countOdd(myList[1:]) # This next version (howManyOdd) works the same way, except # the last line. Keep in mind that both countOdd (above) and # howManyOdd both take a "list of integers". We can't pass in a single # integer and expect the function to work. So, we can't pass in myList[0] # which is of type int. We have to pass in [myList[0]], which is a list # with a single item in it. Another way is myList[0:1] which is a list with # a single item in it (namely the item that is in position [0]). # consumes: myList, an list of integers # produces: a count of how many integers in the list are odd def howManyOdd(myList): if (len(myList)==0): return 0 elif (len(myList==1) and isOdd(myList[0])): return 1 elif (len(myList==1) and not isOdd(myList[0])): return 0 else: # split the list into first and rest, and add them together return(howManyOdd(myList[0:1]) + howManyOdd(myList[1:])