Homework 2: Dictionaries/Lists/Arrays, If Statements, Functions, and Modules#
✅ Put your name here
#Assignment instructions#
Work through the following assignment, making sure to follow all the directions and answer all the questions.
This assignment is due at 11:59 pm on October 16th. You will submit it through Gradescope this time (not D2L): you will upload your completed notebook, an autograder converts it to a PDF, and you then map the PDF pages to the questions for grading.
Follow the step-by-step Gradescope Submission Instructions on the course website (also linked at the end of this notebook).
IMPORTANT NOTE: Throughout this notebook, you will see a number of cells that say “DO NOT EDIT OR MOVE THIS CELL”. Please leave these cells where they are and do not edit them. Moving or editing them makes it more challenging to divide the homework into questions for grading. Your TAs will thank you for leaving them where they are!
Academic integrity statement (2 Points)#
In the markdown cell below, paste your personal academic integrity statement. By including this statement, you are confirming that you are submitting this as your own work and not that of someone else.
✎ Put your personal academic integrity statement here.
DO NOT EDIT OR MOVE THIS CELL - Make sure your answer is above it!
1. Dictionaries, Lists, Arrays (10 Points)#
Python provides several ways to store and organize collections of information.
Dictionaries are particularly useful for keeping track of information using keys and values.
Lists are useful for storing a collection of values in a specific order.
NumPy arrays are similar to lists but are particularly useful for storing numerical values and performing calculations on them.
Scenario: A campus coffee shop recorded the number of customers who visited during each of its first 10 hours of operation:
[42, 57, 63, 51, 78, 85, 91, 74, 68, 55]
The coffee shop wants to examine these data to better understand how customer traffic changes throughout the day.
✅ 1.1 Task (5 Points)#
You can solve this problem using either a dictionary, a list, or a NumPy array.
Store the 10 customer counts shown above in one Python variable using a data structure of your choice.
Then:
Print the complete collection of customer counts.
Print the number of customers during the 5th hour.
Calculate and print the total number of customers across all 10 hours.
Calculate and print the average number of customers per hour.
Print the highest number of customers recorded during any hour.
# Put your answer here
customers = [42, 57, 63, 51, 78, 85, 91, 74, 68, 55]
✅ 1.2 Task (5 Points)#
Now it is time to think about the process:
Why did you choose a dictionary, list, or NumPy array to solve this problem? What made it a good choice for these data?
✎ Put your answer here
What part of your solution required the most thought, and how did you work through it?
✎ Put your answer here
If you solved this problem again using one of the other data structures, what would you need to change in your code?
✎ Put your answer here
DO NOT EDIT OR MOVE THIS CELL - Make sure your answer is above it!
2. Debugging a Function (10 Points)#
In the Tasks below, you will be asked to find, describe, and fix the bugs in each example.
Remember that a bug is anything that prevents intended functionality! Bugs are easily overlooked and can result from several mistakes, including:
typos or mispellings
missing variables or functions
problems with indexing
problems with parentheses
formatting and use of tabs
many, many more unforeseen problems that cause unintended consequences!
✅ 2.1 Task (5 Points)#
In math class, you are studying the well-known Pythagorean theorem:
Where \(a\) and \(b\) are the lengths of the base and perpendicular sides of a right triangle which you can use to solve for \(c\), the length of the remaining side, or the hypotenuse.
You write the function pythagoras, below. The intended funcitonality is, given two lists of equal length as inputs (a_list and b_list), to return a list of calculated c values (c_list).
def pythagoras(a_list, b_list): # inputs of a_list and b_list
c_list = [] # create an empty list to store c values
for i in range(len(a_list)): # for each element in the lists
c = ( a_list[i]**2 + b_list[i]**2 )**(0.5) # calculate c
return c_list # return the list of c values
You give your function a try.
For the 3 sets of values in the lists a_vals and b_vals, based on the values, c_vals should be a list with the values of [2.23606797749979, 3.605551275463989, 5.0], but you only see an empty list for an output.
a_vals = [1,2,3] # list of a values
b_vals = [2,3,4] # list of b values
c_vals = pythagoras(a_list=a_vals, b_list=b_vals) # call the function
print(c_vals) # print out c values
[]
In the cell below, please answer:
(2 points) What was the bug? What is preventing you from returning a full list of values?
(1 point) How did you figure out what the bug was? Please cite use of external sources or any internal logic that you used.
✎ Put your answer here 1.
In the cell below, fix the bug so that the list of c values is correctly printed out (2 points)
###PUT YOUR ANSWER HERE###
#modify the code below to fix the bug!
def pythagoras(a_list, b_list):
c_list = []
for i in range(len(a_list)):
c = ( a_list[i]**2 + b_list[i]**2 )**(0.5)
return c_list
a_vals = [1,2,3] # list of a values
b_vals = [2,3,4] # list of b values
c_vals = pythagoras(a_list=a_vals, b_list=b_vals) # call the function
print(c_vals) # print out c values
[]
✅ 2.2 Task (5 Points)#
Now in your introductory botany class, you learn that species names have two parts: a genus, which is a larger group of related species, and a species epithet, which indicates the exact species name. You learn that despite appearing so diverse, that tomato 🍅, potato 🥔, and eggplant 🍆 are so related to each other that they are in the same genus, Solanum, and all their species names begin with Solanum. So for example, domesticated tomato, potato, and eggplant are known as Solanum lycopersicum, Solanum tuberosum, and Solanum melongena, respectively.
You are given a list of Solanum species and you write a function to distinguish whether the species names are either the domesticated species or wild relatives of tomato, potato, and eggplant.
def tomato_potato_eggplant(species_list):
for i in range(len(species_list)): # for each species
species = species_list[i] # set the current species
# if a tomato species, print tomato
if species in ["Solanum lycopersicum",
"Solanum pimpinellifolium",
"Solanum habrochaites","Solanum pennellii"]:
print("It's a tomato 🍅!")
# else if a potato species, print potato
elif species in ["Solanum tuberosum",
"Solanum demissum",
"Solanum bulbocastanum",
"Solanum commersonii"]:
print("It's a potato 🥔!")
# else, it must be an eggplant!!!!
else:
print("It's an eggplant 🍆!")
However, when you try your function on the list of species names below, it only returns one value, that the species is an eggplant:
solanum_species = ["Solanum lycopersicum","Solanum pimpinellifolium","Solanum habrochaites",
"Solanum pennellii","Solanum tuberosum","Solanum demissum","Solanum bulbocastanum",
"Solanum commersonii","Solanum melongena","Solanum insanum","Solanum incanum","Solanum linnaeanum" ]
tomato_potato_eggplant(solanum_species)
It's an eggplant 🍆!
In the cell below, please answer:
What was the bug? What is preventing you from printing out whether each species is a tomato, potato, or eggplant? (2 points)
How did you figure out what the bug was? Please cite use of external sources or any internal logic that you used. (1 point)
✎ Put your answer here
In the cell below, fix the bug so that whether each species name in the list is a tomato, potato, or eggplant it is correctly printed out (2 points)
HINT: If you need to modify a block of text, select and highlight the text block in entirety you wish to modify
HINT: The output should be 4x tomatoes 🍅🍅🍅🍅, 4x potatoes 🥔🥔🥔🥔, and 4x eggplants 🍆🍆🍆🍆
#Modify the code below to fix the bug!
def tomato_potato_eggplant(species_list):
for i in range(len(species_list)): # for each species
species = species_list[i] # set the current species
# if a tomato species, print tomato
if species in ["Solanum lycopersicum",
"Solanum pimpinellifolium",
"Solanum habrochaites","Solanum pennellii"]:
print("it's a tomato 🍅!")
# else if a potato species, print potato
elif species in ["Solanum tuberosum",
"Solanum demissum",
"Solanum bulbocastanum",
"Solanum commersonii"]:
print("it's a potato 🥔!")
# else, it must be an eggplant!!!!
else:
print("it's an eggplant 🍆!")
solanum_species = ["Solanum lycopersicum","Solanum pimpinellifolium","Solanum habrochaites",
"Solanum pennellii","Solanum tuberosum","Solanum demissum","Solanum bulbocastanum",
"Solanum commersonii","Solanum melongena","Solanum insanum","Solanum incanum","Solanum linnaeanum" ]
tomato_potato_eggplant(solanum_species)
it's an eggplant 🍆!
DO NOT EDIT OR MOVE THIS CELL - Make sure your answer is above it!
3. Functions and if/else (10 Points)#
The goal of this question is to include the all topics you have learned about thus far in class in one problem. As such, this problem might be pretty challenging for you – that’s OK!
Do your best to solve the problem and remember that is possible to get partial credit on every question if you are able to figure out even part of the solution.
For this question you are given a list named “cars” where each of the elements in the list are lists themselves. The lists have the following items stored in them in order: [number of axles, number of wheels, weight, number of seats].
Your task is to write a function which takes a list which contains four elements as an argument.
Your function will take one of the lists found in our list, cars, and predict whether the vehicle is a sedan, truck, or a van.
The function should include a print statement that tells you what the vehicle type is.
Here are some pieces of information that may be useful in writing your function:
Sedans and vans have two axles and four wheels.
Sedans typically have 4-5 seats.
A truck can have two axles and four wheels, but it can also have more.
Trucks typically have fewer seats than sedans.
Vans come standard with 6 or more seats.
A typical sedan weighs about 2,500 pounds, a van weighs between 4,000 and 5,000 pounds, and trucks usually weigh between 7,000 and 10,000 pounds.
Once you write your function
Write a loop which goes through each of the lists in the list of cars and apply your function to determine whether it is a sedan, a truck, or a van.
If the vehicle cannot be classified, your function should print out a message to tell you this.
Once you are done, create a markdown cell and explain why you think the results of your function are correct and whether or not the results make sense.
#Write your code here
#This is the list that you must use for this problem
cars = [[2, 4, 2300, 4],[3, 6, 7500, 3],[2, 4, 4100, 7],[2, 4, 2800, 5],[2, 4, 5800, 2], [2, 4, 4800, 8], [2, 4, 2750, 4]]
#Write your function to determine what kind of vehicle something is based on its inputs
#Write a loop to apply your function to each list in "cars" and print out the type of vehicle it is
#Make a new markdown cell and explain why you agree with the results of your function
DO NOT EDIT OR MOVE THIS CELL - Make sure your answer is above it!
4. Numpy, matplotlib, and functions (18 Points)#
✅ 4.1 Making a plotting function (8 points)#
In CMSE 201, you will be making plots often. To help future you save time, you are going to write a function to use when you make plots!
In the cells below, write a function that takes in arrays of years and population values and displays a figure containing 4 subplots. Each subplot should display the population data in a different way.
Your figure should include: Use population_1, population_2 etc to create appropriate titles and legends for your plots. Your figure should include:
Subplot 1: Plot the first population using a solid line.
Subplot 2: Plot the second population using a dashed line with markers.
Subplot 3: Plot the third and fourth populations together on the same subplot so they can be compared.
Subplot 4: Plot the second, third, and fourth populations together on the same subplot.
Use plt.subplot() to organize the plots in a 2 × 2 layout.
Include appropriate axis labels, titles, colors, line styles, and a legend when more than one dataset appears on a subplot.
You must also test your function with the test data to receive full credit
Citation: US Census Bureau Historical Population Change data
import numpy as np
#TEST DATA
#Years
years = np.array([1910,1920,1930,1940,1950,1960,1970,1980,1990,2000,2010,2020])
#Alabama
population_1 = np.array([2138093,2348174,2646248,2832961,3061743,3266740,3444165,3893888,4040587,4447100,4779736,5024279])
#Alaska
population_2 = np.array([64356,55036,59278,72524,128643,226167,300382,401851,550043,626932,710231,733391])
#Arizona
population_3 = np.array([204354,334162,435573,499261,749587,1302161,1770900,2718215,3665228,5130632,6392017,7151502])
#Arkansas
population_4 = np.array([1574449,1752204,1854482,1949387,1909511,1786272,1923295,2286435,2350725,2673400,2915918,3011524])
#Names that correspond to the four population arrays
population_names = ["Alabama", "Alaska", "Arizona", "Arkansas"]
# put your answer here
✅ 4.3 More plotting (4 points)#
Along with this homework assignment, you will find a pop_data_HW.csv file with some additional state population data.
In the cell(s) below:
Load the population data for four states from the .csv file.
Store the population data for each state in a separate array.
Use the population_plots() function you created in the previous question to create four subplots using your new data.
Make sure you pass the appropriate year and population arrays to your function.
You should not rewrite the plotting code. Instead, reuse your function with the new data.
Remember that one advantage of functions is that they can be reused with different data.
Remember that you can open the .csv file in Jupyter to see how the data are organized!
# put your work here
DO NOT EDIT OR MOVE THIS CELL - Make sure your answer is above it!
Congratulations, you’re done!#
Submit this assignment by uploading it to the course GradeScope page, which you can find by using the dropdown menu on the right side of the navigation bar in D2L. Look for “Homework 02 - Student Notebook Submission” assignment and upload your Jupyter Notebook there – once it uploads, double-check that you submitted the version with your completed solutions! You should also get a confirmation that a PDF version of your submission was successfully built. We will grade the PDF version. Additional details for this submission process will be provided in class and share via Teams, email, and/or D2L.
For the full step-by-step process, see the Gradescope Submission Instructions on the course website.