added tut11 notes

This commit is contained in:
2024-01-18 13:33:28 +01:00
parent 7ab54d324d
commit c7d9b69c6d
3 changed files with 251 additions and 15 deletions

View File

@ -1,7 +1,5 @@
from typing import Callable, Iterable, Iterator
type Optional[T] = T | None
from typing import Any, Callable, Iterable, Iterator
def map[T, R](func: Callable[[T], R], xs: Iterable[T]) -> Iterable[R]:
return [func(x) for x in xs]
@ -13,17 +11,25 @@ def filter[T](func: Callable[[T], bool], xs: Iterable[T]) -> Iterable[T]:
def reduce[T](func: Callable[[T, T], T], xs: Iterable[T]) -> T:
it: Iterator[T] = iter(xs)
value: T
try:
x: T = next(it)
except StopIteration:
value: T | None = None
for x in it:
match value:
case None:
value = x
case _:
value = func(value, x)
if not value:
raise TypeError("can't reduce empty list")
else:
value = x
for y in it:
value = func(value, y)
return value
def flatten(xs: Iterable[Any]) -> Iterable[Any]:
new_list = []
for s in xs:
if isinstance(s, Iterable):
new_list.append(flatten(s))
else:
new_list.append([s])
return new_list
def compose[T](*funcs: Callable[[T], T]) -> Callable[[T], T]:
return reduce(lambda f, g: lambda n: f(g(n)), funcs)
@ -46,3 +52,4 @@ print(list(
[1, 2, 3, 4, "hello_world"]))))
print(list(filter(lambda e: isinstance(e, int), [1, 2, 3, "hello"])))
print(list(flatten([[1, 2, 3], 4, [[5, 6], 7, [8, 9]]])))