Make me look good. Click on the cell below and press Ctrl+Enter.
from IPython.core.display import HTML
HTML(open('css/custom.css', 'r').read())
Problem 1. Refactoring is the process of restructuring computer code without changing its external behavior. Typically, we refactor our code to make it easier to read, less complex, and more flexible.
Take a look at the code below. Note that midshipmen
is a list of dictionaries.
midshipmen = [
{'name': 'foraker', 'company': 3, 'preference': 'NFO'},
{'name': 'uhan', 'company': 17, 'preference': 'Marine Ground'},
{'name': 'traves', 'company': 11, 'preference': 'Nuke SWO'},
{'name': 'phillips', 'company': 5, 'preference': 'SWO'},
{'name': 'svirsko', 'company': 25, 'preference': 'Navy Pilot'}
]
mid = midshipmen[0]
print(f"Name: {mid['name'].title()}")
print(f"Company: {mid['company']}")
print(f"Service assignment preference: {mid['preference']}\n")
mid = midshipmen[1]
print(f"Name: {mid['name'].title()}")
print(f"Company: {mid['company']}")
print(f"Service assignment preference: {mid['preference']}\n")
mid = midshipmen[2]
print(f"Name: {mid['name'].title()}")
print(f"Company: {mid['company']}")
print(f"Service assignment preference: {mid['preference']}\n")
mid = midshipmen[3]
print(f"Name: {mid['name'].title()}")
print(f"Company: {mid['company']}")
print(f"Service assignment preference: {mid['preference']}\n")
mid = midshipmen[4]
print(f"Name: {mid['name'].title()}")
print(f"Company: {mid['company']}")
print(f"Service assignment preference: {mid['preference']}\n")
Name: Foraker Company: 3 Service assignment preference: NFO Name: Uhan Company: 17 Service assignment preference: Marine Ground Name: Traves Company: 11 Service assignment preference: Nuke SWO Name: Phillips Company: 5 Service assignment preference: SWO Name: Svirsko Company: 25 Service assignment preference: Navy Pilot
Refactor the code above by following these steps:
Write a function print_info
that takes a dictionary containing a midshipman's information as input, and prints the midshipman's information in a format similar to above. Assume that the input dictionary has keys name
, company
, and preference
. The function should print each piece of information on a separate line, like this:
Name: midshipman's name
Company: midshipman's company number
Service assignment preference: midshipman's preference
Without comments or extra blank lines, you should be able to define this function in 4 lines.
Write a for
loop that iterates over the list midshipmen
defined above, and prints each midshipman's information using the print_info
function you defined earlier. Without comments or extra blank lines, you should be able to write this for
loop in 2 lines.
Hopefully, your new code is more compact, less repetitive, and easier to read than the code above!
midshipmen = [
{'name': 'foraker', 'company': 3, 'preference': 'NFO'},
{'name': 'uhan', 'company': 17, 'preference': 'Marine Ground'},
{'name': 'traves', 'company': 11, 'preference': 'Nuke SWO'},
{'name': 'phillips', 'company': 5, 'preference': 'SWO'},
{'name': 'svirsko', 'company': 25, 'preference': 'Navy Pilot'}
]
# Write your code below
def print_info(mid):
"""Prints information about a midshipman from a dictionary."""
print(f"Name: {mid['name'].title()}")
print(f"Company: {mid['company']}")
print(f"Service assignment preference: {mid['preference']}\n")
for mid in midshipmen:
print_info(mid)
Name: Foraker Company: 3 Service assignment preference: NFO Name: Uhan Company: 17 Service assignment preference: Marine Ground Name: Traves Company: 11 Service assignment preference: Nuke SWO Name: Phillips Company: 5 Service assignment preference: SWO Name: Svirsko Company: 25 Service assignment preference: Navy Pilot
Problem 2. Recall that we can convert degrees Fahrenheit to degrees Celsius with the following formula:
$$ \text{degrees Celsius} = \frac{5}{9} (\text{degrees Fahrenheit} - 32). $$Write a function named fahrenheit_to_celsius
that takes a value in degrees Fahrenheit, and returns the equivalent temperature in degrees Celsius.
def fahrenheit_to_celsius(deg_f):
"""Converts deg_f to the equivalent temperature in degrees Celsius, returns the value."""
return (5 / 9) * (deg_f - 32)
Test your function with the code cell below. You should see the output:
97 degrees Fahrenheit is equivalent to 36.11 degrees Celsius.
Note that the cell below uses an f-string with a format specifier: {deg_c:.2f}
prints the value of deg_c
, but with 2 decimal places.
# DO NOT MODIFY THE CODE IN THIS CELL
deg_c = fahrenheit_to_celsius(97)
print(f"97 degrees Fahrenheit is equivalent to {deg_c:.2f} degrees Celsius.")
97 degrees Fahrenheit is equivalent to 36.11 degrees Celsius.
Problem 3. Recall the estimate_temperature
function from Lesson 6, that takes the number of field cricket chirps in 15 seconds as input, and outputs the estimated temperature in Fahrenheit. The function is defined in the code cell below:
def estimate_temperature(n_chirps):
"""Estimate temperature based on number of chirps in 15 seconds."""
# The number of seconds it took the cricket to chirp n_chirps times
time = 15
# Determine the number of chirps per minute
chirps_per_minute = n_chirps * (60 / time)
# Estimated temperature (in degrees Fahrenheit)
est_temp = (chirps_per_minute + 40) / 4
# Return the answer
return est_temp
Using the function fahrenheit_to_celsius
you wrote in the problem above, and the function estimate_temperature
defined in the code cell above, write code that prints the estimated temperature in degrees Celsius when there are 75 chirps in 15 seconds. Do this in one line of code.
print(fahrenheit_to_celsius(estimate_temperature(75)))
29.444444444444446
Problem 4. A triangular number counts objects arranged in an equilateral triangle. The $n$th triangular number is the number of dots in the triangular arrangement with $n$ dots on a side, and is equal to the sum of the $n$ natural numbers from 1 to $n$. The sequence of triangluar numbers, starting at the 0th triangular number, is
There is a formula for the $n$th triangular number: \begin{equation*} T_n = \frac{n(n+1)}{2} \end{equation*}
In the code cell below, write a Python function named triangular_number
that takes n
as an argument, and returns the n
th triangular number.
def triangular_number(n):
"""Returns the nth triangular number."""
return (n * (n + 1)) / 2
Test your function with the code cell below. You should see the output:
The 14th triangular number is 105.0.
# DO NOT MODIFY THE CODE IN THIS CELL
my_triangular_number = triangular_number(14)
print(f"The 14th triangular number is {my_triangular_number}.")
The 14th triangular number is 105.0.
Note. Why are triangular numbers useful? The triangular number $T_n$ measures the number of possible one on one interactions among $n+1$ people. For instance, among $4$ people, there are $T_3 = 6$ possible connections one on one interactions: AB, AC, AD, BC, BD, and CD.
Most animals can only manage a small number of relationships to other animals. A group of 4 dogs can monitor the 6 one-on-one relationships in the pack. A group of 15 dogs would have trouble keeping track of the 120 relationships among the pack. The pack would likely splinter into smaller groups. Humans can use language to manage many more relationships but keeping track of the 435 relationships among 30 people would be difficult. This is one reason that military squads tend to be small.
Similarly, the $T_{19} = 190$ wires are needed to connect 20 computers to each other directly. This number grows (close to) quadratically: if we double the number of computers, we require approximately four times as many wires. In face, we require $T_{39} = 780$ wires to connect 40 computers directly to each other.
Problem 5. Write a function named buno_frequency
that takes two arguments:
aircraft_ids
, consisting of strings representing aircraft identifiers, andbuno
that represents a specific aircraft identifier.The function should return the number of times the value stored in buno
appears in the list aircraft_ids
.
def buno_frequency(aircraft_ids, buno):
"""Returns the number of times buno appears in aircraft_ids."""
# Initialize frequency to 0
freq = 0
# Iterate through list of aircraft ids
# Count how many are the same as buno
for i in aircraft_ids:
if i == buno:
freq += 1
return freq
Test your function with the code cell below. You should see the output:
The BUNO 165908 appears 3 times in the list.
# DO NOT MODIFY THE CODE IN THIS CELL
aircraft_ids = ['165904', '165908', '165910', '165904', '166902', '165908',
'166902', '166910', '164482', '165908', '165904', '166902']
buno = '165908'
num_times = buno_frequency(aircraft_ids, buno)
print(f"The BUNO {buno} appears {num_times} times in the list.")
The BUNO 165908 appears 3 times in the list.
Problem 6. Write a function named sum_and_product
that takes a list called numbers
as input, and returns a list consisting of two values: (1) the sum of the values in numbers
, and (2) the product of the values in numbers
.
def sum_and_product(numbers):
"""Returns the sum and product of the values in the list numbers."""
my_sum = 0
my_product = 1
for i in numbers:
my_sum = my_sum + i
my_product = my_product * i
return [my_sum, my_product]
Test your function with the code cell below. You should see the output:
The sum of these numbers is 24 and the product of these numbers is -40320.
# DO NOT MODIFY THE CODE IN THIS CELL
numbers = [5, 7, -2, 8, 6, -3, 4, -1]
output = sum_and_product(numbers)
print(f"The sum of these numbers is {output[0]} and the product of these numbers is {output[1]}.")
The sum of these numbers is 24 and the product of these numbers is -40320.
Problem 7. Look at the code in the cell below. Before you run the code, what do you think the results will be for the two print statements? Write your answers below, then run the code to see if you were correct.
print(x)
will result in the following:Write your answer here. Double-click to edit.
print(my_value)
will result in the following:Write your answer here. Double-click to edit.
# ANSWER THE QUESTIONS ABOVE BEFORE RUNNING THIS CELL
x = 2
def my_function(x):
x = 500
return x
my_value = my_function(x)
print(x)
print(my_value)
2 500
Did you get the correct results for the two print statements? Read the aside below.
Not all variables are accessible from all parts of our code.
The part of our code where a variable is accessible is called its scope.
A variable defined inside a function is local to that function:
The arguments/parameters in the function definition also behave like local variables.
Problem 8. Look at the code in the cell below. Before you run the code, what do you think the results will be for the two print statements? Write your answers below, then run the code to see if you were correct.
print(my_name)
will result in the following:Write your answer here. Double-click to edit.
print(cap_first_name)
will result in the following:Write your answer here. Double-click to edit.
# ANSWER THE QUESTIONS ABOVE BEFORE RUNNING THIS CELL
first_name = 'jay'
last_name = 'foraker'
def full_name_function(a ,b):
cap_first_name = a.title()
cap_last_name = b.title()
full_name = f'{cap_first_name} {cap_last_name}'
return full_name
my_name = full_name_function(first_name, last_name)
print(my_name)
print(cap_first_name)
Jay Foraker
--------------------------------------------------------------------------- NameError Traceback (most recent call last) <ipython-input-15-868756c1d1b3> in <module>() 11 my_name = full_name_function(first_name, last_name) 12 print(my_name) ---> 13 print(cap_first_name) NameError: name 'cap_first_name' is not defined
Running the code in the cell above resulted in a NameError
because cap_first_name
was only defined inside the function full_name_function
.
The cell below contains a copy of the code that produced the error. Modify the code in the cell below so that the two print statements in the next code cell produces the following output:
print(my_name[0])
Jay Foraker
print(my_name[1])
Jay
# MODIFY the code in this cell
first_name = 'jay'
last_name = 'foraker'
def full_name_function(a, b):
cap_first_name = a.title()
cap_last_name = b.title()
full_name = f'{cap_first_name} {cap_last_name}'
return [full_name, cap_first_name]
my_name = full_name_function(first_name, last_name)
# DO NOT MODIFY THE CODE IN THIS CELL
# Run this code AFTER you've modified the code in the cell above
print(my_name[0])
print(my_name[1])
Jay Foraker Jay