Exercise 1: Python basics
Abschlussbedingungen
Exercise 1: Python basics
from typing import List, Tuple, Union, Dict
with open("names.txt") as f:
= [line.strip() for line in f if line]
names print(f"Number of names: {len(names)}")
print(names[::1000])
class NamesDataset:
"""
Implement all methods in this class,
such that the output type fulfills the type annotations
and their behavior follows the description in the doc-strings.
"""
def __init__(self, names: List[str]):
"""
The constructor must save the names as an attribute.
"""
def query(self, prefix: str) -> List[str]:
"""
The query method takes in a prefix and returns a list
of all names in the dataset that start with the given prefix.
"""
def longest_name(self, prefix: str = None, return_len: bool = False) -> Union[str, Tuple[str, int]]:
"""
The longest_name method returns the longest name in the dataset.
It also must support filtering the names by the prefix.
If a prefix is given, than it should return the longest name, starting with the prefix
Additionally, if the return_len argument is True, it should output the longest name.
AND its length (as tuple).
"""
def mean_name_length(self) -> float:
"""
This method computes the mean length of all names in the dataset.
"""
def ngrams(self, size: int, prefix: str = None) -> List[str]:
"""
This method returns a list of all character n_grams of all names (or those starting with a given prefix).
The size determines the size of the n_grams.
"""
def count_ngrams(self, size: int, prefix: str = None) -> List[Tuple[str, int]]:
"""
This method returns a list of tuples containing all n_grams created with the given the arguments
and their frequency within all n_grams found under the parameters.
The list should be sorted in ascending order.
"""
- 12. Oktober 2023, 13:56