This commit is contained in:
englingvi103466 committed 2026-10-29 13:42:50 +01:00
1 parent c269b7f6b8
commit 84f0f9e8fb
1 file changed
+36 -25
+36 -25
View File
@@ -1,41 +1,52 @@
# Ausgangs- und Zielzustand from functools import reduce
state = {'A': 'B', 'B': '', 'C': ''}
goal = {'A': 'C', 'B': 'A', 'C': ''}
# Gegebene Funktionen aus der Aufgabe
def is_clear(state, block): def is_clear(state, block):
"""Prüft, ob ein Block frei ist (nichts liegt darauf).""" return all([v != block for v in state.values()])
return all(v != block for v in state.values())
def move(block, target): def move(block, target):
"""Gibt eine Action-Funktion zurück (Closure).""" def action(state):
if not is_clear(state, block):
def action(current_state):
if not is_clear(current_state, block):
raise ValueError(f"Auf Block {block} liegt etwas!") raise ValueError(f"Auf Block {block} liegt etwas!")
if target != '' and not is_clear(current_state, target): if target != "_" and not is_clear(state, target):
raise ValueError(f"Block {target} ist nicht frei!") raise ValueError(f"Block {target} ist nicht frei!")
new_state = state.copy()
new_state = current_state.copy()
new_state[block] = target new_state[block] = target
print(f"Moved {block} to {target}.")
return new_state return new_state
return action return action
def chain(f, g): def chain(f, g):
"""Funktionale Komposition: Erst f, dann g ausführen.""" return lambda state: g(f(state))
return lambda current_state: g(f(current_state))
if __name__ == '__main__': if __name__ == '__main__':
# Erstellen des Ausführungsplans # Ausgangs- und Zielzustand der Aufgabe
plan = chain(move('A', 'C'), move('B', 'A')) start = {"A": "B", "B": "_", "C": "_", "D": "C"}
goal = {"A": "_", "B": "C", "C": "_", "D": "B"}
# Ausführen des Plans auf dem Ausgangszustand # Liste der Aktionen in korrekter Reihenfolge
final = plan(state) actions = [
move("A", "_"),
move("D", "_"),
move("B", "C"),
move("D", "B")
]
print("Final state:", final) # Originalzustand für den späteren Unverändertbarkeits-Check sichern
assert final == goal start_copy = start.copy()
# 1. Plan aus der Liste mit reduce erzeugen (Startwert ist die neutrale Funktion)
plan = reduce(chain, actions, lambda state: state)
# 2. Plan auf den Startzustand anwenden
final_state = plan(start)
print("Final state:", final_state)
# Prüfen, ob das Ziel erreicht wurde
assert final_state == goal, "Das Ziel wurde nicht erreicht!"
# 3. Prüfen, ob der Startzustand durch die rein funktionale Arbeitsweise unverändert geblieben ist
assert start == start_copy, "Der Startzustand wurde modifiziert (Seiteneffekt)!"
print("Erfolgreich! Zielzustand erreicht und Startzustand blieb intakt.")