Practice Exercises 6 For the week of 2020-03-30

The following exercises provide additional practice problems (not to turn in) for our material this week. Try to solve each problem on paper first before using Thonny to confirm your answers. You are encouraged to work on these practice exercises with classmates throughout the week.

  1. What is the value of the dictionary e after this code executes?

     d = { 1: 2, 3: 4 }
     d[2] = 1
     d[2] = 2
     e = {}
     for x in d:
         e[2*x] = d[x]
    
  2. [PP Problem 11.4] The keys in a dictionary are guaranteed to be unique, but the values are not. Write a function called count_values that takes a single dictionary as an argument and returns the number of distinct values it contains. Given the input {'red': 1, 'green': 1, 'blue': 2}, for example, it should return 2.

  3. [PP Problem 11.5] After doing a series of experiments, you have compiled a dictionary showing the probability of detecting certain kinds of subatomic particles. The particles’ names are the dictionary’s keys, and the probabilities are the values: {'neutron': 0.55, 'proton': 0.21, 'meson': 0.03, 'muon': 0.07, 'neutrino': 0.14}. Write a function that takes a single dictionary of this kind as input and returns the particle that is least likely to be observed. Given the dictionary shown earlier, for example, the function would return ‘meson’.

  4. You want to determine if all of the keys of a dictionary are integers. Write a function named all_ints that takes a dictionary as a parameter and returns True if all the keys are integers and False otherwise. For example:

     >>> all_ints({ 1: 2, 2: "a" })
     True
     >>> all_ints({ 1: 2, 2: "a", "c": 3 })
     False
    

    As a hint, recall that you can use the type function to determine the type of a value, and that you can perform equality comparisons on those types, e.g.

     >>> type(1) == int
     True
     >>> type(1) == float
     False
     >>> type("a") == int
     False
    
  5. What is the result of the following expressions?

    a. {2, 3, 5, 7} | {5, 6, 7, 8}
    b. {2, 3, 5, 7} & {5, 6, 7, 8}
    c. {2, 3, 5, 7} - {5, 6, 7, 8}
    d. {2, 3, 5, 7} ^ {5, 6, 7, 8}
    e. {2, 3} <= {3, 4}
    f. {2, 3} >= {3}

    Note that set comparisons are defined in terms of subset and superset.

  6. [PP Problem 11.1] Write a function named find_dups that takes a list of integers as its input argument and returns a set of those integers that occur two or more times in the list.