# find the total order size for different products if the orders are # specified as a line with a product name, and an optional comma and number # if the comma and number are missing, or the number is missing or not a # valid number, assume an order of 1 def orderTotals(src,dst) : s = open(src,"r") d = open(dst,"w") # put the orders in a dictionary # dictionaries are efficient for lookup, and the values are mutable # so as we get new orders we can update it # if this were written in 2016 and not 1992, we would not read from a # file, but would get orders live from the internet # in the live case, it is really important that we read the file line # by line, and using a dictionary lets us print a summary every hour, etc. orders = {} # this is new way of going through the lines in a file # when we use a for like this, the .readline() is hidden # just like the indexing into a list is also hidden when using a for for line in s : # we often use comma, space of tab separated files, and there is # a convenient way of turning each line into a list fields = line.split(',') # a "blank line" is not an empty string, it has a return '\n' # this will give us an empty first component, as would a line # ",anything", but in either case we can ignore this line if fields[0] != '' or fields[0] = '\n': # precondition: fields[0] is not empty # now check for there being a field which could be a number if len(fields) >= 2 : # and try to get a number out of it, but if that fails... try : numOrdered = int(fields[1]) except : # assume an order of 1 numOrdered = 1 else : # if there is no second field, also assume an order of 1 numOrdered = 1 # now check whether this thing has been ordered before, in # which case add to the current order, otherwise start counting if fields[0] in orders : orders[fields[0]] = numOrdered + orders[fields[0]] else : orders[fields[0]] = numOrdered # finally, we need to print out the total orders for item in orders : # note that try to avoid really dumb plurals, but allow somewhat # silly ones like grasss and octupuss if orders[item] > 1 : plural = "s" else : plural = "" d.write(str(orders[item]) + " " + item + plural + " ordered") # don't forget to put your toys away d.close() s.close()