commit 49438ccaaf47a56beed49fa95864d8d318e33d80 Author: Jan-Niclas Loosen Date: Sat Oct 18 20:34:32 2025 +0200 Dynamic program example diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..ecbfcaa --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +.idea +.venv \ No newline at end of file diff --git a/Uebung-01/perseverance.py b/Uebung-01/perseverance.py new file mode 100644 index 0000000..3023f5c --- /dev/null +++ b/Uebung-01/perseverance.py @@ -0,0 +1,39 @@ +data = [ + [0, 9, 2, 5, 11, 8], + [17, 21, 32, 5, 15, 3], + [2, 2, 3, 8, 1, 5], + [8, 2, 8, 11, 15, 9], + [0, 5, 3, 10, 4, 0] +] + +max_y = len(data) +max_x = len(data[0]) +start = (max_y-1, max_x-1) + +# Cache with size of n points +cache = [[None for _ in range(max_x)] for _ in range(max_y)] + +def find_path(y, x): + if not (0 <= y < max_y and 0 <= x < max_x): + return (), float('-inf') + + if cache[y][x] is not None: + return cache[y][x] + + if y == 0 and x == 0: + res = (((y, x),), data[y][x]) + else: + west_path, west_val = find_path(y, x-1) + north_path, north_val = find_path(y-1, x) + + if west_val > north_val: + res = (west_path + ((y, x),), west_val + data[y][x]) + else: + res = (north_path + ((y, x),), north_val + data[y][x]) + + cache[y][x] = res + return res + +path, val = find_path(*start) +print(f"Val: {val}") +print(f"Path: {path}")