# # A function that computes the mode of a list # # Parameters: # data: list of data items # # Returns: # mode_value: the mode of the list # max_count: number of occurences of the mode # def mode(data): # # For each value in the list # counts = {} for i in data: # # If the item is already in the dictionary, increase its value by 1. # Otherwise, add it to the dictionary with a count of 1. # if (i in counts.keys()): counts[i] = counts[i] + 1 else: counts[i] = 1 # # if data is empty, set max_count to 0 (indicating no mode) # if (len(counts) == 0): mode_value = "" max_count = 0 else : # # Find the largest item count in the dictionary # max_count = max(counts.values()) # # Find the key that has the largest value # for i in counts.keys(): if (counts[i] == max_count): mode_value = i return (mode_value,max_count) def main(): # # Read all the values from the user and store them in a list # items = [] item = raw_input("Enter something (return to exit): ") while (item != ""): items.append(item) item = raw_input("Enter something (return to exit): ") (mode_value,mode_count) = mode(items) if (mode_count == 0): print "Empty list (no mode)" else: print "The mode of the list is",mode_value,"with a count of",mode_count main()