Day 3 — Optional Exercises

Functions, modules, comprehensions, NumPy

These exercises practice Day 3 material: functions, modules, list/dict comprehensions, and NumPy basics.

Solutions are in Day_3_Solutions.qmd.


Exercise 1 — Write your first function

Write a function called winning_margin(a, b) that:

  • Takes two numbers (vote totals for candidates A and B).
  • Returns the margin of victory as a percentage of the total votes, rounded to one decimal place.
  • Returns the value as a positive number regardless of which candidate won (use abs()).

Include a docstring.

# your code here

Test it on winning_margin(5200, 4800) (should return 4.0).


Exercise 2 — Function with conditional return

Write a function called state_classifier(margin) that takes a margin of victory (positive number, in percentage points) and returns:

  • "Solid" if the margin is greater than 10
  • "Likely" if the margin is between 5 and 10 (inclusive)
  • "Lean" if the margin is between 2 and 5
  • "Toss-up" if the margin is less than 2
# your code here

Test it on margins of 1, 4, 7, and 15.


Exercise 3 — enumerate

You have a list of senator names that aren’t formatted consistently:

senators = ["bernie sanders", "Elizabeth Warren", "ted CRUZ", "AMY Klobuchar"]
  1. Use a for loop with enumerate() to normalize each name to title case (use the .title() string method). Update each name in place with senators[idx] = .... Then print the cleaned list.

  2. Write a second loop using enumerate that prints each senator with their 1-based position, like:

#1: Bernie Sanders
#2: Elizabeth Warren
#3: Ted Cruz
#4: Amy Klobuchar

(Hint: enumerate(senators, start=1) lets you start counting from 1 instead of 0.)

# your code here

Exercise 4 — List comprehension

You have a list of candidate ages:

ages = [42, 67, 51, 39, 78, 55, 33, 71]

Using a single list comprehension for each:

  1. Create a list of the squares of each age.
  2. Create a list of only the ages that are 50 or above.
  3. Create a list of labels — "senior" if the age is 65+, "adult" otherwise.
# your code here

Exercise 5 — Dictionary comprehension

Given two parallel lists:

states = ["Ohio", "Florida", "Texas", "California", "New York"]
electoral_votes = [17, 30, 40, 54, 28]
  1. Use a dict comprehension to build a dictionary mapping each state to its electoral vote count.
  2. Use a second dict comprehension to build a new dictionary that only includes states with 30 or more electoral votes.
# your code here

Exercise 6 — Using a module

Use the math module to:

  1. Compute the natural logarithm of 1000.
  2. Compute the square root of 2.
  3. Print math.pi rounded to 4 decimal places (use an f-string).

Then use the datetime module to print today’s date.

# your code here

Exercise 7 — NumPy arrays

import numpy as np

Create a 1D NumPy array containing the numbers 1 through 10. Then:

  1. Print the mean.
  2. Print only the elements that are greater than 5 (use boolean indexing).
  3. Multiply every element by 3 and print the result.
  4. Reshape the array into a 2×5 matrix and print it.
# your code here

Exercise 8 — Putting it together

Write a function called summarize_polls(poll_results) that:

  • Takes a list of poll percentages (numbers between 0 and 100).
  • Returns a dictionary with three keys: "mean", "min", "max", each rounded to one decimal place.
  • If the input list is empty, returns None (use an if early in the function).

Use NumPy for the calculations.

# your code here

Test it on summarize_polls([48.5, 51.2, 49.8, 50.3, 47.9]) and on summarize_polls([]).