Py Warmup 3

New Topics: sets, dictionaries, iterating over (k,v) pairs, randomness.

Review: input, parsing, converting to integers.

Basic Exercises

  1. Create a dictionary that that lets you look up “red” to get 2, “yellow” to get 10, and “green” to get 50.
  2. Add “blue” with a value of 90 to your dictionary.
  3. Remove “red” from your dictionary.
  4. Read about defaultdict – the examples are enough – and create one that holds the items in your dictionary above, but gives 0 when you ask for a color that is not in the dictionary.
  5. Create a default dictionary that takes in a number and gives a list. When the number is 0 give [1,2,3], when the number is 2, give [1,3], and when the number is 3 give [1,2]. Other numbers should give the empty list.

Color Exercises

Here is a list of ten different colors:

    colors = ["Red", "Blue", "Green", "Yellow", "Orange",
              "Purple", "Pink", "Brown", "Gray", "Teal"]
  1. Print a single random color from the list above.
  2. Make a dictionary with a random number from 1 to 1000 mapping to a random color.
  3. Add 200 random items just list above.
  4. Repeat this ten times: pick a random number from 1 to 1000 and print either the matching color from your dictionary or “transparent” if there is no matching color.
  5. Create another dictionary that maps color name to the number of items that match that color. (“No technology”, just base Python.)
  6. Print out a report from most common to least common, showing a single COLOR and COUNT on each line.
  7. Ask the user for a number and if that number is in the dictionary print out the matching color. Otherwise print out “never heard of it”.
  8. Read about the Counter class and write another solution to the exercises 5 and 6 above (the color counting and report).
Last modified August 28, 2023: Python introduction content days 1-4. (75c2bfd)