← return to practice.dsc10.com


Lecture 6 — Collected Practice Questions

Topics: Grouping and data visualization.

Below are practice problems tagged for Lecture 6 (rendered directly from the original exam/quiz sources). By default, problems are sorted from easiest to hardest by average score; problems without a score are listed last.


Source: Question 4 from Summer 2024 Midterm Exam

Problem 1

Consider the scatterplot generated by the following expression:

kart.plot(kind="scatter, x="Total Points", y="Races Won")

Which of the following questions would you be able to answer from this scatterplot? Select all that apply.

Answer:: Option 2 and Option 3

  • Option 1 is incorrect since the scatter plot shows all the observations based on the x and y values and they are not labeled by team. Thus, team information is not shown on this scatterplot.
  • Option 4 is incorrect since the scatter plot does not label the teams and thus you would not know this information.
  • Option 2 is correct. Since the x axis is total points, you can count the number of observations that fall at x≥6000.
  • Option 3 is correct. The phrase “100 total points per race that they won” indicates a relationship between total points and races won. Since the x-axis denotes total points and the y-axis represents races won, this relationship is simply the line x=100y. To answer this question, since we are interested in the number of teams that scored less than this, you can count the number of points below this line.

Difficulty: ⭐️

The average score on this problem was 95%.


Source: Question 5 from Spring 2025 Quiz 2

Problem 2

The scatter plot below shows the budget and revenue (in millions of dollars) for each of the 6 distinct films in kate. Answer each question below, or write “not enough info" if you don’t have enough information to answer.


Problem 2.1

How many of these films had less than 200 million dollars in revenue?

Answer: 4

Solution: Look at the y-axis (Revenue in Millions) and locate the tick mark that represents $200 million. Imagine you drew a line from this tick mark on the left side of the graph to the right side of the graph. There are 4 dots that will be under this line, representing 4 films that had less than $200 million in revenue.


Difficulty: ⭐️

The average score on this problem was 98%.



Problem 2.2

How many of these films earned a revenue more than five times their budget?

Answer: 4

Solution:

Let’s move left to right and analyze each dot along the way. The first dot has a budget of around $19 million. Five times of this is given by the following expression: 19 * 5 = 95. This dot has a revenue of around $275 million, which is much higher than $95 million. We can repeat this process with the rest of the dots. You will notice that the first four dots follow this pattern, but the last two do not. The second-to-last dot has a budget of $30 million. Five times of this is $150 million, but the revenue for this dot is only around $120 million. Similarly, the last dot has a budget of $100 million. Five times of this is $500 million, but the revenue for this dot is only around $170 million.


Difficulty: ⭐️⭐️

The average score on this problem was 85%.



Source: Question 3 from Spring 2026 Final Exam

Problem 3

For each goal below, determine the most appropriate plot type.


Problem 3.1

Show the relationship between each band’s formation year and "top_album_sales" to see if older bands tend to have higher sales.

Answer:

Scatter plot

Solution:

A scatter plot is the most appropriate choice because both the formation year and "top_album_sales" are numerical variables, and each point represents one band. It lets us check for an association between the two, such as a downward trend if earlier bands tend to have higher sales.

A line plot is less appropriate because we are comparing individual bands rather than tracking a single quantity over time, and connecting the points would imply a sequence that doesn’t exist.

A bar chart is less appropriate because bar charts compare numerical values across categories, whereas both variables here are numerical.


Difficulty: ⭐️⭐️⭐️

The average score on this problem was 68%.


Problem 3.2

Compare the total number of albums released by bands from each country, with countries sorted from most albums to fewest albums.

Answer:

Bar chart

Solution:

A bar chart is the most appropriate choice because "origin" is a categorical variable, and we want to compare a numerical summary, the total number of albums, across countries. We would group the bands by country, sum the albums for each, and draw one bar per country, ideally sorted from highest to lowest so the top countries are easy to spot.

A scatter plot is not appropriate because it displays relationships between two numerical variables, whereas country is categorical.

A line plot is not appropriate because countries have no natural order, and connecting them with lines would suggest a trend that doesn’t exist.


Difficulty: ⭐️

The average score on this problem was 95%.


Problem 3.3

Display how the average number of members in a band has changed over time.

Answer:

Line plot

Solution:

A line plot is the most appropriate choice because we want to see how a numerical quantity changes over time. We would group bands by formation year, compute the average number of members for each year, and plot formation year on the x-axis against that average on the y-axis, with the connecting line making trends in band size easy to spot.

A scatter plot would be better for examining the relationship between formation year and member count across individual bands, rather than a yearly summary.

A bar chart could display the yearly averages, but it is less effective at emphasizing the overall trend across a sequence of years.


Difficulty: ⭐️

The average score on this problem was 97%.


Problem 3.4

Compare "top_album_sales" across different genres to identify which genre has the highest median sales.

Answer:

Bar chart

Solution:

A bar chart is the most appropriate choice because genre is a categorical variable, and we want to compare the median "top_album_sales" across genres. We would group the bands by genre, compute the median top album sales for each, and draw one bar per genre, which lets us directly identify the genre with the highest median.

A scatter plot is less appropriate because it displays relationships between numerical variables, whereas genre is categorical.

A line plot is less appropriate because genres have no natural order, and connecting the medians with lines would suggest a trend that doesn’t exist.


Difficulty: ⭐️

The average score on this problem was 95%.


Problem 3.5

Show the relationship between number of albums released and "top_album_sales" to see if one variable can be predicted from the other.

Answer:

Scatter plot

Solution:

A scatter plot is the most appropriate choice because both the number of albums released and "top_album_sales" are numerical variables, and each point represents one band. It lets us examine the direction, strength, and shape of the association, such as whether bands with more albums tend to have higher top sales and whether the relationship looks approximately linear, which is useful for deciding if linear regression is appropriate.

A line plot is less appropriate because the bands are separate observations rather than a continuous sequence, so connecting them would be misleading.

A bar chart is less appropriate because it compares values across categories rather than investigating the relationship between two numerical variables.


Difficulty: ⭐️

The average score on this problem was 97%.



Source: Question 1 from Fall 2024 Final Exam

Problem 4


Problem 4.1

Notice that bookstore has an index of "ISBN" and sales does not. Why is that?

Answer: The bookstore can sell multiple copies of the same book.

In the sales DataFrame, each row represents an individual sale, meaning multiple rows can have the same "ISBN" if multiple copies of the same book are sold. Therefore we can’t use it as the index because it is not a unique identifier for rows of sales.


Difficulty: ⭐️⭐️

The average score on this problem was 87%.


Problem 4.2

Is "ISBN" a numerical or categorical variable?

Answer: categorical

Even though "ISBN" consists of numbers, it is used to identify and categorize books rather than to quantify or measure anything, thus it is categorical. It doesn’t make sense to compare ISBN numbers like you would compare numbers on a number line, or to do arithmetic with ISBN numbers.


Difficulty: ⭐️⭐️

The average score on this problem was 75%.


Problem 4.3

Which type of data visualization should be used to compare authors by median rating?

Answer: bar chart

A bar chart is best, as it visualizes numerical values (median ratings) across discrete categories (authors).


Difficulty: ⭐️⭐️

The average score on this problem was 88%.



Source: Question 12 from Fall 2024 Midterm Exam

Problem 5


Problem 5.1

What would be the best type of plot to visualize the distribution of "neighborhood" among the houses represented in treat?

Answer: bar chart


Difficulty: ⭐️⭐️

The average score on this problem was 76%.


Problem 5.2

Suppose we had access to historical data about the price of fun-sized candies over time. If we wanted to compare the prices of Milky Way and Skittles over time, which would be the best type of visualization to plot?

Answer: overlaid line plot


Difficulty: ⭐️

The average score on this problem was 90%.



Source: Question 5 from Winter 2026 Quiz 1

Problem 6

For a report to the Academic Senate, you need to analyze course enrollment patterns. Write or finish one line of Python code that produces each quantity described.


Problem 6.1

(a) A DataFrame consisting of "Department" as the index, and a single column containing the mean "Enrollment" of all courses within each "Department".

courses.get(["Department", "Enrollment"]).___________________________

Answer: groupby("Department").mean() — full one-liner:

courses.get(["Department", "Enrollment"]).groupby("Department").mean()

Explanation: .get(["Department", "Enrollment"]) keeps only those columns. .groupby("Department") groups rows by department. .mean() computes the mean of numeric columns per group — here mean "Enrollment" — producing a DataFrame with "Department" as the index and one column of means.


Difficulty: ⭐️⭐️

The average score on this problem was 78%.


Problem 6.2

(b) A scatter plot of the data in the courses DataFrame with "Capacity" on the x-axis and "Enrollment" on the y-axis.

Answer: courses.plot(kind="scatter", x="Capacity", y="Enrollment")

kind="scatter" draws a scatter plot; x and y name the columns for the horizontal and vertical axes.


Difficulty: ⭐️⭐️

The average score on this problem was 79%.



Source: Question 1 from Fall 2026 Midterm Exam

Problem 7

Write one line of code to create a horizontal bar chart showing both the average "num_likes" and the average "num_comments" for each "category". On a DataFrame of just the 5 rows shown in the data description, it would look like the image below.


Answer: posts.get(["category", "num_likes", "num_comments"]).groupby("category").mean().plot(kind="barh")


Difficulty: ⭐️⭐️

The average score on this problem was 75%.


Source: Question 1 from Winter 2026 Midterm Exam

Problem 8


Problem 8.1

Which column of the pizza DataFrame would be an appropriate index?

Answer: None of these.

Explanation:

An index needs unique values for each row. Let’s check each option:

  • "store": Multiple slices from the same restaurant — not unique.
  • "kind": Multiple restaurants sell the same kind — not unique.
  • "rating": Multiple pizzas can have the same rating — not unique.
  • "neighborhood": Multiple places per neighborhood — not unique.

None of these columns uniquely identify each row, so none work as an index on their own.


Difficulty: ⭐️⭐️⭐️

The average score on this problem was 67%.


Problem 8.2

Suppose you want to see if there is a relationship between num_ingredients and price. Which visualization will best enable you to investigate this?

Answer: A scatter plot of price vs. num_ingredients.

Explanation:

Both variables are numerical. A scatter plot is the right choice for two numerical variables — you can see the relationship, trend, and individual points.

The other options:

  • Overlaid histograms show distributions, not relationships between the two variables.
  • Bar charts treat one variable as categorical, which doesn’t work well for continuous numerical data here.

Difficulty: ⭐️⭐️

The average score on this problem was 77%.


Problem 8.3

Fill in the blanks to create a horizontal bar chart showing both the average price_per_slice and average rating for each store side by side. On a DataFrame of just the 10 rows shown in the data description, it would look like the image below

(pizza._____(i)______
      .groupby("store")._____(ii)_____
      .plot(__(iii)__));

Answer: get(["store", "price_per_slice", "rating"]), then mean(), then plot with kind="barh" (see below).

(i) get(["store", "price_per_slice", "rating"])

(ii) mean()

(iii) kind="barh"

Full chain:

pizza.get(["store", "price_per_slice", "rating"]).groupby("store").mean().plot(kind="barh")

Explanation:

  1. .get(["store", "price_per_slice", "rating"]) — Select the columns we need (use a list for multiple columns). Names match the Data Description (price_per_slice in code).
  2. .groupby("store") — Group by store.
  3. .mean() — Average price_per_slice and rating within each store.
  4. .plot(kind="barh") — Horizontal bar chart ("h" means horizontal).

Difficulty: ⭐️⭐️

The average score on this problem was 83%.


Difficulty: ⭐️

The average score on this problem was 90%.


Difficulty: ⭐️⭐️⭐️

The average score on this problem was 57%.



Source: Question 5 from Fall 2025 Quiz 2

Problem 9


Problem 9.1

Use the scatterplot of all 30 ingredients to determine how many have a calorie-to-protein ratio that is at least 5.

Answer: 26


Difficulty: ⭐️⭐️⭐️

The average score on this problem was 73%.


Problem 9.2

Let calories and protein be numpy arrays containing the calorie and protein amounts, as ints, for each of the 30 ingredients in chipotle. Fill in the blanks so that the code below calculates the number of ingredients with a calorie-to-protein ratio of at least 5.

count = __(a)__
for i in np.arange(__(b)__):
    if calories[i] / protein[i] >= 5:
        count = __(c)__

(a): 0
(b): len(calories) or 30
(c): count + 1


Difficulty: ⭐️⭐️

The average score on this problem was 76%.



Source: Question 1 from Winter 2024 Quiz 2

Problem 10

We’d like to visualize the distribution of the "Mfr" column in the laptops DataFrame. Fill in the blanks so that the code below draws an appropriate plot.

laptops.groupby(__(a)__).__(b)__.get([__(c)__]).plot(kind=__(d)__)

Answer:

Answer (a): "Mfr"

We want to see how laptops are distributed across manufacturers, so we group by the "Mfr" column.


Difficulty: ⭐️

The average score on this problem was 92%.

Answer (b): count()

.count() counts the number of rows in each group. Grouping by "Mfr" and then counting tells us how many laptops come from each manufacturer, which is exactly the distribution we want to plot.


Difficulty: ⭐️⭐️

The average score on this problem was 82%.

Answer (c): "Model", "OS", "Screen Size", or "Price"

After laptops.groupby("Mfr"), the "Mfr" column becomes the index rather than a regular column. So .count() returns a DataFrame with one row per manufacturer, where every remaining column holds the same count (the number of laptops from that manufacturer). Since all of these columns contain identical values, we can pick any one of them with .get([...]) — just not "Mfr" itself, since it’s no longer a column.


Difficulty: ⭐️⭐️⭐️

The average score on this problem was 56%.

Answer (d): "bar" or "barh"

"Mfr" is a categorical variable (manufacturer names), and the standard way to visualize the distribution of a categorical variable is a bar chart, with one bar per category.


Difficulty: ⭐️⭐️⭐️

The average score on this problem was 68%.


Source: Question 3 from Fall 2023 Quiz 2

Problem 11

Which type of plot should we use to visualize the distribution of the "Location" column in the items DataFrame?

Answer: Bar chart

“Location” is a categorical variable, since each value is the name of a store or action. The distribution of a categorical variable is shown with a bar chart (one bar per category).


Difficulty: ⭐️⭐️⭐️

The average score on this problem was 74%.


Source: Question 4 from Fall 2023 Final Exam

Problem 12

The following code block produces a bar chart, which is shown directly beneath it.

    (txn.get(["browser", "is_fraud"]).groupby("browser").mean()
        .sort_values(by="is_fraud", ascending=False)
        .take(np.arange(10))
        .plot(kind="barh", y="is_fraud"))


Problem 12.1

Based on the above bar chart, what can we conclude about the browser "icedragon"? Select all that apply.

Answer: C

First, let’s take a look at what the code is doing. We start by grouping by browser and taking the mean, so each column will have the average value of that column for each browser (where each browser is a row). We then sort in descending order by the "is_fraud" column, so the browser which has the highest proportion of fraudulent transactions will be first, and we take first the ten browsers, or those with the most fraud. Finally, we plot the "is_fraud" column in a horizontal bar chart. So, our plot shows the proportion of fraudulent transactions for each browser, and we see that icedragon has a proportion of 1.0, implying that every transaction is fraudulent. This makes the third option correct. Since we don’t have enough information to conclude any of the other options, the third option is the only correct one.


Difficulty: ⭐️⭐️

The average score on this problem was 83%.


Problem 12.2

How can we modify the provided code block so that the bar chart displays the same information, but with the bars sorted in the opposite order (i.e. with the longest bar at the top)?

Answer: C

Let’s analyze each option A: This isn’t correct, because we must remember that np.take(np.arange(10)) takes the rows indexed 0 through 10. And if we change ascending = False to ascending = True, the rows indexed 0 through 10 won’t be the same in the resulting DataFrame (since now they’ll be the 10 browsers with the lowest fraud rate). B: This will have the same effect as option A, since it’s being applied before the np.take() operation C: Once we have the 10 rows with the highest fraud rate, we can sort them in ascending order in order to reverse the order of the bars. Since we already have the 10 rows from the original plot, this option is correct.


Difficulty: ⭐️⭐️⭐️

The average score on this problem was 59%.



Source: Question 3 from Fall 2025 Midterm Exam

Problem 13

Below is a bar chart and the code that produced it.

(words.sort_values(by="diff", ascending=False).take(np.arange(20))
      .plot(kind='barh', y="diff"));

Determine whether each statement below is true or false.


Problem 13.1

Students found the word “decades" more difficult than any other word.

Answer: False

We can see on the bar chart that there were 5 other words with the same diff value as decades, so the answer is False.


Difficulty: ⭐️⭐️

The average score on this problem was 83%.



Problem 13.2

If we removed ascending = False from the code, the bar chart would show the same information, except the bars would appear in the opposite order from top to bottom.

Answer: False

We are only plotting the first 20 rows of words after sorting it. So, currently we have plotted the 20 words with the highest diff value. If we removed ascending = False then it would sort in ascending order and we would only be plotting the 20 words with the lowest diff value. They would not be the same words.


Difficulty: ⭐️⭐️⭐️⭐️

The average score on this problem was 46%.



Problem 13.3

This bar chart shows all words that more than 20 students found difficult. If we changed np.arange(20) to np.arange(15) in the code, the bar chart would instead show all words that more than 15 students found difficult.

Answer: False

.take(np.arange(20)) takes the elements at those positional indices. .take(np.arange(15)) would take less elements, so there is no way that it would include more students in the bar chart


Difficulty: ⭐️⭐️

The average score on this problem was 80%.



Source: Question 1 from Fall 2023 Midterm Exam

Problem 14


Problem 14.1

You’re interested in comparing the "avg_housing_cost" across different "family_type" groups for San Diego County, CA specifically. Which type of visualization would be most appropriate?

Answer: Bar chart

"family_type" is a categorical variable, and we use bar charts to visualize the distribution of categorical variables.

  • A scatter plot visualizes the relationship between two numerical variables, but we are only using one numerical variable here ("avg_housing_cost").
  • A line plot is used to visualize the trend between two numerical variables, but we are only using one numerical variable.
  • A histogram is used to visualize the distribution of numerical variables, but we want to see the distribution of the categorical variable "family_type".

Difficulty: ⭐️⭐️

The average score on this problem was 89%.


Problem 14.2

Suppose we run the three lines of code below.

families = living_cost.get(["family_type", "avg_housing_cost", "avg_childcare_cost"]).groupby("family_type").median()
sorted_families = families.sort_values(by="avg_housing_cost")
result = sorted_families.get("avg_childcare_cost").iloc[0]

Which of the following does result evaluate to?

Answer: The median "avg_childcare_cost" of the "family_type" with the lowest median "avg_housing_cost".

When we grouped living_cost by "family_type", families is a DataFrame with one row per "family_type". Using the .median() aggregation method takes the median of all numerical columns per "family_type".

sorted_families is the families DataFrame, but sorted in ascending order based on the "avg_housing_cost" column. The first row of sorted_families is the "family_type" with the lowest median "avg_housing_cost", and the last row of sorted_families is the "family_type" with the highest median "avg_housing_cost".

In the last line of code, we’re getting the "avg_childcare_cost" column from the sorted_families DataFrame. We then use iloc to get the first entry in the "avg_childcare_cost" column. Since sorted_families is sorted by "avg_housing_cost", this entry belongs to the family type with the lowest median housing cost; it is not necessarily the lowest median childcare cost. Therefore, result evaluates to the median "avg_childcare_cost" of the "family_type" with the lowest median "avg_housing_cost".


Difficulty: ⭐️⭐️

The average score on this problem was 82%.


Problem 14.3

Suppose we define another_result as follows.

another_result = (living_cost.groupby("state").count()
                  .sort_values(by="median_income", ascending=False)
                  .get("median_income").index[0])

What does another_result represent?

Answer: The state with the most counties.

The living_cost DataFrame is being grouped by the "state" column, so there is now one row per "state". By using the .count() aggregation method, the columns in the DataFrame will contain the number of rows in living_count for each "state". All of the columns will also be the same after using .count(), so they will all contain the distribution of "state". Since living_cost has data on every county in the US, the grouped DataFrame represents the number of counties that each state has.

We then sort the DataFrame in descending order, so the state with the most counties is at the top of the DataFrame. The last line of the expression gets a column and uses .index to get the state corresponding to the first entry, which happens to be the state with the most counties and the value that gets assigned to another_result.

Since all the columns are the same, it doesn’t matter which column we pick to use in the .sort_values() method. In this case, we used the "median_income" column, but picking any other column will produce the same result.


Difficulty: ⭐️⭐️⭐️

The average score on this problem was 65%.


Problem 14.4

Which of the following DataFrames has exactly four columns?

Answer: None of the above.

None of these DataFrames has exactly four columns.

  • .min() runs on strings, so "state" and "county" stay. After grouping by "family_type", six columns remain.
  • .sum() concatenates the strings in "state" and "county" and sums the numeric columns, so it also has six columns.
  • .count() also keeps every remaining column, so it has six columns too.

Difficulty: ⭐️⭐️⭐️⭐️

The average score on this problem was 35%.


Problem 14.5

Suppose we define the Series three_columns to be the concatenation of three columns of the living_cost DataFrame as follows.

three_columns = (living_cost.get("state") + " " +
                 living_cost.get("county") + " " + 
                 living_cost.get("family_type"))

For example, the first element of three_columns is the string "CA San Diego County 1a2c" (refer back to the first row of living_cost provided in the data overview).

What does the following expression evaluate to?

(living_cost.assign(geo_family=three_columns)
            .groupby("geo_family").count()
            .shape[0])

Answer: 31430, the number of rows in the living_cost DataFrame.

The first line of the expression creates a new column in living_cost, called "geo_family" that represents the concatenation of the values in "three_columns". When we group the DataFrame by "geo_family", we create a new DataFrame that contains a row for every unique value in "three_columns". "three_columns" has various combinations of "state", "country", and "family_type". Since it’s given in the DataFrame description that each of the 31430 rows of the DataFrame represents a different combination of "state", "country", and "family_type", this means that the grouped DataFrame has 31430 unique combinations as well. Therefore, when we use .shape[0] to get the number of rows in the grouped DataFrame in the last line of the expression, we get the same value as the number of rows in the living_cost DataFrame, 31430.


Difficulty: ⭐️⭐️⭐️

The average score on this problem was 74%.



Source: Question 2 from Fall 2022 Midterm Exam

Problem 15


Problem 15.1

Which type of visualization should we use to visualize the distribution of "Range"?

Answer: Histogram

"Range" is a numerical (i.e. quantitative) variable, and we use histograms to visualize the distribution of numerical variables.

  • A bar chart couldn’t work here. Bar charts can show the distribution of a categorical variable, but "Range" is not categorical.
  • A scatter plot visualizes the relationship between two numerical variables, but we are only dealing with one numerical variable here ("Range").
  • Similarly, a line plot visualizes the relationship between two numerical variables, but we only have one here.

Difficulty: ⭐️⭐️⭐️

The average score on this problem was 63%.


Problem 15.2

Teslas, on average, tend to have higher "Range"s than BMWs. In which of the following visualizations would we be able to see this pattern? Select all that apply.

Answer:

  • A bar chart that shows the average "Range" for each "Brand"
  • An overlaid histogram showing the distribution of "Range" for each "Brand"

Let’s look at each option more closely.

  • Option 1: A bar chart showing the distribution of "Brand" would only show us how many cars of each "Brand" there are. It would not tell us anything about the average "Range" of each "Brand".

  • Option 2: A bar chart showing the average range for each "Brand" would help us directly visualize how the average range of each "Brand" compares to one another.

  • Option 3: An overlaid histogram, although perhaps a bit messy, would also give us a general idea of the average range of each "Brand" by giving us the distribution of the "Range" of each brand. In the scenario mentioned in the question, we’d expect to see that the Tesla distribution is further right than the BMW distribution.

  • Option 4: A scatter plot of "TopSpeed" against "Range" would only illustrate the relationship between "TopSpeed" and "Range", but would contain no information about the "Brand" of each EV.


Difficulty: ⭐️

The average score on this problem was 91%.


Problem 15.3

Gabriel thinks "Seats" is a categorical variable because it can be used to categorize EVs by size. For instance, EVs with 4 seats are small, EVs with 5 seats are medium, and EVs with 6 or more seats are large.

Is Gabriel correct?

Justify your answer in one sentence. Your answer must fit in the box below.

Answer: No

"Seats" is a numerical variable, since it makes sense to do arithmetic with the values. For instance, we can find the average number of "Seats" that a group of cars has. Gabriel’s argument could apply to any numerical variable; just because we can place numerical variables into “bins” doesn’t make them categorical.


Difficulty: ⭐️⭐️⭐️

The average score on this problem was 51%.



Source: Question 3 from Summer 2026 Midterm Exam

Problem 16

The "time" column in ufo describes the time at which a UFO was initially sighted. The times are formatted in 24-hour time which uses hours 00 through 23. For example, 13:51 is the same as 1:51 PM.

We want to create a function named time_of_day which takes in a time and returns the corresponding category, defined by the table below.

hour range category
00:00–04:59 "night"
05:00–11:59 "morning"
12:00–16:59 "afternoon"
17:00–23:59 "evening"

Example inputs and outputs are given below.

>>> time_of_day("00:00")
"night"

>>> time_of_day("13:37")
"afternoon"

>>> time_of_day("23:59")
"evening"


Problem 16.1

Consider the following implementations for time_of_day. Which of the following implementations are correct? Select all that apply.

Implementation 1:

def time_of_day(time):
    hour_part = int(time.split(":")[0])
    if hour_part >= 17 or hour_part < 24:
        return "evening"
    elif hour_part >= 12 or hour_part < 17:
        return "afternoon"
    elif hour_part >= 5 or hour_part < 12:
        return "morning"
    else:
        return "night"

Implementation 2:

def time_of_day(time):
    hour_part = int(time.split(":")[0])
    if hour_part < 5:
        return "night"
    if hour_part < 12:
        return "morning"
    if hour_part < 17:
        return "afternoon"
    if hour_part >= 0:
        return "evening"

Implementation 3:

def time_of_day(time):
    hour_part = int(time.split(":")[0])
    if hour_part >= 17:
        return "morning"
    elif hour_part >= 12:
        return "night"
    elif hour_part >= 5:
        return "afternoon"
    else:
        return "evening"

Answer: Implementation 2 only.

All three implementations extract the hour correctly with int(time.split(":")[0]); the difference is in the conditions.

  • Implementation 1: The conditions use or where they should use and. Every valid hour satisfies hour_part < 24, so the very first condition hour_part >= 17 or hour_part < 24 is True for every time, and the function always returns "evening".
  • Implementation 2: Correct. Because each if returns immediately, reaching the second if already guarantees hour_part >= 5, reaching the third guarantees hour_part >= 12, and reaching the fourth guarantees hour_part >= 17. So the one-sided comparisons are enough, and the categories come out exactly as specified. (The final if hour_part >= 0 is always True at that point, so it behaves like an else.)
  • Implementation 3: The structure is right, but the returned labels are shuffled. Hours 17 and later should be "evening", not "morning".

Difficulty: ⭐️⭐️⭐️

The average score on this problem was 71%.


Problem 16.2

Suppose we use a correct implementation of time_of_day to add another column called "time_of_day" to the ufo DataFrame. Every entry in the "time" column has a converted value in the "time_of_day" column.


Which type of data visualization should be used to compare average duration to the original "time" column? Select only one of the options.

Answer: Line plot.

The "time" column is a sequence of times running from 00:00 to 23:59, so it behaves like a numerical variable with a natural order. Here we’re plotting one average duration per time, so we have one variable (average duration) measured across a sequence — exactly the situation a line plot is designed for. Line plots are the standard choice for showing how a quantity changes over time.

A scatter plot would be used for two numerical variables measured on each individual, a bar chart for a categorical variable, and a histogram for the distribution of a single numerical variable.


Difficulty: ⭐️⭐️⭐️⭐️

The average score on this problem was 45%.


Problem 16.3

Which type of data visualization should be used to compare average duration to the new "time_of_day" column? Select only one of the options.

Answer: Bar chart.

Unlike "time", the "time_of_day" column is categorical — it takes only the four values "night", "morning", "afternoon", and "evening". Bar charts are used to show a numerical quantity (here, average duration) for each category of a categorical variable.

A line plot would incorrectly suggest a continuous trend between categories, while scatter plots and histograms both require numerical data.


Difficulty: ⭐️⭐️

The average score on this problem was 88%.



Source: Question 3 from Spring 2026 Quiz 1

Problem 17


Problem 17.1

Kate wants to determine how often championships are won in penalty shoot-outs versus won in regular time. Which plot type would best allow her to visualize this information?

Answer: bar chart


Difficulty: ⭐️⭐️

The average score on this problem was 82%.


Problem 17.2

Bianca creates a horizontal bar chart to show how times a World Cup was won by a team wearing each jersey color. Based on the provided information, what is the maximum possible length of the "blue" bar? Give your answer as an integer.

Answer: 20


Difficulty: ⭐️⭐️⭐️⭐️

The average score on this problem was 48%.



Source: Question 9 from Spring 2022 Midterm Exam

Problem 18

The expression below evaluates to True.

(
classify_artist('Michelle Branch')=='outdated' 
and 
classify_artist('Drake')=='trending'
)

Consider the scatterplot created by the code below.

merged.plot(kind='scatter', x='Year', y='Top_Hit_Year');

The point for Drake is somewhere in this scatterplot. Relative to the point for Drake, there are four quadrants of the scatterplot, as shown below.


There is one quadrant in which the point for Michelle Branch cannot appear. Which is it?

Answer: northwest

The scatterplot shows an artist’s year of performance at Sun God on the x-axis, and their top hit year on the y-axis.

Since Drake is considered trending, we know his top hit came out within the five years prior to his Sun God performance. In other words, the time gap between his top hit release and his Sun God performance is at most five years.

If Michelle Branch were in the northwest quadrant, that would mean her x-coordinate was smaller than Drake’s, and her y-coordinate was larger. In other words, that would mean she performed at Sun God before Drake and her top hit was released after Drake’s. This means the time gap between her top hit release and her Sun God performance is less than five years, so she could not be considered outdated.

We could also answer this question through process of elimination. This would entail finding scenarios that show each of the other three quadrants is possible.

Michelle Branch could wind up in the northeast quadrant if, say, she performed 10 years after Drake and released her top hit 1 year after Drake. She’d be considered outdated because the time gap between her top hit and her Sun God performance would exceed five years.

Similarly, Michelle Branch could be in the southwest quadrant if, say, she performed 1 year before Drake and released her top hit 10 years before Drake. Again, the time gap between her top hit and her Sun God performance would exceed five years, making her outdated.

She could also be in the southeast quadrant if, say, she performed 10 years after Drake and released her top hit 10 years before Drake. This would also make the time gap between her top hit and Sun God performance more than five years.

So since all three other quadrants are possible and we are told that one quadrant is impossible, the northwest quadrant must be impossible.


Difficulty: ⭐️⭐️⭐️

The average score on this problem was 65%.


Source: Question 1 from Summer 2022 Final Exam

Problem 19

Choose the best visualization to answer each of the following questions.


Problem 19.1

What kinds of dogs cost the most?

Answer: Bar plot

Here, there is a categorical variable (the breed of the dog) and a quantitative variable (the price of the dog). A bar plot is most suitable for this scenario when trying to compare quantitative values accross different categorical values. A scatter plot or histogram wouldn’t be appropriate here since both of those charts typically aim to visualize a comparison between two quantitative variables.


Difficulty: ⭐️⭐️

The average score on this problem was 89%.


Problem 19.2

Do toy dogs have smaller 'size' values than other dogs?

Answer: None of the above

We are comparing two categorical variables ('size' and 'kind'). None of the graphs here are suitable for this scenario since bar plots are used to compare a categorical variable against a quantitative variable, while scatter plots and histograms compare a quantitative variable against quantitative variable.


Difficulty: ⭐️⭐️⭐️⭐️⭐️

The average score on this problem was 26%.


Problem 19.3

Is there a linear relationship between weight and height?

Answer: Scatter plot

When looking for a relationship between two continuous quantitative variables, a scatter plot is the most appropriate graph here since the primary use of a scatter plot is to observe the relationship between two numerical variables. A bar chart isn’t suitable since we have two quantitative variables, while a bar chart visualizes a quantitative variable and a categorical variable. A histogram isn’t suitable since it’s typically used to show the frequency of each interval (in other words, the distribution of a numerical variable).


Difficulty: ⭐️

The average score on this problem was 100%.


Problem 19.4

Do dogs that are highly suitable for children weigh more?

Answer: Bar plot

We’re comparing a categorical variable (dog suitability for children) with a quantitative varible (weight). A bar plot is most approriate when comparing a categorical variable against a quantitative variable. Both scatter plot and histogram aim to compare a quantitative variable against another quantitative variable.


Difficulty: ⭐️⭐️⭐️⭐️

The average score on this problem was 40%.



Source: Question 7 from Spring 2026 Midterm Exam

Problem 20

The bar chart below was produced from the data in mascots. It shows how many schools use each color.


Problem 20.1

If you knew the exact heights of each bar, how could you determine the total number of schools in mascots?

Answer: Option 3

Each school can have multiple colors, and any school with more than one color is counted in multiple bars. For example, a school with school colors blue and gold contributes 1 to both the blue bar and the gold bar. This means that summing the bar heights overcounts schools, and we have no way to know how many schools were double or triple-counted (more…) just from the bar chart. Therefore, we cannot recover the total number of schools.


Difficulty: ⭐️⭐️

The average score on this problem was 87%.


Problem 20.2

In the bar chart, the height of the blue bar is 2100 and the height of the gold bar is 1500. Use this information and the first five rows of mascots (provided with the data description) to determine the maximum possible number of schools in mascots whose school colors are blue and gold only. Give your answer as an integer.

Answer: 1498

A school whose colors are “blue and gold only” must appear in both the blue bar (height 2100) and the gold bar (height 1500), so the answer is at most \min(2100, 1500) = 1500.

To maximize the count, we want as many of the 1500 gold-using schools as possible to also use blue, and to use no other color. However, the first five rows of mascots show specific schools that use gold along with a color other than blue (or use gold without blue at all). Each such school is one of the 1500 gold schools but cannot be counted in our group.

From the first five rows, exactly 2 schools using gold are disqualified in this way, so the maximum possible number of “blue and gold only” schools is 1500 - 2 = 1498.


Difficulty: ⭐️⭐️⭐️⭐️

The average score on this problem was 44%.


Problem 20.3

Write one line of code that uses the mascots DataFrame to calculate the sum of the heights of all bars in the bar chart above.

Answer: mascots.get("colors").apply(len).sum()

The sum of the bar heights counts each school once for every color it has (a school with 3 colors contributes 1 to each of 3 bars, for a total of 3). This means that the total bar height equals the total number of (school, color) pairs across the dataset.

The "colors" column contains a list for each school, and the length of that list is the number of colors the school has. Applying len to each list and then summing it all gives exactly the total count of (school, color) pairs, which equals the sum of bar heights.


Difficulty: ⭐️⭐️⭐️⭐️

The average score on this problem was 31%.



Source: Question 3 from Winter 2025 Quiz 1

Problem 21


Problem 21.1

One of the clubs in the clubs DataFrame is the "Surf Club". Without querying, write an expression that evaluates to the rating of this club.

Answer: clubs.set_index("Name").get("Rating").loc["Surf Club"]

Club names are unique, so we can make "Name" the index with .set_index("Name"). Then .get("Rating") pulls out the ratings as a Series, indexed by club name. .loc["Surf Club"] grabs the value whose index label is "Surf Club". The order .loc["Surf Club"].get("Rating") also works, as long as set_index comes first.


Difficulty: ⭐️⭐️⭐️

The average score on this problem was 62%.


Problem 21.2

Now, using a query, write an expression that evaluates to the rating of the "Surf Club".

Answer: clubs[clubs.get("Name") == "Surf Club"].get("Rating").iloc[0]

  1. clubs.get("Name") == "Surf Club" makes a Boolean Series that’s True only for the Surf Club row.
  2. clubs[...] keeps just the rows where it’s True. That’s a DataFrame with one row.
  3. .get("Rating") gives a Series with one value. It’s still a Series, not a number.
  4. .iloc[0] pulls out the value at position 0. We use .iloc (position) rather than .loc (label) because a query keeps the original index labels, so the Surf Club row’s label isn’t necessarily 0.

Difficulty: ⭐️⭐️⭐️⭐️

The average score on this problem was 48%.


Problem 21.3

Fill in the blanks so the expression below evaluates to the name of the category (e.g. "Social") with the largest number of members, on average.

(clubs.groupby(__(a)__).__(b)__.sort_values(by="Members", ascending=__(c)__).__(d)__)

Answer:

(a): "Category"

(b): mean()

(c): False

(d): index[0]

  • (a), (b): We want the average members per category, so we group by "Category" and aggregate with .mean().
  • (c): Sorting by "Members" with ascending=False puts the category with the largest average at the top.
  • (d): After a groupby, the category names become the index, not a column. So .index[0] gives the first label in the sorted index, which is the category name we want.

Difficulty: ⭐️⭐️⭐️

The average score on this problem was 59%.


Problem 21.4

In each category, what is the largest budget for a club? Write one line of code that would produce an appropriate data visualization to answer this question.

Answer: clubs.groupby("Category").max().plot(kind= "bar", y= "Budget")

There are two steps:

  1. Get the right numbers. .groupby("Category").max() finds the largest value of each column within each category. The "Budget" column of the result is the largest budget per category.
  2. Pick the right plot. We’re comparing one number across categories, so a bar chart fits (kind="barh" is also fine). y="Budget" says which column to plot. The category names are in the index, so they automatically label the bars.

Difficulty: ⭐️⭐️⭐️⭐️

The average score on this problem was 38%.