def count_beans(beans): '''Return a list giving the number of beans of each color. Each entry of the returned list is a two-element list consisting of the color and the count of that color.''' color_counts = [] for color in beans: found_color = False for color_count_pair in color_counts: if color_count_pair[0] == color: found_color = True color_count_pair[1] += 1 # increase existing counter for this color if not found_color: # first bean of this color, add a new entry color_counts.append([color, 1]) return color_counts def count_beans_v2(beans): '''Return a dictionary mapping colors to the number of beans of that color.''' color_counts = {} for color in beans: if color in color_counts: # is color an existing key of the dictionary? color_counts[color] += 1 # updating an existing key/value pair else: color_counts[color] = 1 # adding a new key/value pair return color_counts def count_beans_v3(beans): '''Return a dictionary mapping colors to the number of beans of that color.''' color_counts = {} for color in beans: color_counts[color] = color_counts.get(color, 0) + 1 return color_counts ############################## def count_values(some_dict): '''Return the number of unique values in the dictionary.''' values_set = set() for key in some_dict: values_set.add(some_dict[key]) return len(values_set) def count_values_v2(some_dict): '''Return the number of unique values in the dictionary.''' values_set = set() for value in some_dict.values(): values_set.add(value) return len(values_set) def count_values_v3(some_dict): '''Return the number of unique values in the dictionary.''' return len(set(some_dict.values()))