def count_beans(filename): '''Return a list giving the number of beans of each color recorded in filename. Each entry in the list is a two-element list of the bean color and the number of occurrences of that color.''' color_counts = [] data_file = open(filename) for line in data_file: color = line.strip() # throw away the ending newline (\n) color_found = False # whether I've located the right color # look through color_counts for color for entry in color_counts: # check if the color of entry is the right one if entry[0] == color: # this is the color we want entry[1] += 1 color_found = True if not color_found: # didn't find the right color # first color of this bean -> add a new entry to list color_counts.append([color, 1]) data_file.close() return color_counts def count_beans_dict(filename): '''Return a dictionary mapping colors to the number of occurrences of that color in filename.''' color_counts = {} data_file = open(filename) for line in data_file: color = line.strip() # throw away the ending newline (\n) # equivalent to the longer section of code below color_counts[color] = color_counts.get(color, 0) + 1 # if color in color_counts: # we've seen the color before # color_counts[color] += 1 # else: # haven't seen the color before # color_counts[color] = 1 data_file.close() return color_counts def count_values(dictionary): '''return the number of unique values in dictionary''' return len(set(dictionary.values())) # longer version of the same thing below # values_set = set() # create an empty set # for key in dictionary: # values_set.add(dictionary[key]) # return len(values_set)