18/40
Part 4 of 7 · A park with no cyclesLearn

Top-down reads like the recurrence, and on a long chain it can pass Python's recursion limit

Top-down comes first, because it's the recurrence almost word for word. Ask from the other end: the best total from a junction to an exit. Let functools.cache remember each answer.

import math
from collections import defaultdict
from functools import cache


def best_score_top_down(stretches, start, exits):
    below = defaultdict(list)
    for upper, lower, score in stretches:
        below[upper].append((lower, score))
    exits = set(exits)

    @cache
    # the best total from j to an exit
    def down(j):
        best = 0 if j in exits else -math.inf
        for lower, score in below[j]:
            best = max(best, score + down(lower))
        return best

    best = down(start)
    return None if best == -math.inf else best


print(best_score_top_down(PARK, "top", EXITS))
12

An exit starts at 0, the ride that stops there. It still looks below itself, because a route may ride past an exit. On PARK the best is 12: top, ash, cliff, falls. The recursion finds the order for you, since down(j) can't return until every junction below it has.

It also inherits the recursion limit. Take a chain of junctions, each with one stretch to the next:

A chain of 998 junctions, top-down
down(j0)
down(j1)
down(j2)
...
down(j997)the exit, the first call to return

998 calls open at once, the most that works. One more junction raises RecursionError.

Run from a script, the function worked on a chain of 998 junctions and raised RecursionError: maximum recursion depth exceeded on 999. Python's default limit is 1,000 frames, and the script itself uses a few. A park is something people build, and a long chain of junctions is fair input. Raising the limit is a gamble: the Python docs warn that a limit set too high can lead to a crash.