# debugging
def find_max(scores):
max = scores[0]
for s in scores:
if s > max:
max = s
return max
scores = [90, 83, 85, 96, 82,71]
max = find_max(scores)
print("the highest score is: ", max)
the highest score is: 96
# approximating average
import numpy as np
def f(x):
return x**2 + 2*x + 1
a = 0
b = 5
xs = np.linspace(0,5,100)
vectorized = np.vectorize(f)
ys = vectorized(xs)
deltax = xs[1] - xs[0]
average = np.sum(ys*deltax) / (b-a)
print(f"approximate average is: {average}")
approximate average is: 14.52062714688977
# Extra practice problems
#Write a function that takes a dictionary of type dict[str, int]
#and creates a new dictionary sorted by the keys in alphabetical
#order.
def sort_dict(d: dict[str, int]) -> dict[str, int]:
new_d = {}
sorted_keys = sorted(d)
for key in sorted_keys:
new_d[key] = d[key]
return new_d
sort_dict({"a": 1, "c": 3, "b": 2})
{'a': 1, 'b': 2, 'c': 3}
#Write a function that sorts a list of numbers from highest to
#lowest with mutation. Write annotations, a docstring, and tests
#for this function.
def sort_list(lst: list[float]) -> list[float]:
"""Return the list lst sorted from highest to lowest
and mutate lst"""
lst.sort(reverse = True)
return lst
sort_list([1.6, -2.0, 9.0])
[9.0, 1.6, -2.0]
#Write a function that prints the first word from each line of
#a text file.
def first_word(filename: str) -> None:
with open(filename) as ifh:
for line in ifh:
print(line.split()[0])
# create your own text file to test this
first_word("myText.txt")
Hello print only thanks!
#Write a function that opens the CSV file as a dictionary and
#add all the values under a given key.
import csv
def add_column(filename: str, myKey: str) -> float:
with open(filename) as ifh:
fileCSV = csv.DictReader(ifh)
fieldnames = list(fileCSV.fieldnames or [])
assert myKey in fieldnames, "key must be valid"
sum = 0.0
for line in fileCSV:
sum += float(line[myKey])
return sum
# use the tutorial 6 students.csv file to test this
assert abs(add_column("Students.csv", "Age") - 158.0) < 0.001
annotateMe: tuple[dict[int, str], float] = ({1: "hi"}, 7.0)
Indexing = (["four", "me", ["you"]], {3: "see", 9: "hello", 10: "hi"}, "same")
Indexing[1][10]
'hi'