'''A program demonstrating the performance benefit of using a set over a list. Author: Sean Barker, CSCI 1101B''' from time import perf_counter import sys # number of searches in a single experiment NUM_TRIALS = 1000 def run_trials(collection): '''Repeatedly search the given collection (either a list or set) for numbers using the 'in' operator.''' # record the current time t_start = perf_counter() # run the set of trials for i in range(NUM_TRIALS): trial_result = i in collection # search for a number in the list/set # calculate how long the trials took duration = perf_counter() - t_start print('Trials took {0:2f} msec\n'.format(duration * 1000)) # display output immediately (don't worry about this line) sys.stdout.flush() def main(): '''Prompt the user for a number of elements, then run a set of search trials using a list, then a set.''' finished = False while not finished: num_items_str = input('Enter the number of elements to test: ') if num_items_str == 'quit': finished = True else: num_items = int(num_items_str) print('Running trials using list...') nums_list = [0] * num_items run_trials(nums_list) print('Running trials using set...') nums_set = set([0] * num_items) run_trials(nums_set) main()