2025-01-13
Max. 100 points
Name:
Task | Max. | Achieved |
---|---|---|
1 | 50 | |
2 | 50 | |
Sum | 100 |
count_words(text: str) -> dict
in Python that takes a string and returns a dictionary containing how
often each word occurs in the string.
Words are mainly delimited by whitespace, but they may also be delimited
by '.', ':', ',', '!', '?'
. Hint: you have to split the input
at any of these characters as well as on whitespace.text
as keys and the number of times each word occurs
as values.count_words('Hello') # -> {'hello': 1}
count_words('Hello world!') # -> {'hello': 1, 'world': 1}
count_words('Hello world! Hello hello') # -> {'hello': 3, 'world': 1}
count_words('Peace. Peace, peace. PEACE! Plz.') # -> {'peace': 4, 'plz': 1}
(50 points)
def count_words(text: str) -> dict:
"""
Return how often each word occurs in `text`.
"""
for delimiter in {'.', ':', ',', '!', '?'}:
text = text.replace(delimiter, ' ')
words = text.lower().split()
counts = {}
for word in words:
counts[word] = counts.get(word, 0) + 1
return counts
2024-01-02T19:49,1100 2024-01-02T19:59,1100 2024-01-02T20:09,1200 ... 2024-01-02T22:09,700 2024-01-02T22:19,800Implement a function
average_co2(filename)
that returns
the average CO2 in the given file. As example, execute the function on a
file named "sensor1_2024-01-02.csv". Assume the file contains the data above
(only the 5 visible data lines). The average then is
(1100 + 1100 + 1200 + 700 + 800) / 5 = 4900 / 5 = 980.0. In that case,
running the function looks like
average_co2('sensor1_2024-01-02.csv') # returns 980.0
Add a proper docstring, a sample doctest, and type annotations to the
function to receive full points. (50 points)def average_co2(filename: str) -> float:
"""
Return average CO2 from the given file.
>>> average_co2('sensor1_2024-01-02.csv')
980.0
"""
count = 0
total = 0
with open(filename) as f:
for line in f:
total += int(line.split(',')[-1])
count += 1
return total / count