Erste Version
This commit is contained in:
commit
782b1850a3
1641 files changed
+512713
No files matched your search
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,146 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Installiert die Abhängigkeiten aus pyproject.toml in die aktuelle Python-Umgebung.
|
||||
|
||||
Ersatz für "Install requirements" aus PyCharm, wenn das Projekt eine pyproject.toml
|
||||
statt einer requirements.txt hat. Kein Build, keine besondere Projektstruktur nötig,
|
||||
nur Standardbibliothek (Python >= 3.11).
|
||||
|
||||
Benutzung:
|
||||
In PyCharm: Rechtsklick auf diese Datei -> Run 'install_dependencies'
|
||||
Im Terminal (venv aktiv): python install_dependencies.py
|
||||
|
||||
Ohne Parameter wird ALLES installiert:
|
||||
[project].dependencies + alle [project.optional-dependencies] + alle [dependency-groups]
|
||||
|
||||
Abweichendes Verhalten:
|
||||
python install_dependencies.py --extra dev nur Basis + Extra "dev"
|
||||
python install_dependencies.py --group test nur Basis + Gruppe "test"
|
||||
python install_dependencies.py --no-main --group dev
|
||||
python install_dependencies.py --list nur anzeigen, nichts installieren
|
||||
python install_dependencies.py --write requirements.txt schreiben statt installieren
|
||||
python install_dependencies.py --write -o reqs.txt
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
|
||||
if sys.version_info < (3, 11):
|
||||
sys.exit("Dieses Skript braucht Python 3.11 oder neuer (tomllib). "
|
||||
f"Aktuell: {sys.version.split()[0]}")
|
||||
|
||||
import argparse
|
||||
import subprocess
|
||||
import tempfile
|
||||
import tomllib
|
||||
from pathlib import Path
|
||||
|
||||
PROJECT_DIR = Path(__file__).resolve().parent
|
||||
|
||||
|
||||
def resolve_group(groups: dict, name: str, seen: set[str] | None = None) -> list[str]:
|
||||
"""Löst eine Dependency-Group inkl. {include-group = "..."} rekursiv auf."""
|
||||
seen = set() if seen is None else seen
|
||||
if name in seen:
|
||||
raise ValueError(f"Zyklische include-group: {name}")
|
||||
if name not in groups:
|
||||
raise KeyError(f"Dependency-Group '{name}' nicht gefunden")
|
||||
seen.add(name)
|
||||
result: list[str] = []
|
||||
for entry in groups[name]:
|
||||
if isinstance(entry, str):
|
||||
result.append(entry)
|
||||
elif isinstance(entry, dict) and "include-group" in entry:
|
||||
result.extend(resolve_group(groups, entry["include-group"], seen))
|
||||
return result
|
||||
|
||||
|
||||
def collect(data: dict, extras: list[str], groups: list[str], no_main: bool) -> list[str]:
|
||||
project = data.get("project", {})
|
||||
optional = project.get("optional-dependencies", {})
|
||||
dep_groups = data.get("dependency-groups", {})
|
||||
deps: list[str] = []
|
||||
|
||||
if not no_main:
|
||||
deps.extend(project.get("dependencies", []))
|
||||
for extra in extras:
|
||||
if extra not in optional:
|
||||
raise KeyError(f"Optional-Dependency '{extra}' nicht gefunden")
|
||||
deps.extend(optional[extra])
|
||||
for group in groups:
|
||||
deps.extend(resolve_group(dep_groups, group))
|
||||
|
||||
# Duplikate entfernen, Reihenfolge behalten
|
||||
return list(dict.fromkeys(d.strip() for d in deps if d.strip()))
|
||||
|
||||
|
||||
def main() -> int:
|
||||
p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||
p.add_argument("-p", "--pyproject", type=Path, default=PROJECT_DIR / "pyproject.toml",
|
||||
help="Pfad zur pyproject.toml (Standard: neben diesem Skript)")
|
||||
p.add_argument("--extra", action="append", default=None,
|
||||
help="nur diese optional-dependencies (mehrfach möglich)")
|
||||
p.add_argument("--group", action="append", default=None,
|
||||
help="nur diese dependency-groups (mehrfach möglich)")
|
||||
p.add_argument("--no-main", action="store_true", help="[project].dependencies weglassen")
|
||||
p.add_argument("--list", action="store_true", help="Abhängigkeiten nur anzeigen")
|
||||
p.add_argument("--write", action="store_true", help="requirements-Datei schreiben statt installieren")
|
||||
p.add_argument("-o", "--output", type=Path, default=PROJECT_DIR / "requirements.txt",
|
||||
help="Zieldatei für --write")
|
||||
args = p.parse_args()
|
||||
|
||||
if not args.pyproject.exists():
|
||||
print(f"{args.pyproject} nicht gefunden", file=sys.stderr)
|
||||
return 1
|
||||
data = tomllib.loads(args.pyproject.read_text(encoding="utf-8"))
|
||||
all_extras = list(data.get("project", {}).get("optional-dependencies", {}))
|
||||
all_groups = list(data.get("dependency-groups", {}))
|
||||
|
||||
# Ohne --extra/--group: alles. Mit einem davon: nur das Gewählte.
|
||||
selective = args.extra is not None or args.group is not None
|
||||
extras = (args.extra or []) if selective else all_extras
|
||||
groups = (args.group or []) if selective else all_groups
|
||||
|
||||
try:
|
||||
deps = collect(data, extras, groups, args.no_main)
|
||||
except (KeyError, ValueError) as e:
|
||||
print(f"Fehler: {e.args[0]}", file=sys.stderr)
|
||||
print(f" Vorhandene --extra: {', '.join(all_extras) or '(keine)'}", file=sys.stderr)
|
||||
print(f" Vorhandene --group: {', '.join(all_groups) or '(keine)'}", file=sys.stderr)
|
||||
return 1
|
||||
|
||||
parts = ([] if args.no_main else ["Basis"]) + [f"extra:{e}" for e in extras] + [f"group:{g}" for g in groups]
|
||||
print(f"Auswahl: {', '.join(parts) or '(nichts)'}")
|
||||
|
||||
if args.list:
|
||||
print("\n".join(deps) or "(keine Abhängigkeiten)")
|
||||
return 0
|
||||
|
||||
content = f"# Automatisch erzeugt aus {args.pyproject.name} – nicht von Hand bearbeiten\n" + "\n".join(deps) + "\n"
|
||||
|
||||
if args.write:
|
||||
args.output.write_text(content, encoding="utf-8")
|
||||
print(f"{len(deps)} Abhängigkeiten -> {args.output}")
|
||||
return 0
|
||||
|
||||
if not deps:
|
||||
print("Keine Abhängigkeiten gefunden – nichts zu tun.")
|
||||
return 0
|
||||
|
||||
if sys.prefix == sys.base_prefix:
|
||||
print("WARNUNG: Es ist kein virtuelles Environment aktiv – es wird in die globale "
|
||||
f"Python-Installation installiert:\n {sys.prefix}", file=sys.stderr)
|
||||
if sys.stdin.isatty() and input("Trotzdem fortfahren? [j/N] ").strip().lower() not in ("j", "ja", "y", "yes"):
|
||||
return 1
|
||||
|
||||
with tempfile.NamedTemporaryFile("w", suffix=".txt", delete=False, encoding="utf-8") as tmp:
|
||||
tmp.write(content)
|
||||
tmp_path = Path(tmp.name)
|
||||
try:
|
||||
print(f"Installiere {len(deps)} Abhängigkeiten in {sys.prefix}\n")
|
||||
return subprocess.call([sys.executable, "-m", "pip", "install", "-r", str(tmp_path)])
|
||||
finally:
|
||||
tmp_path.unlink(missing_ok=True)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,10 @@
|
||||
[project]
|
||||
name = "Funktional"
|
||||
version = "0.1.0"
|
||||
dependencies = ["pygame-ce"]
|
||||
|
||||
[project.optional-dependencies]
|
||||
dev = ["pytest", "ruff", "pytest-cov"]
|
||||
|
||||
[tool.pytest.ini_options]
|
||||
pythonpath = "src"
|
||||
Submodule
+1
Submodule aufgaben/hausaufgaben added at 728dd0b739.
@@ -0,0 +1,4 @@
|
||||
numbers = [1, 2, 3, 4, 5]
|
||||
|
||||
doppelt = list(map(lambda x: x * 2, numbers))
|
||||
print(doppelt) # [2, 4, 6, 8, 10]
|
||||
@@ -0,0 +1,6 @@
|
||||
#map-filter-iteratoren
|
||||
words=["Hofmann","was","right","about","something"]
|
||||
result= list(map( lambda w: w.upper(), words))
|
||||
print(result)
|
||||
senstence= "".join(words)
|
||||
print(senstence)
|
||||
@@ -0,0 +1,4 @@
|
||||
#map-filter-iteratoren
|
||||
numbers = list(range(1, 21))
|
||||
gerade = list(filter(lambda x: x%2==0, numbers))
|
||||
print(gerade)
|
||||
@@ -0,0 +1,5 @@
|
||||
words = ["Apfel", "Banane", "Kirsche", "Kiwi", "Melone"] #summe der Wortlänge, die mit k beginnen
|
||||
#summe= sum(len(word) for word in words if word.startwith("K"))
|
||||
#print(summe)
|
||||
|
||||
summe = filter(lambda word: str.startswith("K"), words, )
|
||||
@@ -0,0 +1,7 @@
|
||||
from functools import reduce
|
||||
|
||||
def produkt(numbers):
|
||||
return reduce(lambda a, b: a * b, numbers, 1)
|
||||
|
||||
print(produkt([1, 2, 3, 4, 5])) # 120
|
||||
print(produkt([])) # 1
|
||||
@@ -0,0 +1,34 @@
|
||||
from functools import reduce
|
||||
|
||||
|
||||
def is_clear(state, block):
|
||||
return all([v != block for v in state.values()])
|
||||
|
||||
|
||||
def move(block, target):
|
||||
def action(state):
|
||||
if not is_clear(state, block):
|
||||
raise ValueError(f"Auf Block {block} liegt etwas!")
|
||||
if target != "_" and not is_clear(state, target):
|
||||
raise ValueError(f"Block {target} ist nicht frei!")
|
||||
new_state = state.copy()
|
||||
new_state[block] = target
|
||||
return new_state
|
||||
return action
|
||||
|
||||
|
||||
def chain(f, g):
|
||||
return lambda state: g(f(state))
|
||||
|
||||
|
||||
identity = lambda state: state
|
||||
|
||||
start = {"A": "B", "B": "_", "C": "_", "D": "C"}
|
||||
goal = {"A": "_", "B": "C", "C": "_", "D": "B"}
|
||||
|
||||
actions = [
|
||||
move("A", "_"),
|
||||
move("D", "_"),
|
||||
move("B", "C"),
|
||||
move("D", "B"),
|
||||
]
|
||||
@@ -0,0 +1,39 @@
|
||||
from undo_06 import Particle
|
||||
|
||||
|
||||
def test_update_und_undo():
|
||||
# Ausgangszustand: Position (0,0), Geschwindigkeit (0,0), Beschleunigung (1,1)
|
||||
p0 = Particle((0, 0), (0, 0), (1, 1))
|
||||
|
||||
# Dreimal update: jedes Mal entsteht ein neues Particle-Objekt
|
||||
p1 = p0.update()
|
||||
p2 = p1.update()
|
||||
p3 = p2.update()
|
||||
|
||||
# Prüfen, ob die Positionen nach jedem update stimmen
|
||||
assert p1.position == (1, 1)
|
||||
assert p2.position == (3, 3)
|
||||
assert p3.position == (6, 6)
|
||||
|
||||
# undo muss jeweils genau die Vorversion zurückgeben
|
||||
assert p3.undo() is p2 # ein Schritt zurück
|
||||
assert p3.undo().undo() is p1 # zwei Schritte zurück
|
||||
|
||||
|
||||
def test_undo_ohne_vorversion():
|
||||
# Ein frisch erstelltes Particle hat noch keine History
|
||||
p0 = Particle((0, 0), (0, 0), (1, 1))
|
||||
|
||||
# undo liefert dann einfach das Objekt selbst zurück
|
||||
assert p0.undo() is p0
|
||||
|
||||
|
||||
def test_history_ist_begrenzt():
|
||||
p = Particle((0, 0), (0, 0), (1, 1))
|
||||
|
||||
# Deutlich öfter updaten, als die History speichern darf
|
||||
for _ in range(10):
|
||||
p = p.update()
|
||||
|
||||
# Die History darf nie länger als MAX_HISTORY werden
|
||||
assert len(p.history) == Particle.MAX_HISTORY
|
||||
@@ -0,0 +1,42 @@
|
||||
from functools import reduce
|
||||
from klötzchenwelt_07 import move, chain, identity, start, goal, actions
|
||||
|
||||
|
||||
def test_plan_erreicht_ziel():
|
||||
# Alle Aktionen mit reduce zu einem einzigen Plan verknüpfen
|
||||
# (identity als Startwert: Aktion, die nichts tut)
|
||||
plan = reduce(chain, actions, identity)
|
||||
|
||||
# Plan auf den Startzustand anwenden: Ergebnis muss der Zielzustand sein
|
||||
assert plan(start) == goal
|
||||
|
||||
|
||||
def test_start_bleibt_unveraendert():
|
||||
# Kopie des Startzustands merken, um später zu vergleichen
|
||||
kopie = dict(start)
|
||||
|
||||
# Plan ausführen (das Ergebnis brauchen wir hier nicht)
|
||||
reduce(chain, actions, identity)(start)
|
||||
|
||||
# move arbeitet mit state.copy(), deshalb darf start sich nicht verändert haben
|
||||
assert start == kopie
|
||||
|
||||
|
||||
def test_leere_liste():
|
||||
# Ohne Aktionen liefert reduce nur den Startwert identity zurück
|
||||
plan = reduce(chain, [], identity)
|
||||
|
||||
# Ein leerer Plan tut nichts: der Zustand bleibt gleich
|
||||
assert plan(start) == start
|
||||
|
||||
|
||||
def test_vertauschte_aktionen():
|
||||
# B wird auf C gelegt, bevor D von C heruntergenommen wurde
|
||||
falsch = [move("A", "_"), move("B", "C"), move("D", "_"), move("D", "B")]
|
||||
|
||||
# Der Plan muss einen ValueError auslösen ("Block C ist nicht frei!")
|
||||
try:
|
||||
reduce(chain, falsch, identity)(start)
|
||||
assert False, "Es hätte ein ValueError auftreten müssen"
|
||||
except ValueError as e:
|
||||
assert str(e) == "Block C ist nicht frei!"
|
||||
@@ -0,0 +1,28 @@
|
||||
class Particle:
|
||||
MAX_HISTORY = 5 # maximal so viele Undos möglich
|
||||
|
||||
def __init__(self, position, velocity=(0, 0), acceleration=(0, 0), history=()):
|
||||
self.position = position
|
||||
self.velocity = velocity
|
||||
self.acceleration = acceleration
|
||||
self.history = list(history)
|
||||
|
||||
def update(self):
|
||||
new_velocity = (self.velocity[0] + self.acceleration[0],
|
||||
self.velocity[1] + self.acceleration[1])
|
||||
new_position = (self.position[0] + new_velocity[0],
|
||||
self.position[1] + new_velocity[1])
|
||||
# Vorversion (self) an die neue History anhängen, alte Liste bleibt unverändert
|
||||
new_history = (self.history + [self])[-Particle.MAX_HISTORY:]
|
||||
return Particle(new_position, new_velocity, self.acceleration, new_history)
|
||||
|
||||
def undo(self):
|
||||
if not self.history:
|
||||
return self # nichts mehr zum Zurückgehen
|
||||
return self.history[-1] # Vorversion (hat ihre eigene History)
|
||||
|
||||
def __repr__(self):
|
||||
return f"Particle(pos={self.position}, vel={self.velocity})"
|
||||
|
||||
|
||||
|
||||
Reference in new issue
Block a user