''' Purpose: implements the di.py problem on test 2 ''' def ction( x ) : # Takes in a list x (like x1 = ['m', 'i', 'm', 'i', 'c']) # and it will build and return a dictionary where each element in x is mapped to # the number of times it occurs in the list x # m is mapped to 2, i is mapped to 2, c is mapped to 1 # Initialize a dictionary accumulator (we will add mappings to this dictionary) counting_dictionary = {} for element in x: number_copies_element = x.count( element ) # Store the count of element in x in number_copies_element # Put it in our dictionary if ( element not in counting_dictionary ): # Check to make sure we map each unique element once to its count counting_dictionary[ element ] = number_copies_element # Create a mapping of the element to the count of the element # ex. 'm' is mapped to its count 2 # ex. 'i' is mapped to its count 2 # ex. 'c' is mapped to its count 1 return counting_dictionary # ex. {'m':2, 'i':2, 'c':1} # Remember we can't duplicate keys in dictionaries so if we reassign it when we get to that # second 'm' it just overwrites the first mapping with the same value if we don't have the if statement on line 16. # Progression: # element is 'm' # Dictionary goes from {} to {'m':2} # element is 'i' # Dictionary goes from {'m':2} to {'m':2, 'i':2} # element is 'm' again! # Dictionary already has a mapping for key 'm' so it's mapping 'm':2 is overwritten with the same # mapping 'm':2 since we have that counting_dictionary[element] = number_copies_element line # but it ends up being the same value so it doesn't change anything # Dictionary is still {'m':2, 'i':2} # second 'i' is also overwrriten # element is 'c' # Dictionary goes from {'m':2, 'i':2} to {'m':2, 'i':2, 'c':1} # To create a new mapping, the format is: # dictionary_name[ key ] = value # The people who made dictionaries used [] to create dictionary mappings ^ It's just a convention. # () Parentheses are for functions or tuples (grouping things in parentheses) # [] are also used to denote lists or are used for indexing (subscripting/slicing) -> getting # characters / elements out of sequences like strings / lists if ( __name__ == "__main__" ) : x1 = ['m', 'i', 'm', 'i', 'c'] x2 = [3, 1, 2, 2, 1, 2] x3 = [True, False, True, True] tests =[ x1, x2, x3 ] for i in range( 0, 3 ) : x = tests[ i ] d = ction( x ) print( 'ction( x' + str( i+1 ), '):', d ) # dict = {} # for el in x: # if ( el in dict ): # dict[ el ] += 1 # else: # dict[ el ] = 1 # return dict # dict = {} # for el in x: # count_el = x.count( el ) # dict[ el ] = count_el # return dict