cconnected.
Understand the pattern. Find your own way.Find your starting point
Back to your feed

A few lines, your way.

You know the syntax. This is about deciding what one state means.

Choose values from a row without choosing adjacent positions. Picking nothing is allowed. Implement best_non_adjacent() in 5–10 lines, aiming for linear time.

A memoized recurrence makes the choices explicit. A table makes the evaluation order visible. Rolling values reduce storage. Choose the version you can explain.

python3 practice/state_workshop.py

This exercise runs in local Python. The page displays the starter; it does not execute Python in your browser.

Give me a state-design hint

Let best(i) mean the best value from index i onward, with no earlier selection restricting index i. Taking the current value changes which next index is unrestricted. What are the two choices?

"""A small learner-owned recurrence. Run this file with Python 3.9+."""

import argparse


def best_non_adjacent(values: list[int]) -> int:
    """Return the maximum sum of non-adjacent positions; choosing none is allowed.

    Values may be negative. Empty input returns zero. Do not mutate the input.
    Aim for O(n) time. Memoized recursion, a table, or rolling values are valid.
    """
    # TODO: Write 5–10 lines expressing the consequences of taking or skipping.
    # First decide what one state means and how taking changes the next state.
    # A table makes dependencies visible; rolling values use less memory.
    raise NotImplementedError("Implement your take/skip recurrence here.")


def main() -> int:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--hint", action="store_true", help="Reveal a state-design hint")
    args = parser.parse_args()
    if args.hint:
        print("Try: best(i) = the best value from index i onward, with i unrestricted.")
        print("If you take i, which next index is unrestricted? If you skip it, which is next?")
        return 0

    cases = [([], 0), ([7], 7), ([-5, -2], 0), ([4, 5, 4], 8),
             ([2, 7, 9, 3, 1], 12), ([0, 0, 0], 0), ([3, 2, 5, 10, 7], 15)]
    for values, expected in cases:
        original = values.copy()
        try:
            actual = best_non_adjacent(values)
        except NotImplementedError:
            print("Workshop ready: implement best_non_adjacent() in practice/state_workshop.py.")
            print("No solution checks ran. Use --hint if needed; card 20 has a reference explanation.")
            return 0
        if actual != expected or values != original:
            print(f"Recheck {original}: expected {expected}, received {actual}.")
            if values != original:
                print("The function also changed its input; preserve the caller's list.")
            return 1
    print(f"Passed {len(cases)} workshop examples. Now explain why the take branch skips a neighbor.")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())

Read the complete reasoning in the 1D DP lesson.