Solutions
Quiz 01
Pseudocode:
set EXCHANGE_RATE = 1.0984
set FEE = 20
ask for name
ask for amount in CAD
display Hello, user
set result = (amount - FEE) * EXCHANGE_RATE
round result to 2 decimal points
display result
Python code:
EXCHANGE_RATE = 1.0984 # Australian dollars
FEE = 20 # Management fee
name = input("Who are you? ")
amount = float(input("Enter amount in CAD, $20 minimum: "))
print("Hello,", name, ".")
result = (amount - FEE) * EXCHANGE_RATE
result = round(result, 2)
print("Your $", amount, "CAD will buy you", result, "in AUD.")
Quiz 03
def exposure_limit(noise_level: float, base_level=85) -> float:
'''Args:
noise_level (float): how loud environment is in dBA
base_level (float, optional): ‘safe’ level, default = 85 dBA
Returns:
float: The permitted duration of exposure, in hrs. -1 if no time limit
'''
exposure = noise_level - base_level
if exposure <= 0:
result = -1
else:
if exposure <= 3:
result = 4
else:
if exposure <= 9:
result = 1
else:
result = 0.25
return result
Quiz 04
def smallest_items(any_list: list, k: int) -> list:
"""
Args: any non-empty list of numbers and
an integer k that must be less than the length of the list
Returns a sub-list of items from the passed list
that the k smallest.
"""
sorted_list = sorted(any_list)
return sorted_list[:k]
iteration = 5
while iteration < 26:
print(iteration)
iteration += 5
# Is equivalent to this
for iteration in range(5, 26, 5):
print(iteration)
a = [1,2,3,4,5,6]
for index in range(len(a)-2):
print(a[index])
# Is equivalent to this
a = [1, 2, 3, 4, 5, 6]
index = 0
while index < len(a) - 2:
print(a[index])
index += 1
List c looks like: [[4, 40], [3, 30], [2, 20], [1, 10]]
and the value at c[2][0] has a value of: 2
Quiz 05
def csv_to_2d_list(filename: str) -> list[list]:
"""
Takes a csv filename as string and turns it into a 2D list.
Returns a 2D list.
"""
result = []
f = open(filename, "r")
for line in f:
line = line.strip()
columns = line.split(",")
row = []
for item in columns:
item = item.strip()
if item.lower() == "yes":
row.append(True)
elif item.lower() == "no":
row.append(False)
else:
try:
number = int(item)
row.append(number)
except ValueError:
row.append(item)
result.append(row)
f.close()
return result
def swap_col_rows(data: list[list], filename: str) -> None:
"""
Swaps rows and columns of a given 2D list and
writes the content into a file with each row on a separate line.
"""
num_cols = len(data[0])
num_rows = len(data)
swapped = []
for col_index in range(num_cols):
row = []
for row_index in range(num_rows):
row.append(data[row_index][col_index])
swapped.append(row)
f = open(filename, "w")
for row in swapped:
row_list = []
for item in row:
row_list.append(str(item))
f.write(",".join(row_list) + "\n")
f.close()
def main() -> None:
result = csv_to_2d_list("marx.csv")
swap_col_rows(result, "brothers.csv")
main()