# reads in a list of numbers, prints the number of positive numbers # ECS 10, May 29, 2009 # Matt Bishop # read in a list of comma-separated numbers from the input # parameters: none # returns: 2 values # 1st: the list, if read successfully; empty list, if not # 2nd: True, if list read successfully; False, if not def getlist(): # read the input # catch any problems and bail out at once try: inp = input("Enter a comma-separated sequence of numbers: ") except (EOFError, TypeError, NameError, SyntaxError): return [], False # now check each element is a number # we actually build the list here lst = [] for i in inp: # number check: if adding 0 causes a TypeError, # it's not a number and we skip it (with a # suitable error message) try: i += 0 except TypeError: print i, "is not a number -- ignoring it" else: # it's a number -- add it to the list lst.append(i) # return results return lst, True # recursively count the number of positive integers in the list # parameters: lst, the list # returns: the number of positive integers in the list def poslist(lst): # base case: empty list has 0 positive elements if lst == []: return 0 # recursion here elif lst[0] > 0: # positive number: one more than are in rest of list return 1 + poslist(lst[1:]) else: # non-positive number: same as in the return poslist(lst[1:]) # this puts it all together def main(): # read in the list lst, okay = getlist() # if a valid list eas read, count the number # of positive elements in it if okay: print "There are", poslist(lst), "positive numbers in your list" main()