18 Commits
Author SHA1 Message Date
schaermicha1 aea0c0173d last week's exercises / katas 2026-05-30 12:49:43 +02:00
schaermicha1 eb6a242257 Merge pull request 'sw7 detect laps from coordinates' (#9) from sw7_lap_detection into master
Reviewed-on: #9
2026-05-08 15:45:24 +02:00
schaermicha1 f03c720435 Merge remote-tracking branch 'origin/master' into sw7_lap_detection 2026-04-11 23:10:28 +02:00
schaermicha1 45921bfe17 sw7 detect laps from coordinates 2026-04-11 15:51:34 +02:00
schaermicha1 0b02a65bd4 Merge pull request 'sw6 testing hands on' (#8) from sw6_testing into master
Reviewed-on: #8
2026-03-27 21:01:54 +01:00
schaermicha1 f089317e86 sw6 testing hands on 2026-03-27 21:01:31 +01:00
schaermicha1 5d0aa9c876 Merge pull request 'process orders with error handling' (#7) from process_orders_error_handling into master
Reviewed-on: #7
2026-03-27 20:45:39 +01:00
schaermicha1 155b92b937 Merge pull request 'SW4 Codewars Exercises' (#6) from sw4_codewars_exercises into master
Reviewed-on: #6
2026-03-27 20:44:58 +01:00
schaermicha1 327e9497b6 process orders with error handling 2026-03-22 19:23:20 +01:00
schaermicha1 ecf4a2ed7a Add exercises from sw5 theory lesson 2026-03-20 15:18:03 +01:00
schaermicha1 5d7063afa2 Add test files for PandasTutorial.py 2026-03-19 02:04:05 +01:00
schaermicha1 9134f059da refactor WhoLikesIt.py and PandasTutorial.py 2026-03-13 21:01:04 +01:00
schaermicha1 d0609303dc train kata "Simple Web Framework" 2026-03-13 20:57:09 +01:00
schaermicha1 323687c00d train kata "Pandas Tutorial" 2026-03-13 19:32:01 +01:00
schaermicha1 b11ca22119 train kata "Who likes it?" 2026-03-13 19:06:10 +01:00
schaermicha1 4f1450fe6e add module exercises 2026-03-13 18:51:03 +01:00
schaermicha1 978db954d2 Merge pull request 'add analysis module' (#5) from sw4_analyis_module into master
Reviewed-on: #5
2026-03-13 18:50:20 +01:00
schaermicha1 fb97703cdd add analysis module 2026-03-12 15:07:47 +01:00
72 changed files with 19564 additions and 2 deletions

No files matched your search

+1 -1
View File
@@ -13,6 +13,6 @@ repos:
- id: ruff # Linting - id: ruff # Linting
- repo: https://github.com/psf/black - repo: https://github.com/psf/black
rev: stable rev: 26.3.1
hooks: hooks:
- id: black # formatting - id: black # formatting
File renamed without changes.
+13
View File
@@ -0,0 +1,13 @@
from analysis.io import load_sales
from analysis.metrics import revenue_per_day
from analysis.plotting import plot_daily_revenue
def main() -> None:
df = load_sales("resources/sales.csv")
daily = revenue_per_day(df)
plot_daily_revenue(daily)
if __name__ == "__main__":
main()
+5
View File
@@ -0,0 +1,5 @@
import pandas as pd
def load_sales(path: str) -> pd.DataFrame:
return pd.read_csv(path, sep=",", encoding="utf-8")
+6
View File
@@ -0,0 +1,6 @@
import pandas as pd
def revenue_per_day(df: pd.DataFrame) -> pd.Series:
revenue = df["quantity"] * df["unit_price"]
return revenue.groupby(df["day"]).sum()
+9
View File
@@ -0,0 +1,9 @@
import matplotlib.pyplot as plt
import pandas as pd
def plot_daily_revenue(daily: pd.Series) -> None:
daily.plot(kind="bar")
plt.title("Daily Revenue")
plt.tight_layout()
plt.show()
+21
View File
@@ -0,0 +1,21 @@
import pandas as pd
def export_csv_with_name_and_grade(student_name: str, grade: str):
students_df = pd.read_csv("files/students.csv", index_col=False)
grades_df = pd.read_csv("files/grades.csv", index_col=False)
students_grades_df = students_df.merge(
grades_df, left_on="Student_ID", right_on="ID"
)
solution = students_grades_df[
(students_grades_df["Name"] == student_name)
& (students_grades_df["Grade"] == grade)
]
solution[["Student_ID", "Class"]].to_csv("files/output.csv", index=False)
if __name__ == "__main__":
export_csv_with_name_and_grade("Bob", "A")
+53
View File
@@ -0,0 +1,53 @@
import typing
class Router(object):
def __init__(self):
self.routes = {}
def bind(self, path: str, method: str, func: typing.Callable):
self.routes[(path, method)] = func
def run_request(self, path: str, method: str):
return self.routes.get((path, method), lambda: "Error 404: Not Found")()
if __name__ == "__main__":
# Should handle GET routes'
router = Router()
router.bind("/hello", "GET", lambda: "hello world")
router.bind("/login", "GET", lambda: "Please log-in.")
assert router.run_request("/hello", "GET") == "hello world"
assert router.run_request("/login", "GET") == "Please log-in."
# Should handle POST routes
router = Router()
router.bind("/vote", "POST", lambda: "Voted.")
router.bind("/comment", "POST", lambda: "Comment sent.")
assert router.run_request("/vote", "POST") == "Voted."
assert router.run_request("/comment", "POST") == "Comment sent."
# Should handle mixed routes.
router = Router()
router.bind("/login", "GET", lambda: "Please log-in.")
router.bind("/login", "POST", lambda: "Logging-in.")
assert router.run_request("/login", "GET") == "Please log-in."
assert router.run_request("/login", "POST") == "Logging-in."
# Should return 404 for non-existing routes.
router = Router()
assert (
router.run_request("/this-url-does-not-exist", "GET") == "Error 404: Not Found"
)
# Should modify existing routes
router = Router()
router.bind("/page", "GET", lambda: "First binding.")
router.bind("/page", "GET", lambda: "Modified binding.")
assert router.run_request("/page", "GET") == "Modified binding."
print("All tests passed!")
+24
View File
@@ -0,0 +1,24 @@
def likes(names):
match len(names):
case 0:
return "no one likes this"
case 1:
return f"{names[0]} likes this"
case 2:
return f"{names[0]} and {names[1]} like this"
case 3:
return f"{names[0]}, {names[1]} and {names[2]} like this"
case _:
return f"{names[0]}, {names[1]} and {len(names) - 2} others like this"
if __name__ == "__main__":
assert likes([]) == "no one likes this"
assert likes(["Peter"]) == "Peter likes this"
assert likes(["Jacob", "Alex"]) == "Jacob and Alex like this"
assert likes(["Max", "John", "Mark"]) == "Max, John and Mark like this"
assert (
likes(["Alex", "Jacob", "Mark", "Max"]) == "Alex, Jacob and 2 others like this"
)
print("All tests passed!")
+303
View File
@@ -0,0 +1,303 @@
PERIODIC_TABLE: dict[str, tuple[int, float | int]] = {
"H": (1, 1.0),
"B": (3, 10.8),
"C": (4, 12.0),
"N": (3, 14.0),
"O": (2, 16.0),
"F": (1, 19.0),
"Mg": (2, 24.3),
"P": (3, 31.0),
"S": (2, 32.1),
"Cl": (1, 35.5),
"Br": (1, 80.0),
}
class LockedMolecule(Exception):
pass
class UnlockedMolecule(Exception):
pass
class InvalidBond(Exception):
pass
class EmptyMolecule(Exception):
pass
class Atom(object):
def __init__(self, elt: str, id_: int):
self.element = elt
self.id = id_
self.bounds = []
self.max_bounds = PERIODIC_TABLE[self.element][0]
self.weight = PERIODIC_TABLE[self.element][1]
def __hash__(self):
return self.id
def __eq__(self, other):
return self.id == other.id
def __str__(self):
bounds = []
bounds.extend(
list(sorted(Molecule.filter_element(self.bounds, "C"), key=lambda b: b.id))
)
bounds.extend(
list(sorted(Molecule.filter_element(self.bounds, "O"), key=lambda b: b.id))
)
for bound in list(
sorted(sorted(self.bounds, key=lambda b: b.id), key=lambda b: b.element)
):
if bound.element not in ["C", "H", "O"]:
bounds.append(bound)
bounds.extend(
list(sorted(Molecule.filter_element(self.bounds, "H"), key=lambda b: b.id))
)
return (
f"Atom({self.element}.{self.id}"
f"{': ' if bounds else ''}"
f"{','.join(bound.element + (str(bound.id) if bound.element != 'H' else '') for bound in bounds)})"
)
def add_bound(self, atom):
if self == atom:
raise InvalidBond
if len(self.bounds) >= self.max_bounds:
raise InvalidBond
self.bounds.append(atom)
@staticmethod
def remove_bounds(atom1, atom2):
if not (atom1 or atom2):
return
if atom1 in atom2.bounds:
atom2.bounds.remove(atom1)
if atom2 in atom1.bounds:
atom1.bounds.remove(atom2)
def mutate(self, element: str):
if len(self.bounds) > PERIODIC_TABLE[element][0]:
raise InvalidBond
self.element = element
self.max_bounds = PERIODIC_TABLE[self.element][0]
self.weight = PERIODIC_TABLE[self.element][1]
def unlock(self):
self.bounds = list(filter(lambda atom: atom.element != "H", self.bounds))
class Molecule(object):
name: str
_formula: str
_molecular_weight: float
atoms: list[Atom]
branches: dict[int, list[Atom]]
locked: bool = False
exception_thrown = False
def __init__(self, name=""):
self.name = name
self.atoms = []
self.branches = {}
@staticmethod
def filter_element(atoms: list[Atom], element: str) -> list[Atom]:
return list(filter(lambda atom: element == atom.element, atoms))
def brancher(self, *branches: int):
if self.locked:
raise LockedMolecule
for carbons in branches:
branch_id = len(self.branches) + 1
self.branches[branch_id] = []
for i in range(1, carbons + 1):
atom = Atom(elt="C", id_=len(self.atoms) + i)
self.branches[branch_id].append(atom)
if i > 1:
last_atom = self.branches[branch_id][i - 2]
try:
atom.add_bound(last_atom)
last_atom.add_bound(atom)
except InvalidBond as e:
Atom.remove_bounds(atom, last_atom)
raise e
self.atoms.extend(self.branches[branch_id])
return self
def bounder(self, *bounds: tuple[int, int, int, int]):
if self.locked:
raise LockedMolecule
for c1, b1, c2, b2 in bounds:
atom1 = self.branches[b1][c1 - 1]
atom2 = self.branches[b2][c2 - 1]
atom1_bounds = atom1.bounds[:]
atom2_bounds = atom2.bounds[:]
try:
atom1.add_bound(atom2)
atom2.add_bound(atom1)
except InvalidBond as e:
atom1.bounds = atom1_bounds
atom2.bounds = atom2_bounds
raise e
return self
def mutate(self, *mutations: tuple[int, int, str]):
if self.locked:
raise LockedMolecule
for nc, nb, element in mutations:
atom = self.branches[nb][nc - 1]
try:
atom.mutate(element)
except InvalidBond as e:
raise e
return self
def add(self, *additions: tuple[int, int, str]):
if self.locked:
raise LockedMolecule
for nc, nb, element in additions:
atom = Atom(elt=element, id_=len(self.atoms) + 1)
carbon = self.branches[nb][nc - 1]
try:
carbon.add_bound(atom)
atom.add_bound(carbon)
except InvalidBond as e:
Atom.remove_bounds(carbon, atom)
raise e
self.atoms.append(atom)
return self
def add_chaining(self, nc: int, nb: int, *elements: str):
if self.locked:
raise LockedMolecule
carbon = self.branches[nb][nc - 1]
chain = []
try:
last_atom = Atom(elt=elements[0], id_=len(self.atoms) + len(chain) + 1)
chain.append(last_atom)
for element in elements[1:]:
atom = Atom(elt=element, id_=len(self.atoms) + len(chain) + 1)
chain.append(atom)
last_atom.add_bound(atom)
atom.add_bound(last_atom)
last_atom = atom
except InvalidBond as e:
Atom.remove_bounds(atom, last_atom)
raise e
try:
carbon.add_bound(chain[0])
chain[0].add_bound(carbon)
except InvalidBond as e:
Atom.remove_bounds(carbon, chain[0])
raise e
self.atoms.extend(chain)
return self
def closer(self):
if self.locked:
raise LockedMolecule
try:
for atom in self.atoms:
while len(atom.bounds) < atom.max_bounds:
hydrogen = Atom(elt="H", id_=len(self.atoms) + 1)
atom.add_bound(hydrogen)
hydrogen.add_bound(atom)
self.atoms.append(hydrogen)
except InvalidBond as e:
Atom.remove_bounds(atom, hydrogen)
raise e
self.locked = True
return self
def unlock(self):
self.locked = False
self.atoms = list(filter(lambda atom: atom.element != "H", self.atoms))
for new_id, atom in enumerate(self.atoms, start=1):
atom.unlock()
atom.id = new_id
new_branches = {}
new_id = 1
for atoms in self.branches.values():
filtered = list(filter(lambda atom: atom.element != "H", atoms))
if len(filtered) > 0:
new_branches[new_id] = filtered
new_id += 1
self.branches = new_branches
if not self.branches:
raise EmptyMolecule
return self
@property
def formula(self) -> str:
if not self.locked:
raise UnlockedMolecule
elements = set(atom.element for atom in self.atoms)
formula = ""
if "C" in elements:
c_len = len(Molecule.filter_element(self.atoms, "C"))
formula += f"C{c_len if c_len > 1 else ''}"
if "H" in elements:
h_len = len(Molecule.filter_element(self.atoms, "H"))
formula += f"H{h_len if h_len > 1 else ''}"
if "O" in elements:
o_len = len(Molecule.filter_element(self.atoms, "O"))
formula += f"O{o_len if o_len > 1 else ''}"
for element in list(sorted(elements)):
if element not in ["C", "H", "O"]:
num = len(Molecule.filter_element(self.atoms, element))
formula += f"{element}{num if num > 1 else ''}"
return formula
@property
def molecular_weight(self) -> float:
if not self.locked:
raise UnlockedMolecule
return sum(atom.weight for atom in self.atoms)
+32
View File
@@ -0,0 +1,32 @@
class VigenereCipher(object):
def __init__(self, key: str, alphabet: str):
self.key = key
self.alphabet = alphabet
def encode(self, text):
encoded_text = ""
for idx, c in enumerate(text):
alph_position = self.alphabet.find(c)
if alph_position == -1:
encoded_text += c
continue
shift = self.alphabet.find(self.key[idx % len(self.key)])
encoded_text += self.alphabet[(alph_position + shift) % len(self.alphabet)]
return encoded_text
def decode(self, text):
encoded_text = ""
for idx, c in enumerate(text):
alph_position = self.alphabet.find(c)
if alph_position == -1:
encoded_text += c
continue
shift = self.alphabet.find(self.key[idx % len(self.key)])
encoded_text += self.alphabet[(alph_position - shift) % len(self.alphabet)]
return encoded_text
+8
View File
@@ -0,0 +1,8 @@
ID,Class,Grade
32155,English,A
32155,History,B
32155,Science,B
43226,English,C
43226,Math,A
43226,Science,A
43226,History,B
1 ID Class Grade
2 32155 English A
3 32155 History B
4 32155 Science B
5 43226 English C
6 43226 Math A
7 43226 Science A
8 43226 History B
+2
View File
@@ -0,0 +1,2 @@
Student_ID,Class
32155,English
1 Student_ID Class
2 32155 English
+3
View File
@@ -0,0 +1,3 @@
Name,Student_ID
Bob,32155
Ron,43226
1 Name Student_ID
2 Bob 32155
3 Ron 43226
View File
Whitespace-only changes.
File renamed without changes.
@@ -72,3 +72,5 @@ print(dog2.bark(3))
print(dog2.is_puppy()) print(dog2.is_puppy())
print(Dog.amount_of_dogs) print(Dog.amount_of_dogs)
print(dog2 == dog1) print(dog2 == dog1)
print("is a dog", isinstance(dog1, Dog))
+31
View File
@@ -0,0 +1,31 @@
# Ziel dieses Skripts:
#
# 1. Das Produkt von 6 * 7 berechnen → Erwartet: 42.0
# 2. Die Kreisfläche für Radius 5 berechnen → Erwartet: ~78.54
# 3. Den genauen Wert von PI ausgeben → Erwartet: 3.141592653589793
#
# ----------------------------------------------------------------------
# AUFGABE: Das Skript liefert falsche Ergebnisse. Finde den Fehler und
# korrigiere die Import-Anweisungen – ohne den restlichen Code
# zu verändern!
# ----------------------------------------------------------------------
import src.mathematik as math # (1) Import aus mathematik
import src.geometrie as geo # (2) Import aus geometrie
def main():
# --- Aufgabe 1: Produkt berechnen (nutzt mathematik.berechne) ---
produkt = math.berechne(6, 7) # Erwartet: 42.0 — bekommt aber einen Fehler!
print(f"6 × 7 = {produkt}")
# --- Aufgabe 2: Kreisfläche (nutzt geometrie.berechne) ---
flaeche = geo.berechne(5) # Erwartet: ~78.54
print(f"Kreisfläche (r=5): {flaeche:.4f}")
# --- Aufgabe 3: PI-Wert ---
print(f"PI = {math.PI}") # Erwartet: 3.141592653589793
if __name__ == "__main__":
main()
View File
Whitespace-only changes.
+14
View File
@@ -0,0 +1,14 @@
# geometrie.py
# Modul für geometrische Berechnungen (Kreisflächen, Umfang usw.)
PI = 3.14 # Vereinfachter Wert (nur 2 Nachkommastellen!)
def berechne(radius: float) -> float:
"""Berechnet die Fläche eines Kreises: A = PI * r²"""
return PI * radius**2
def umfang(radius: float) -> float:
"""Berechnet den Umfang eines Kreises: U = 2 * PI * r"""
return 2 * PI * radius
+14
View File
@@ -0,0 +1,14 @@
# mathematik.py
# Modul für allgemeine mathematische Berechnungen
PI = 3.141592653589793 # Hochpräziser Wert
def berechne(a: float, b: float) -> float:
"""Berechnet das Produkt zweier Zahlen."""
return a * b
def potenz(basis: float, exponent: int) -> float:
"""Berechnet basis hoch exponent."""
return basis**exponent
+52
View File
@@ -0,0 +1,52 @@
# Ziel dieses Skripts:
#
# Testergebnisse einer Klasse auswerten und formatiert ausgeben.
#
# Gegeben: Punkte von 5 Studierenden (von max. 100 Punkten)
# Erwartet:
# Mittelwert → 73.5 (kaufm. gerundet → 74 → "Gut")
# Max. Punkte → 100 (aus statistik.MAX_WERT)
#
# ----------------------------------------------------------------------
# AUFGABE: Das Skript gibt falsche Werte aus. Es gibt keine Fehlermeldung
# vom Interpreter. Finde heraus, warum die Ergebnisse falsch sind
# und korrigiere die Import-Anweisungen!
# ----------------------------------------------------------------------
import src.statistik as stat # importiert: runde, mittelwert, bewerte, MAX_WERT, MIN_WERT
import src.formatierung as formatting # importiert: runde, als_prozent, trennlinie, MAX_WERT, MIN_WERT
PUNKTE = [92, 85, 61, 48, 82]
def auswertung():
print(formatting.trennlinie("="))
print(" TESTERGEBNISSE")
print(formatting.trennlinie("="))
# --- Mittelwert berechnen und benoten ---
mw = stat.mittelwert(PUNKTE)
mw_gerundet = stat.runde(mw) # Soll kaufm. auf int runden → Erwartet: 74
note = stat.bewerte(mw)
print(f" Mittelwert : {mw}")
print(f" Gerundet : {mw_gerundet} ← Erwartet: 74 (int)")
print(f" Durchschnittsnote: {note}")
print(formatting.trennlinie())
# --- Maximale Punktzahl aus dem Modul ---
print(f" Max. Punkte : {stat.MAX_WERT} ← Erwartet: 100")
print(formatting.trennlinie())
# --- Einzelne Ergebnisse ---
print(" Einzelergebnisse:")
for p in PUNKTE:
print(f" {p:>3} Punkte → {stat.bewerte(p)}")
print(formatting.trennlinie("="))
if __name__ == "__main__":
auswertung()
View File
Whitespace-only changes.
+21
View File
@@ -0,0 +1,21 @@
# formatierung.py
# Modul für Ausgabe-Formatierung und Darstellung
MAX_WERT = 255 # Maximaler RGB-Farbwert (0–255)
MIN_WERT = 0 # Minimaler RGB-Farbwert
def runde(wert: float, stellen: int = 2) -> float:
"""Rundet auf 'stellen' Nachkommastellen (für Anzeige-Formatierung)."""
faktor = 10**stellen
return int(wert * faktor + 0.5) / faktor
def als_prozent(wert: float, gesamt: float) -> str:
"""Gibt einen Wert als formatierten Prozentstring zurück."""
return f"{runde(wert / gesamt * 100)} %"
def trennlinie(zeichen: str = "-", laenge: int = 40) -> str:
"""Erzeugt eine Trennlinie für die Konsolenausgabe."""
return zeichen * laenge
+30
View File
@@ -0,0 +1,30 @@
# statistik.py
# Modul für statistische Berechnungen
MAX_WERT = 100 # Maximale Punktzahl in einem Test (0–100)
MIN_WERT = 0 # Minimale Punktzahl
def runde(wert: float) -> int:
"""Rundet kaufmännisch auf ganze Zahlen (für Testergebnisse)."""
return int(wert + 0.5)
def mittelwert(werte: list[float]) -> float:
"""Berechnet den arithmetischen Mittelwert einer Liste."""
return sum(werte) / len(werte)
def bewerte(punkte: float) -> str:
"""Gibt eine Note zurück basierend auf Punktzahl (0–100)."""
p = runde(punkte)
if p >= 90:
return "Sehr gut"
elif p >= 75:
return "Gut"
elif p >= 60:
return "Befriedigend"
elif p >= 45:
return "Ausreichend"
else:
return "Ungenügend"
+51
View File
@@ -0,0 +1,51 @@
# Lotterie-Simulation: Zieht 6 aus 45 Zahlen, dazu eine Zusatzzahl.
#
# Wiederholt die Ziehung 5× und gibt die Ergebnisse aus.
# Anschließend wird die Gewinnerliste zufällig gemischt.
#
# Erwartetes Verhalten:
# • Jede Ziehung liefert 6 VERSCHIEDENE, ZUFÄLLIGE Zahlen aus 1–45
# • Wiederholte Aufrufe liefern UNTERSCHIEDLICHE Ergebnisse
# • Die Teilnehmerliste ist nach dem Mischen in ZUFÄLLIGER Reihenfolge
#
# ----------------------------------------------------------------------
# AUFGABE: Das Programm läuft ohne Fehlermeldung, aber die Ergebnisse
# sind offensichtlich nicht zufällig. Finde die Ursache und
# behebe den Fehler – ohne ziehung.py oder statistik.py zu ändern!
#
# REMARK: Möglicherweise ist das Problem sogar abhängig von der verwendeten
# IDE... Lasst das main.py mal aus eurer IDE laufen sowie aus dem
# Terminal. Sind die Resultate gleich?
# ----------------------------------------------------------------------
from ziehung import ziehe_zahlen, ziehe_zusatzzahl
from statistik import simuliere_ziehungen, mische_teilnehmer
TEILNEHMER = ["Alice", "Bob", "Carol", "Dave", "Eve"]
def main():
print("=" * 45)
print(" LOTTO-SIMULATION (6 aus 45)")
print("=" * 45)
print("\n--- 5 unabhängige Ziehungen ---")
for i, ziehung in enumerate(simuliere_ziehungen(5), 1):
print(f" Ziehung {i}: {ziehung}")
print("\n--- Einzelziehung mit Zusatzzahl ---")
haupt = ziehe_zahlen()
zusatz = ziehe_zusatzzahl(haupt)
print(f" Hauptzahlen : {haupt}")
print(f" Zusatzzahl : {zusatz}")
print("\n--- Gewinnerliste (zufällig gemischt) ---")
gemischt = mische_teilnehmer(TEILNEHMER)
for rang, name in enumerate(gemischt, 1):
print(f" Rang {rang}: {name}")
print("=" * 45)
if __name__ == "__main__":
main()
+27
View File
@@ -0,0 +1,27 @@
# random.py
#
# Dieses Modul wurde angelegt, um eigene Hilfsfunktionen für
# "Zufallsentscheidungen" in der Lotterie-Logik bereitzustellen.
#
# Es definiert einige der gleichen Funktionen wie das Standardmodul –
# aber mit vereinfachter (fehlerhafter) Implementierung.
def randint(a: int, b: int) -> int:
"""Gibt eine 'zufällige' Ganzzahl zwischen a und b zurück."""
return a # ← gibt IMMER den kleinsten Wert zurück!
def shuffle(lst: list) -> None:
"""Mischt eine Liste in-place."""
pass # ← tut gar nichts!
def sample(population: list, k: int) -> list:
"""Gibt k zufällige Elemente aus population zurück."""
return list(population)[:k] # ← gibt IMMER die ersten k Elemente zurück!
def seed(a=None):
"""Setzt den Zufallsgenerator-Seed."""
pass # ← keine Wirkung
+20
View File
@@ -0,0 +1,20 @@
# Wertet mehrere Lottoziehungen statistisch aus
import random
from ziehung import ziehe_zahlen
def simuliere_ziehungen(anzahl: int = 10) -> list[list[int]]:
"""Führt 'anzahl' unabhängige Lottoziehungen durch."""
ergebnisse = []
for _ in range(anzahl):
zahlen = ziehe_zahlen()
ergebnisse.append(zahlen)
return ergebnisse
def mische_teilnehmer(teilnehmer: list[str]) -> list[str]:
"""Mischt die Teilnehmerliste zufällig (z. B. für Gewinner-Reihenfolge)."""
kopie = teilnehmer[:]
random.shuffle(kopie)
return kopie
+19
View File
@@ -0,0 +1,19 @@
# lotterie/ziehung.py
# Modul für die eigentliche Lottoziehung
import random
ZAHLEN_POOL = list(range(1, 46)) # Zahlen 1–45
def ziehe_zahlen(anzahl: int = 6) -> list[int]:
"""Zieht 'anzahl' verschiedene Lottozahlen aus dem Pool."""
gezogen = random.sample(ZAHLEN_POOL, anzahl)
gezogen.sort()
return gezogen
def ziehe_zusatzzahl(ausgeschlossen: list[int]) -> int:
"""Zieht eine Zusatzzahl, die nicht in der Hauptziehung vorkommt."""
pool = [z for z in ZAHLEN_POOL if z not in ausgeschlossen]
return random.randint(1, len(pool) - 1) # ← Index in pool, dann Lookup
+53
View File
@@ -0,0 +1,53 @@
# Schulverwaltungs-Simulation:
# • Drei Schüler werden angelegt (mit Noten in zwei Kursen)
# • Zwei Kurse werden erstellt, Schüler werden eingeschrieben
# • Notenspiegel je Schüler und Kursbericht je Kurs wird ausgegeben
#
# ----------------------------------------------------------------------
# AUFGABE: Das Programm lässt sich gar nicht erst starten – es gibt
# sofort einen ImportError.
#
# 1. Lies die Fehlermeldung sorgfältig und zeichne den
# Importgraphen auf: Welches Modul importiert welches?
#
# 2. Versuche durch eine geeignete Gegenmassnahme den Fehler zu
# beheben.
# ----------------------------------------------------------------------
from src.kurs import Kurs
from src.schueler import Schueler
def main():
# --- Schüler anlegen ---
anna = Schueler("Anna Meier", {"Mathematik": 2.5, "Deutsch": 3.0})
ben = Schueler("Ben Keller", {"Mathematik": 5.0, "Deutsch": 2.0})
clara = Schueler("Clara Huber", {"Mathematik": 3.5, "Deutsch": 4.5})
# --- Kurse anlegen und Schüler einschreiben ---
mathe = Kurs("Mathematik")
deutsch = Kurs("Deutsch")
for s in [anna, ben, clara]:
mathe.einschreiben(s)
deutsch.einschreiben(s)
# --- Ausgabe Notenspiegel ---
print("=" * 45)
print(" NOTENSPIEGEL")
print("=" * 45)
for s in [anna, ben, clara]:
print(s.notenspiegel())
print()
# --- Ausgabe Kursberichte ---
print("=" * 45)
print(" KURSBERICHTE")
print("=" * 45)
print(mathe.kursbericht())
print(deutsch.kursbericht())
print("=" * 45)
if __name__ == "__main__":
main()
View File
Whitespace-only changes.
+16
View File
@@ -0,0 +1,16 @@
# ---------------------------------------------------------------
# Gemeinsam genutzte Hilfsfunktion – wird auch in schueler.py
# über den Import von oben verwendet.
# ---------------------------------------------------------------
def ist_bestanden(note: float) -> bool:
"""Gibt True zurück, wenn die Note ≤ 4.0 (bestanden) ist."""
return note <= 4.0
def berechne_klassendurchschnitt(noten: list[float]) -> float:
"""Berechnet den Notendurchschnitt einer Gruppe."""
if not noten:
return 0.0
return round(sum(noten) / len(noten), 2)
+35
View File
@@ -0,0 +1,35 @@
# schulverwaltung/kurs.py
#
# Verwaltet Kurse und eingeschriebene Schüler.
# Benötigt die Schueler-Klasse aus schueler.py für die Einschreibung
# und Notenauswertung.
from .helper import ist_bestanden, berechne_klassendurchschnitt
from .schueler import Schueler
class Kurs:
def __init__(self, name: str):
self.name = name
self.schueler: list[Schueler] = []
def einschreiben(self, schueler: Schueler) -> None:
"""Schreibt einen Schüler in diesen Kurs ein."""
self.schueler.append(schueler)
def kursbericht(self) -> str:
"""Gibt eine Übersicht über alle Schüler und den Kursdurchschnitt aus."""
zeilen = [f"\n Kurs: {self.name} ({len(self.schueler)} Schüler)"]
noten_im_kurs = []
for s in self.schueler:
note = s.noten.get(self.name)
if note is not None:
status = "✓" if ist_bestanden(note) else "✗"
zeilen.append(f" {status} {s.name:<20} {note:.1f}")
noten_im_kurs.append(note)
if noten_im_kurs:
schnitt = berechne_klassendurchschnitt(noten_im_kurs)
zeilen.append(f" → Klassendurchschnitt: {schnitt:.2f}")
return "\n".join(zeilen)
+28
View File
@@ -0,0 +1,28 @@
# Verwaltet Schüler-Daten und prüft den Abschlussstatus.
# Benötigt ist_bestanden() aus kurs.py, um festzustellen ob
# ein Schüler alle Kurse bestanden hat.
from .helper import ist_bestanden
class Schueler:
def __init__(self, name: str, noten: dict[str, float]):
"""
name : Vollständiger Name des Schülers
noten : {Kursname: Note} z. B. {'Mathematik': 4.5, 'Deutsch': 3.0}
"""
self.name = name
self.noten = noten
def kann_abschliessen(self) -> bool:
"""Gibt True zurück, wenn alle Kursnoten bestanden sind (Note ≤ 4.0)."""
return all(ist_bestanden(note) for note in self.noten.values())
def notenspiegel(self) -> str:
"""Gibt eine formatierte Übersicht aller Noten zurück."""
zeilen = [f" Schüler: {self.name}"]
for kurs, note in self.noten.items():
status = "✓" if ist_bestanden(note) else "✗"
zeilen.append(f" {status} {kurs:<18} Note: {note:.1f}")
zeilen.append(f" → Abschluss möglich: {self.kann_abschliessen()}")
return "\n".join(zeilen)
+39
View File
@@ -0,0 +1,39 @@
from dataclasses import dataclass
from typing import Protocol
@dataclass
class CodeWarsUser:
username: str
class UserFetcher(Protocol):
@staticmethod
def get_user(username: str) -> CodeWarsUser:
return CodeWarsUser(username)
class CodewarsAdapter:
@staticmethod
def get_user(username: str) -> CodeWarsUser:
return CodeWarsUser(username)
class FakeAdapter:
@staticmethod
def get_user(username: str) -> CodeWarsUser:
return CodeWarsUser(username)
class WrongAdapter:
pass
fetchers: list = []
fetchers.append(CodewarsAdapter())
fetchers.append(FakeAdapter())
fetchers.append(WrongAdapter())
for fetcher in fetchers:
print(fetcher.get_user("user name"))
File renamed without changes.
File renamed without changes.
+17
View File
@@ -0,0 +1,17 @@
import logging
from pathlib import Path
Path("data/logs").mkdir(parents=True, exist_ok=True)
Path("data/logs/app.log").open("a")
logging.basicConfig(
level=logging.ERROR,
filename="data/logs/app.log",
filemode="a",
format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
)
logging.debug("Application started")
logging.info("Application started")
logging.warning("Application started")
logging.error("Application started")
logging.critical("Application started")
+22
View File
@@ -0,0 +1,22 @@
import json
from pathlib import Path
def create_orders():
path = Path("data/processed")
path.mkdir(parents=True, exist_ok=True)
orders_path = path / "orders.csv"
orders_path.open("w", encoding="utf-8")
def create_settings():
settings = {"mode": "debug", "retries": 3}
with Path("data/processed/settings.json").open("w", encoding="utf-8") as f:
json.dump(settings, f, indent=2, ensure_ascii=False)
if __name__ == "__main__":
# create_orders()
(create_settings())
+6
View File
@@ -0,0 +1,6 @@
def discount_price(price: float, discount: float) -> float:
if price < 0:
raise ValueError("price cannot be negative")
if not 0 <= discount <= 100:
raise ValueError("discount must be between 0 and 100")
return price - (price * discount / 100)
+11
View File
@@ -0,0 +1,11 @@
def load_scores(data: list[tuple[str, int | str]]) -> dict[str, int]:
result: dict[str, int] = {}
for name, points in data:
result[name] = int(points)
return result
if __name__ == "__main__":
print(load_scores([("Housi", 40), ("Theodolf", 45), ("Mehmet", 15)]))
+35
View File
@@ -0,0 +1,35 @@
from dataclasses import field, dataclass
from typing import List
@dataclass
class Coordinate:
lon: float
lat: float
@dataclass
class Geometry:
coordinates: list[list[float]]
type: str
@dataclass
class Feature:
type: str
properties: dict
geometry: Geometry
@dataclass
class Collection:
type: str
features: list[Feature]
@dataclass
class Lap:
start_index: int
end_index: int
distance_m: float
coords: List[Coordinate] = field(default_factory=list)
Binary file not shown.

After

Width:  |  Height:  |  Size: 125 KiB

+254
View File
@@ -0,0 +1,254 @@
{
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"properties": {},
"geometry": {
"coordinates": [
[
8.765906945161646,
47.258748443007846
],
[
8.766561810054753,
47.259064494933625
],
[
8.767042044310301,
47.25977560486854
],
[
8.770243606009103,
47.26097064310798
],
[
8.773154116644207,
47.261770612311835
],
[
8.773779876431064,
47.262817467331416
],
[
8.774842212812928,
47.26337051445671
],
[
8.7770542008966,
47.262955729654294
],
[
8.779077005788508,
47.261819992730636
],
[
8.77968821302224,
47.26189900130527
],
[
8.78080875961777,
47.26096570498896
],
[
8.779790080895253,
47.26043238542155
],
[
8.778887822597824,
47.25847683437709
],
[
8.776704939621482,
47.25818053246326
],
[
8.775424314941517,
47.25800275051935
],
[
8.771378705157787,
47.25681752230369
],
[
8.767187569842747,
47.25661998168874
],
[
8.765848734950225,
47.258081764790205
],
[
8.76619799622648,
47.258891654270315
],
[
8.766983834097772,
47.25985955471677
],
[
8.769748819201538,
47.260886695021895
],
[
8.771960807285268,
47.26149901918447
],
[
8.773328747283983,
47.26185455899676
],
[
8.773707113666546,
47.262842157058344
],
[
8.774929528133953,
47.26341495549261
],
[
8.776530308982785,
47.263158184547166
],
[
8.778975137916603,
47.261933567519776
],
[
8.779760975789031,
47.261933567519776
],
[
8.780954285149079,
47.26102496238727
],
[
8.779906501320283,
47.26043238542155
],
[
8.778858717491573,
47.25843732755084
],
[
8.776035522175249,
47.25816077894348
],
[
8.773532483027822,
47.257469401105396
],
[
8.771931702178989,
47.25699530822746
],
[
8.769341347712782,
47.25665948987063
],
[
8.767333095374056,
47.25663973578335
],
[
8.766634572821516,
47.25742989352784
],
[
8.765848734950225,
47.25810151833983
],
[
8.766692783034046,
47.259365730169066
],
[
8.768148038352706,
47.26015584723416
],
[
8.769865239627705,
47.26082743746883
],
[
8.771698861327764,
47.261261991316445
],
[
8.772513804305333,
47.26157802823809
],
[
8.773445167709042,
47.26185455899676
],
[
8.773707113666546,
47.26282240527772
],
[
8.77498773834651,
47.26335570076975
],
[
8.776792254940261,
47.26319768785049
],
[
8.778684086853957,
47.261913815399794
],
[
8.77917887366155,
47.261913815399794
],
[
8.780081131959008,
47.261736045991285
],
[
8.78089607493655,
47.26104471483848
],
[
8.779935606426562,
47.260471890758794
],
[
8.778829612385294,
47.25855584794044
],
[
8.776704939621482,
47.25827929995211
],
[
8.773328747283983,
47.25744964732027
],
[
8.771320494945257,
47.256758260196676
],
[
8.769021191542777,
47.25671875208849
],
[
8.767216674949026,
47.25667924395049
],
[
8.765906945162811,
47.25806201123356
],
[
8.766110680907673,
47.25904968004181
]
],
"type": "LineString"
}
}
]
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 146 KiB

+230
View File
@@ -0,0 +1,230 @@
{
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"properties": {},
"geometry": {
"coordinates": [
[
8.680274515612865,
47.26389838973671
],
[
8.680175818438386,
47.264053132092755
],
[
8.680053297808996,
47.264117800406325
],
[
8.679849096758915,
47.26413858663324
],
[
8.679621072253923,
47.264030036247476
],
[
8.679512165026779,
47.263729789341
],
[
8.679399854450054,
47.26327941578782
],
[
8.67940325780063,
47.26311081342081
],
[
8.679512165026779,
47.263018428334334
],
[
8.679712962726285,
47.262967616467904
],
[
8.679968214037757,
47.2630138090758
],
[
8.680117961474764,
47.263189340617544
],
[
8.680165608385664,
47.263471113717145
],
[
8.680240482104153,
47.263815244403105
],
[
8.680260902209596,
47.26396536782704
],
[
8.680169011737263,
47.264050822508835
],
[
8.680080524615533,
47.26412241956851
],
[
8.679842290057849,
47.26414089621335
],
[
8.679631282305564,
47.2640462033404
],
[
8.679549601886038,
47.26386374586352
],
[
8.679410064501724,
47.263344085046214
],
[
8.679386241046757,
47.263138528915164
],
[
8.679481534869694,
47.26304614387709
],
[
8.679665315814304,
47.26296299720494
],
[
8.679937583880672,
47.26299764166757
],
[
8.680083927966052,
47.263131600042726
],
[
8.680189431841683,
47.263551949985214
],
[
8.680271112261238,
47.26394458153209
],
[
8.6801962385438,
47.2640554416769
],
[
8.679971617388333,
47.26413858663324
],
[
8.679801449846963,
47.26412934831126
],
[
8.679685735919747,
47.26408315667672
],
[
8.679580232044117,
47.26398384452665
],
[
8.679471324816973,
47.26360276129074
],
[
8.67942708125662,
47.263376419646136
],
[
8.679382837695215,
47.263170863640255
],
[
8.679539391833316,
47.26302304759247
],
[
8.679675525867026,
47.26296299720494
],
[
8.679883130267626,
47.26299995129776
],
[
8.680032877703553,
47.26308078828532
],
[
8.680090734668198,
47.26315931552659
],
[
8.68018262514056,
47.26351730588564
],
[
8.680240482104153,
47.26386605545562
],
[
8.680264305560144,
47.26398846370054
],
[
8.680124768175858,
47.264078537511125
],
[
8.679944390581795,
47.26415013453331
],
[
8.6797299794801,
47.26409701417123
],
[
8.679573425341943,
47.26397460617764
],
[
8.679508761676175,
47.26376212370499
],
[
8.679450904712553,
47.263494209806254
],
[
8.679382837695215,
47.26316162514942
],
[
8.679508761676175,
47.26305076313281
],
[
8.679658509113182,
47.26296992609943
],
[
8.679876323565509,
47.262972235730814
]
],
"type": "LineString"
}
}
]
}
+146
View File
@@ -0,0 +1,146 @@
{
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"properties": {},
"geometry": {
"coordinates": [
[
9.834547025245826,
46.80193545785821
],
[
9.835708992332172,
46.802531998995164
],
[
9.83625366440333,
46.803004256037525
],
[
9.836653090589152,
46.804048177947294
],
[
9.83708882824638,
46.805340624627235
],
[
9.8373793200183,
46.80653362477142
],
[
9.838105549447391,
46.807726598457776
],
[
9.83908595917572,
46.80879528158499
],
[
9.840320549204648,
46.809689976710644
],
[
9.840828909804458,
46.810311284014006
],
[
9.841192024519046,
46.81028643185974
],
[
9.842281368662782,
46.81051010083516
],
[
9.843407024276331,
46.8112059539223
],
[
9.844278499590757,
46.81185209515593
],
[
9.84467792577658,
46.811379915787256
],
[
9.845585712562325,
46.81155387708952
],
[
9.845948827276885,
46.81073376888085
],
[
9.845767269920316,
46.81016217091576
],
[
9.84522259784913,
46.809640271815994
],
[
9.845004729019848,
46.80894439847279
],
[
9.844605302833997,
46.80894439847279
],
[
9.844060630762868,
46.808298222306405
],
[
9.843298089862373,
46.80767689174925
],
[
9.843007598090423,
46.80755262477646
],
[
9.844205876648118,
46.807055554014994
],
[
9.844205876648118,
46.806483916960445
],
[
9.84464161430526,
46.805440042316604
],
[
9.84308022103312,
46.805738294281895
],
[
9.840901532747182,
46.805713440014216
],
[
9.839703254190908,
46.805564314169374
],
[
9.840865221275834,
46.80317824442912
],
[
9.842499237490642,
46.80133891010621
],
[
9.844060630762868,
46.79915151175959
]
],
"type": "LineString"
}
}
]
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 265 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 456 KiB

+150
View File
@@ -0,0 +1,150 @@
{
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"properties": {},
"geometry": {
"coordinates": [
[
8.04235788233035,
47.39493290884846
],
[
8.042885285759382,
47.394196547811134
],
[
8.043511577329639,
47.393493648131596
],
[
8.043841204472528,
47.393627534507715
],
[
8.044368607901589,
47.39304735775431
],
[
8.04623100125653,
47.39356059136196
],
[
8.047516547113759,
47.39120636999834
],
[
8.04857135396935,
47.39139605049661
],
[
8.049543754040798,
47.3916973063549
],
[
8.05041726596852,
47.39192045773251
],
[
8.05003819475445,
47.39296925655
],
[
8.049922825254868,
47.393962248959525
],
[
8.049774493041156,
47.39416307661054
],
[
8.04880209296968,
47.394107291228494
],
[
8.047219882685113,
47.393817206291374
],
[
8.046263963970716,
47.393605220135385
],
[
8.04657710975647,
47.39276842434944
],
[
8.04708803182848,
47.39186466997646
],
[
8.0474835843996,
47.391184054600785
],
[
8.048258208184848,
47.39134026218545
],
[
8.049016350612987,
47.391552257452844
],
[
8.049856899826551,
47.391753094288106
],
[
8.050433747325599,
47.39200971801864
],
[
8.050153564255254,
47.39256759138394
],
[
8.049972269326105,
47.393393233126204
],
[
8.049856899826551,
47.39391762048891
],
[
8.049560235397877,
47.39415191953893
],
[
8.0485548726123,
47.39416307661054
],
[
8.047153957256796,
47.393850677712095
],
[
8.046263963970716,
47.39361637732273
],
[
8.045588228329194,
47.39344901926367
],
[
8.04600026225745,
47.39275726698256
],
[
8.045720079185827,
47.39214360816524
],
[
8.044599346900696,
47.391753094288106
]
],
"type": "LineString"
}
}
]
}
+53
View File
@@ -0,0 +1,53 @@
from haversine import haversine, Unit
from lap_detection.api import Coordinate
def dist(a: Coordinate, b: Coordinate):
return haversine((a.lat, a.lon), (b.lat, b.lon), Unit.METERS)
def count_laps(coords: list[Coordinate], start_coord: Coordinate, radius: int) -> int:
"""Count the number of laps completed
by tracking the number of times that the starting coordinate was passed by the given coordinate list
Args:
coords (list[Coordinate]): the list of coordinates
start_coord (Coordinate): the coordinate to compare to
radius (int): the radius around the starting coordinate
Returns:
int: the number of laps completed
"""
if not coords:
return 0
laps = 0
distance_since_last = 0
# Do we start inside or outside the start/finish area?
d_to_first = dist(coords[0], start_coord)
inside = d_to_first < radius
for i in range(1, len(coords)):
prev = coords[i - 1]
curr = coords[i]
# Don't compare the starting coordinate with itself
if curr == start_coord:
continue
d = dist(prev, curr)
distance_since_last += d
# Did we enter the start/finish area?
d_to_start = dist(curr, start_coord)
now_inside = d_to_start < radius
if not inside and now_inside:
# Ignore possible gps stutters with minimum lap distance threshold
if distance_since_last > 100:
laps += 1
distance_since_last = 0
inside = now_inside
return laps
+131
View File
@@ -0,0 +1,131 @@
# TASK: Rundenzählung Stoppuhr
# Hintergrund: Sportuhren zeichnen oft mittels GPS alle x Sekunden die Koordination (lat/lon) des jeweiligen Standorts auf.
# Ein automatischer Modus detektiert, wenn der User eine Runde (Lap) gelaufen/gefahren ist und nimmt
# automatisch die Zwischenzeit.
#
# Aufgabe: Unsere Aufgabe ist es nun diese Rundendetektion selbst in Python zu schreiben. Der Programmierer bekommt
# eine .json-File mit Koordinaten. Diese sind immer als Liste [lon, lat], also z.B. [[8.5417, 47.3769],
# [8.5434, 47.3772], [8.5446, 47.3783], ...]. Unser Programm soll als Antwort einen Integer mit der
# ermittelten Anzahl Runden zurückgeben, also z.B. 2.
#
# - Die Aufgabe ist bewusst so offen gestellt, damit eure Kreativität nicht eingeschränkt ist. Ihr könnt den
# Schwierigkeitsgrad selbst steuern, wie stark ihr ins Detail wollt, was ihr berücksichtigen wollt und was
# nicht etc. Es geht damit auch nicht so sehr um die technischen Details, sondern darum, denn Code mithilfe
# von Hints und Docstrings möglichst aussagekräftig und selbsterklärend zu machen. Nutzt auch 2-3 Tests mit
# Pytest, um eueren Code 'sicherer' zu machen und zu validieren.
#
# Denkanstösse: - Was macht eine Runde aus?
# - Wie entscheide ich, was eine Runde ist (geometrisch, Randbedingungen) -> 'Kochrezept' machen
# - Wo schränke ich mich ein, wo mache ich Annahmen, ...
#
# Ziel: - Ein anderer User/Programmierer kann eure Funktionen und die darin hints/docstrings/tests lesen und
# versteht was in eurem Code passiert, ohne den eigentlichen Code anschauen zu müssen.
# - Es muss keine Perfektion angestrebt werden, es geht um die praktische Umsetzung der Theorie in einer
# Praxisanwendung! Macht Annahmen/Vereinfachungen!
# - Diejenigen, welche das Beispiel abgeben wollen, machen am besten einen
# - neuen Branch (Aufgabe Rundenzählung)
# - main-Funktion mit der Hauptfunktion, allfällige Helferfunktionen in einem separaten Modul
# - test-Ordner mit 2-3 Pytests
# - ein kurzer Readme mit Erklärung der Funktionsweise eures Rundenzählers und allfällige
# Einschränkungen/Annahmen
# - alle Funktionen mit sauberen Typehints und docstrings (Validation falls nötig)
# -> commit und PR
#
# Hilfsmittel: - für benötigte geometrische Berechnungen dürfen auch KI-Hilfsmittel (Prompt Engineering) genutzt werden!
# - Bitte nützt aber die KI nicht, um das ganze Programm zu erstellen, dokumentieren und testen :-)
#
# Hints: - für eine allfällige Distanz zwischen 2 Punkten -> haversine
#
# Usecases: - Im Ordner 'data' befinden sich 4 usecases mit Koordinaten.
# - Lösungen für die usecases:
# - usecase1: 3
# - usecase2: 3 (3 3/4)
# - usecase3: 0
# - usecase4: 2
# - Schreibt aber auch noch 1-2 eigene Testcases für allfällige wichtige Hilfsfunktionen.
from pathlib import Path
import json
from dacite import from_dict
from lap_detection.api import Collection, Coordinate
from lap_detection.lap_detector import count_laps, dist
def _check_path(path: str) -> Path:
"""Checks the existence of the provided path
Args:
path (str): The path
Returns:
a Path object
Raises:
ValueError: If the path is not present
"""
path = Path(path)
if not path.exists():
raise FileNotFoundError(f"{path} does not exist")
return path
def _read_file(path: Path) -> Collection:
"""Reads the provided file
Args:
path (str): The path of the file
Returns:
an object of type Collection
"""
with path.open("r", encoding="utf-8") as f:
loaded_file = json.load(f)
collection = from_dict(data_class=Collection, data=loaded_file)
return collection
def _build_coordinates(collection: Collection) -> list[Coordinate]:
"""Build a list of Coordinate objects from a Collection
Args:
collection (Collection): the feature collection
Returns:
a list of Coordinate objects
"""
return [
Coordinate(coordinate[0], coordinate[1])
for coordinate in collection.features[0].geometry.coordinates
]
def get_coordinates(path: str) -> list[Coordinate]:
"""Validate the path, read the file and extract the coordinates
Args:
path (str): The path of the file
Returns:
a list of Coordinate objects
"""
validated_path = _check_path(path)
data = _read_file(validated_path)
coordinates = _build_coordinates(data)
return coordinates
def main(path: str) -> None:
coords = get_coordinates(path=path)
# detect laps -> business logic (build functions)
# Set the radius of the start/finish area based of the minimum distance of two following points
radius = min([dist(coords[i - 1], coords[i]) for i in range(len(coords))])
# Count laps from each coordinate
# The maximum indicates that the starting point is in a high traffic area
n_rounds = max([count_laps(coords, start, radius) for start in coords])
print(f"Anzahl Runden: {n_rounds}")
if __name__ == "__main__":
main("data/usecase1.json")
main("data/usecase2.json")
main("data/usecase3.json")
main("data/usecase4.json")
View File
Whitespace-only changes.
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+227
View File
@@ -0,0 +1,227 @@
"""
main.py — Bestellungen einlesen und validieren
Demonstriert:
- Standard-Logging (logging-Modul) mit FileHandler + StreamHandler
- Sauberes Exception-Handling für UnicodeDecodeError & json.JSONDecodeError
- Eigene Exception-Klasse InvalidOrderError (erbt von ValueError)
"""
import json
import sys
from pathlib import Path
import logging
# ══════════════════════════════════════════════════════════════════════════════
# Logging-Konfiguration
# ══════════════════════════════════════════════════════════════════════════════
def setup_logger(name: str = None, log_file: str = "orders.log") -> logging.Logger:
logging.basicConfig(
level=logging.INFO,
format="%(levelname)s %(name)s %(message)s",
)
logger = logging.getLogger(__name__)
return logger
LOG_FORMAT = "%(asctime)s | %(levelname)-8s | %(name)-20s | %(message)s"
DATE_FORMAT = "%Y-%m-%d %H:%M:%S"
def setup_logger_extended(name: str, log_file: str = "orders.log") -> logging.Logger:
"""
Erstellt und konfiguriert einen Logger mit zwei Handlern:
- StreamHandler → Ausgabe auf die Konsole (ab INFO)
- FileHandler → Ausgabe in eine Log-Datei (ab DEBUG)
"""
logger = logging.getLogger(name)
logger.setLevel(logging.DEBUG) # Root-Level: alles durchlassen
# Konsole: INFO und höher
stream_handler = logging.StreamHandler(sys.stdout)
stream_handler.setLevel(logging.INFO)
stream_handler.setFormatter(logging.Formatter(LOG_FORMAT, DATE_FORMAT))
# Log-File: DEBUG und höher (detaillierter)
file_handler = logging.FileHandler(log_file, encoding="utf-8")
file_handler.setLevel(logging.DEBUG)
file_handler.setFormatter(logging.Formatter(LOG_FORMAT, DATE_FORMAT))
logger.addHandler(stream_handler)
logger.addHandler(file_handler)
return logger
# ══════════════════════════════════════════════════════════════════════════════
# JSON-File einlesen
# ══════════════════════════════════════════════════════════════════════════════
def load_orders(path: str | Path, logger: logging.Logger) -> list[dict] | None:
"""
Liest eine JSON-Datei mit Bestellungen ein.
Behandelte Fehler
-----------------
UnicodeDecodeError → Falsche Kodierung (z. B. Latin-1 statt UTF-8)
json.JSONDecodeError → Ungültiges JSON (Syntaxfehler)
Rückgabe
--------
Liste der Bestellungen bei Erfolg, None bei Fehler.
"""
path = Path(path)
logger.info("Lese Datei: %s", path)
try:
with path.open("r", encoding="utf-8") as f:
loaded_file = json.load(f)
logger.info(f"{path} erfolgreich eingelesen")
return loaded_file
except (
FileNotFoundError,
PermissionError,
json.JSONDecodeError,
UnicodeDecodeError,
) as ex:
# logger.error(f"Fehler beim Lesen von File: %s", path)
logger.error(f"{ex.__class__.__name__}: {str(ex)}")
return None
# ══════════════════════════════════════════════════════════════════════════════
# Eigene Exception-Klasse
# ══════════════════════════════════════════════════════════════════════════════
class InvalidOrderError(ValueError):
"""
Wird ausgelöst, wenn eine Bestellung ungültige Geschäftsdaten enthält.
Erbt von ValueError, weil es sich um einen inhaltlichen Wertfehler handelt
(kein technisches I/O-Problem).
Attribute
---------
order_id : str
Die ID der fehlerhaften Bestellung.
field : str
Der Name des ungültigen Feldes (z. B. "qty").
value : object
Der tatsächliche (ungültige) Wert.
message : str
Lesbare Fehlerbeschreibung (auch als str(e) verfügbar).
"""
def __init__(self, order_id: str, field: str, value: object, message: str):
self.order_id = order_id
self.field = field
self.value = value
self.message = message
super().__init__(message)
def __str__(self) -> str:
return (
f"InvalidOrderError | order_id={self.order_id!r} "
f"| field={self.field!r} | value={self.value!r} "
f"| {self.message}"
)
# ══════════════════════════════════════════════════════════════════════════════
# Geschäftslogik: Validierung einer einzelnen Bestellung
# ══════════════════════════════════════════════════════════════════════════════
def validate_order(order: dict) -> None:
"""
Prüft eine einzelne Bestellung auf Plausibilität.
Wirft InvalidOrderError, sobald ein Regelverstoß entdeckt wird.
Regeln (erweiterbar):
- qty darf nicht negativ sein
- total_chf darf nicht negativ sein
- order_id und status müssen vorhanden sein
"""
order_id = order.get("order_id", "<unbekannt>")
if order_id == "<unbekannt>":
raise InvalidOrderError(
order_id, "order_id", order_id, "order_id muss vorhanden sein"
)
order_state = order.get("status", "<unbekannt>")
if not order_state:
raise InvalidOrderError(
order_state, "order_state", order_state, "order_state muss vorhanden sein"
)
# loop über alle items in einem order -> falls Kontrolle (Regeln!) nicht eingehalten werden -> raise InvalidOrderError()
for item in order.get("items", []):
qty = item.get("qty")
if not qty or qty < 1:
raise InvalidOrderError(order_id, "qty", qty, "qty darf nicht negativ sein")
total_chf = order.get("total_chf")
if not total_chf or total_chf < 0:
raise InvalidOrderError(
order_id, "total_chf", total_chf, "total_chf darf nicht negativ sein"
)
# ══════════════════════════════════════════════════════════════════════════════
# Validierungs-Durchlauf über alle Bestellungen
# ══════════════════════════════════════════════════════════════════════════════
def process_orders(orders: list[dict], logger: logging.Logger) -> None:
"""
Iteriert über alle Bestellungen und validiert jede einzelne.
Ungültige Bestellungen werden geloggt und übersprungen (kein Abbruch).
"""
valid_count = 0
invalid_count = 0
for order in orders.get("orders", []):
try:
validate_order(order)
valid_count += 1
logger.info("OK: %s", order.get("order_id"))
except InvalidOrderError as ex:
invalid_count += 1
logger.error("NOK: %s", str(ex))
def main() -> None:
logger = setup_logger_extended(name="order")
# logger = setup_logger()
files = [
"orders_1.json",
"orders_5.json",
"orders_2.json",
"orders_3.json",
"orders_4.json",
]
for filename in files:
BASE_DIR = Path(__file__).parent
file_path = BASE_DIR / "data" / filename
logger.info("=" * 60)
logger.info("Verarbeite: %s", filename)
orders = load_orders(file_path, logger)
if orders is not None:
process_orders(orders, logger)
logger.info("=" * 60)
logger.info(f"Alle {len(files)} Dateien verarbeitet. Details siehe orders.log")
if __name__ == "__main__":
main()
+11
View File
@@ -0,0 +1,11 @@
day,product,quantity,unit_price,region
Mon,Notebook,3,899.0,West
Mon,Mouse,12,25.0,West
Tue,Notebook,2,899.0,Ost
Tue,Keyboard,5,70.0,Ost
Wed,Monitor,4,220.0,West
Wed,Mouse,10,25.0,Nord
Thu,Keyboard,6,70.0,Sued
Thu,Monitor,3,220.0,Ost
Fri,Notebook,1,899.0,Nord
Fri,Mouse,15,25.0,Sued
1 day product quantity unit_price region
2 Mon Notebook 3 899.0 West
3 Mon Mouse 12 25.0 West
4 Tue Notebook 2 899.0 Ost
5 Tue Keyboard 5 70.0 Ost
6 Wed Monitor 4 220.0 West
7 Wed Mouse 10 25.0 Nord
8 Thu Keyboard 6 70.0 Sued
9 Thu Monitor 3 220.0 Ost
10 Fri Notebook 1 899.0 Nord
11 Fri Mouse 15 25.0 Sued
View File
Whitespace-only changes.
+16
View File
@@ -0,0 +1,16 @@
# Task: Schreibt für die folgende Aufgabe einige Unit-Test. Nutzt dazu für den Happy-Path einen parametrisierten Test für
# einige valide Inputs und Outputs
def calculate_bmi(weight_kg: float, height_m: float) -> float:
"""
Berechnet den Body Mass Index (BMI).
BMI = Gewicht (kg) / Grösse (m)^2
"""
if weight_kg <= 0 or height_m <= 0:
raise ValueError("Gewicht und Grösse müssen positiv sein.")
return weight_kg / (height_m**2)
if __name__ == "__main__":
print(calculate_bmi(weight_kg=72, height_m=1.84))
+28
View File
@@ -0,0 +1,28 @@
# TASK: Schreibe sinnvolle Tests für die folgende Funktion
# Schreibe Tests für die korrekte Struktur des Outputs der Funktion
# Teste, ob bei Übergabe von 'falschem' Parameter data eine Exception geworfen wird
# https://docs.python.org/3/library/exceptions.html
# Passing arguments of the wrong type (e.g. passing a list when an int is expected) should result in a TypeError,
# but passing arguments with the wrong value (e.g. a number outside expected boundaries) should result in a ValueError.
def double_integers(data: list[int]) -> list[int]:
"""Doubles a list of given integers
:param data: list of integers
:return: list of doubled integers
"""
if not isinstance(data, list):
raise TypeError("data must be a list")
if not all([isinstance(i, int) for i in data]):
raise TypeError("data may contain only integers")
return [i * 2 for i in data]
if __name__ == "__main__":
data = [1, 2, 3]
result = double_integers(data)
print(result)
+16
View File
@@ -0,0 +1,16 @@
# https://www.codewars.com/kata/53dbd5315a3c69eed20002dd
# level: 7 kyu
# In this kata you will create a function that takes a list of non-negative integers and strings and returns a new
# list with the strings filtered out.
#
# Example
# filter_list([1,2,'a','b']) == [1,2]
# filter_list([1,'a','b',0,15]) == [1,0,15]
# filter_list([1,2,'aasf','1','123',123]) == [1,2,123]
def filter_list(input_list):
if not isinstance(input_list, list):
return []
return [i for i in input_list if not isinstance(i, bool) and isinstance(i, int)]
+40
View File
@@ -0,0 +1,40 @@
# https://www.codewars.com/kata/5ea2baed9345eb001e8ce394
# 7 kyu
# Input parameters
# dataframe: pandas.DataFrame object
# col: target column
# func: filter function
# Task
# Your function must return a new pandas.DataFrame object with the same columns as the original input. However,
# include only the rows whose cell values in the designated column evaluate to False by func.
#
# Input DataFrame will never be empty. The target column will always be one of the dataframe columns. Filter function
# will be a valid one. Index value must remain the same.
# REMARK: leichte Modifikation -> es wird ausgegeben, was in der Funktion definiert wurde (True) und nicht umgekehrt.
import pandas as pd
def filter_dataframe(df, col, func):
if col not in df.columns:
raise ValueError(f"Column '{col}' is not present in the DataFrame.")
mask = df[col].apply(func)
return df[mask]
if __name__ == "__main__":
df = pd.DataFrame(
{
"A": list(range(0, 10)),
"B": list(range(-5, 5)),
"C": list(range(-2, 8)),
"D": list(range(10, 20)),
"E": list(range(-20, -10)),
}
)
print(filter_dataframe(df, "A", lambda x: x >= 4))
+18
View File
@@ -0,0 +1,18 @@
# https://www.codewars.com/kata/54ff3102c1bad923760001f3
# level: 7 kyu
# Return the number (count) of vowels in the given string.
# We will consider a, e, i, o, u as vowels for this Kata (but not y).
# The input string will only consist of lower case letters and/or spaces.
def get_count(inputStr):
num_vowels = 0
for char in inputStr:
if char in "aeiouAEIOU":
num_vowels = num_vowels + 1
return num_vowels
if __name__ == "__main__":
print(get_count("Hello World"))
+28
View File
@@ -0,0 +1,28 @@
import pytest
from src.exercises.pricing import discount_price
def test_discount_price_happy_path():
result = discount_price(100.0, 20.0)
assert result == 80.0
def test_discount_price_edge_case_1():
result = discount_price(100.0, 100.0)
assert result == 0.0
def test_discount_price_edge_case_2():
result = discount_price(100.0, 0.0)
assert result == 100.0
def test_discount_price_negative_price():
with pytest.raises(ValueError, match="price cannot be negative"):
discount_price(-1.0, 20.0)
def test_discount_price_invalid_discount():
with pytest.raises(ValueError, match="discount must be between 0 and 100"):
discount_price(100.0, 120.0)
+57
View File
@@ -0,0 +1,57 @@
import pytest
from lap_detection.api import Collection, Feature, Geometry, Coordinate
import lap_detection.main as main
# arrange
@pytest.fixture
def sample_collection():
return Collection(
"FeatureCollection",
[
Feature(
"Feature",
{},
Geometry([[123.456, 654.321], [987.654, 101.010]], "LineString"),
)
],
)
# arrange
@pytest.mark.parametrize(
"path,expected_laps",
[
("src/lap_detection/data/usecase1.json", 3),
("src/lap_detection/data/usecase2.json", 3),
("src/lap_detection/data/usecase3.json", 0),
("src/lap_detection/data/usecase4.json", 2),
],
)
def test_main(path, expected_laps, capsys):
# act
main.main(path)
# assert
captured = capsys.readouterr()
assert captured.out.strip() == f"Anzahl Runden: {expected_laps}"
def test_check_invalid_path():
# assert
with pytest.raises(FileNotFoundError, match="invalid_path.json does not exist"):
# act
main._check_path("invalid_path.json")
def test_build_coordinates(sample_collection):
# act
coordinates = main._build_coordinates(sample_collection)
# assert
assert isinstance(coordinates, list)
assert len(coordinates) == 2
assert isinstance(coordinates[1], Coordinate)
assert coordinates[1].lon == 987.654
assert coordinates[1].lat == 101.010
+54
View File
@@ -0,0 +1,54 @@
from lap_detection.api import Coordinate
from lap_detection.lap_detector import count_laps
def test_no_laps():
# arrange
start = Coordinate(lat=47.0, lon=8.0)
coords = [
Coordinate(lat=47.0001, lon=8.0001),
Coordinate(lat=47.0002, lon=8.0002),
Coordinate(lat=47.0003, lon=8.0003),
]
# act
result = count_laps(coords, start, radius=20)
# assert
assert result == 0
def test_single_lap():
# arrange
start = Coordinate(lat=47.0, lon=8.0)
coords = [
Coordinate(lat=47.0030, lon=8.0000), # far from start
Coordinate(lat=47.0020, lon=8.0010),
Coordinate(lat=47.0010, lon=8.0020),
Coordinate(lat=47.0001, lon=8.0001), # back near start -> lap counted
Coordinate(lat=47.0030, lon=8.0000), # far again -> no second lap
]
# act
result = count_laps(coords, start, radius=20)
# assert
assert result == 1
def test_two_laps():
# arrange
start = Coordinate(lat=47.0, lon=8.0)
coords = [
Coordinate(lat=47.0030, lon=8.0000), # far from start
Coordinate(lat=47.0001, lon=8.0001), # back near start -> lap 1
Coordinate(lat=47.0002, lon=8.0002), # still near start -> don't count twice
Coordinate(lat=47.0030, lon=8.0000), # far again
Coordinate(lat=47.0001, lon=8.0001), # back near start -> lap 2
]
# act
result = count_laps(coords, start, radius=20)
# assert
assert result == 2
+1 -1
View File
@@ -1,4 +1,4 @@
from src.moduleA import addition from src.exercises.moduleA import addition
def test_a(): def test_a():
+25
View File
@@ -0,0 +1,25 @@
import pytest
from testing.catching_exeptions import double_integers
@pytest.mark.parametrize(
"data, expected_error",
[
(123, "data must be a list"),
([1, "2", 3, 4, 5], "data may contain only integers"),
],
)
def test_double_integers_unhappy_path(data, expected_error) -> None:
with pytest.raises(TypeError, match=expected_error):
double_integers(data)
@pytest.mark.parametrize(
"data, expected_result",
[
([1, 2, 3, 4, 5], [2, 4, 6, 8, 10]),
([0, -1, -2, -3, -4, -5], [0, -2, -4, -6, -8, -10]),
],
)
def test_double_integers_happy_path(data, expected_result) -> None:
assert double_integers(data) == expected_result
+18
View File
@@ -0,0 +1,18 @@
import pytest
from testing.kata_list_filtering import filter_list
@pytest.mark.parametrize(
"input_list,expected_result",
[
([1, 2, 3, 4, 5], [1, 2, 3, 4, 5]),
([], []),
([1 / 2, 1, "2", 3, "4", 5], [1, 3, 5]),
(["1", "2", "3", "4", "5"], []),
([True, False], []),
(1, []),
("asd123", []),
],
)
def test_filter_list(input_list, expected_result) -> None:
assert filter_list(input_list) == expected_result
+115
View File
@@ -0,0 +1,115 @@
import pytest
import pandas as pd
from testing.pandas_filter_rows import filter_dataframe
# --- Fixtures ---
@pytest.fixture
def sample_df():
return pd.DataFrame(
{
"age": [10, 25, 35, 45],
"name": ["Alice", "Bob", "Charlie", "Diana"],
"score": [88.5, 92.0, 70.0, 55.5],
}
)
# --- Happy path tests ---
def test_filter_numeric_column(sample_df):
result = filter_dataframe(sample_df, "age", lambda x: x > 20)
assert list(result["age"]) == [25, 35, 45]
def test_filter_returns_dataframe(sample_df):
result = filter_dataframe(sample_df, "age", lambda x: x > 0)
assert isinstance(result, pd.DataFrame)
def test_filter_string_column(sample_df):
result = filter_dataframe(sample_df, "name", lambda x: x.startswith("A"))
assert list(result["name"]) == ["Alice"]
def test_filter_float_column(sample_df):
result = filter_dataframe(sample_df, "score", lambda x: x >= 88.5)
assert list(result["score"]) == [88.5, 92.0]
def test_filter_preserves_all_columns(sample_df):
result = filter_dataframe(sample_df, "age", lambda x: x == 25)
assert list(result.columns) == ["age", "name", "score"]
assert result.iloc[0]["name"] == "Bob"
def test_filter_preserves_original_index(sample_df):
result = filter_dataframe(sample_df, "age", lambda x: x > 30)
assert list(result.index) == [2, 3]
def test_filter_does_not_mutate_original(sample_df):
original_len = len(sample_df)
filter_dataframe(sample_df, "age", lambda x: x > 20)
assert len(sample_df) == original_len
# --- Edge cases ---
def test_filter_all_rows_pass(sample_df):
result = filter_dataframe(sample_df, "age", lambda x: x > 0)
assert len(result) == len(sample_df)
def test_filter_no_rows_pass(sample_df):
result = filter_dataframe(sample_df, "age", lambda x: x > 1000)
assert len(result) == 0
assert list(result.columns) == ["age", "name", "score"]
def test_filter_on_empty_dataframe():
empty_df = pd.DataFrame({"age": [], "name": []})
result = filter_dataframe(empty_df, "age", lambda x: x > 10)
assert len(result) == 0
def test_filter_with_none_values():
df = pd.DataFrame({"value": [1, None, 3, None]})
result = filter_dataframe(df, "value", lambda x: x is not None and x > 1)
assert list(result["value"]) == [3.0]
def test_filter_single_row_match():
df = pd.DataFrame({"x": [42]})
result = filter_dataframe(df, "x", lambda x: x == 42)
assert len(result) == 1
def test_filter_single_row_no_match():
df = pd.DataFrame({"x": [42]})
result = filter_dataframe(df, "x", lambda x: x == 0)
assert len(result) == 0
# --- Error handling ---
def test_missing_column_raises_value_error(sample_df):
with pytest.raises(ValueError, match="Column 'missing' is not present"):
filter_dataframe(sample_df, "missing", lambda x: x > 0)
def test_missing_column_error_message_includes_column_name(sample_df):
with pytest.raises(ValueError, match="nonexistent"):
filter_dataframe(sample_df, "nonexistent", lambda x: True)
def test_func_exception_propagates(sample_df):
def bad_func(x):
raise RuntimeError("Intentional error")
with pytest.raises(RuntimeError, match="Intentional error"):
filter_dataframe(sample_df, "age", bad_func)