Skip to main content
6 day streak
Skip to lesson
CareerPetalPython field guide
Loading progress...
Course contents
PYTHON FIELD GUIDE

Course contents 72 topics / 15 parts

Full course overviewOriginal coding practice / separate server checks

Essentials first, then internals and engineering trade-offs.

LESSON 18 / FUNCTIONS AND REUSABLE CODE

Recursion, base cases and explicit stacks

Model smaller subproblems and understand Python's recursion limits.

IntermediateTutorial 14 min core+12 min deep divePython 3.11+ / 2026-10-27
Saved work unavailable

Save privately stores your edited code, notes and current section. Runs and public checks are not saved as verified scores.

Before you start

Learners who can read small Python functions and want to apply the listed foundations.

Explore the connected curriculum and preparation map

Lesson content version 2026-10-27. Suggested core budget: 14 minutes; optional deep dive: 12 more minutes. These are reading/practice estimates, not a timed test.

Suggested preparation and repair routes

If an example or checkpoint feels unclear, revisit the relevant foundation and return. These links do not lock the lesson or claim you passed a prerequisite.

Actual runtime and local-lab boundaries

Browser Python 3.13: fresh isolated worker, 4-second execution, 16 KiB output, 256 MiB Python heap; no outbound network, host processes, interactive input or package installation.

Supported snippets run in the browser; temporary files and SQLite data disappear after each run. Models are labelled conceptual, not traces of your edited source. Full operating-system/framework/cloud labs need separate approval.

Public checks, revealed answers and project self-checks are learning feedback, not verified mastery or problem acceptance. Saving code does not execute it.

YOU WILL BE ABLE TO
  • Explain state the shrinking problem
  • Apply use recursion where the shape fits
  • Reason about depth and adversarial inputs
01

State the shrinking problem

Recursion solves a problem by calling the same function on a smaller problem, until a base case can answer without another call.

READ / UNDERSTAND / THEN EXPERIMENT

Understand first

Use recursive reasoning when a structure is made of smaller structures of the same kind. Know functions, return values and an if condition first.

Words you will see

Base case
An input answered directly, with no further recursive call.
Recursive step
A call on a smaller remaining problem.
Call frame
One call's local state and place to continue when a nested call returns.

Promise a smaller input

countdown(n) promises the number of steps from a nonnegative integer n down to zero. At zero it returns 0 immediately. Otherwise it asks countdown(n - 1), then adds the one step just taken.

For 3, calls wait for 2, then 1, then 0. The return values rebuild in reverse: 0, 1, 2, 3. return passes the result back to the waiting caller; print is not a substitute for returning it.

Termination needs a domain

The contract here accepts nonnegative integers. Starting at a negative integer and repeatedly subtracting one would move away from zero. Validate an external input before using this small teaching function.

A loop can count down without retaining one frame per step and is better for large linear inputs. Recursion is not automatically shorter, faster or safer because its spelling resembles a mathematical definition.

The original example, step by step

These steps explain the original code below. They do not change when you edit your own experiment.

  1. if n == 0:

    Test the stopping input before making another call.

  2. return 0

    Supply the starting result for unwinding.

  3. return 1 + countdown(n - 1)

    Wait for a smaller answer and add this step.

  4. print(countdown(3))

    Three recursive steps above the base case return 3.

A recursive function needs a base case and a step that makes progress toward it. Describe what each call promises before writing it. A missing base case or a subproblem that does not shrink eventually exhausts recursion depth rather than proving the algorithm is correct.

Conceptual cause and effect, not a live runtime trace

Conceptual reasoning steps for the original example, not a live trace of your edited Python.

  1. Reduce3 asks 2, which asks 1, which asks 0.
  2. Stop0 returns its base answer without another call.
  3. RebuildWaiting calls each add one, yielding 3.
Predict before you run

How many recursive calls are made below countdown(0)?

Stop before the next callPYTHON 3

Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.

Preparing the editor controls. Run and editing become available when this page is interactive.

Browser Python limits

Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.

Change one thing; explain the difference.

Count a smaller input.

Try: Change countdown(3) to countdown(2).

The first output is 2 because there are two steps to zero.

Break progress safely.

Try: Change n - 1 to n only for a small trial, then restore it.

The call fails with RecursionError rather than producing a count; stop the experiment if needed.

Before you move on

A function returns 1 for n == 1 and otherwise calls itself with n - 2. Will input 4 reach that base case?

Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.

Read a worked answer

No. It visits 4, 2, 0, -2 and continues away. The step and base case must agree for every accepted input.

This is a self-check, not a required quiz or a saved score. You can revisit any concept.
02

Use recursion where the shape fits

A recursive traversal follows child structures, while an explicit stack stores pending work in an ordinary list instead of Python call frames.

READ / UNDERSTAND / THEN EXPERIMENT

Understand first

Use recursion for shallow nested data when it mirrors the shape. Choose an explicit stack for depth that comes from outside your control.

Words you will see

Tree
A branching structure of nodes and children without cycles.
Traversal
Visiting the parts of a structure in a chosen order.
Explicit stack
A container of pending work, adding and removing from its end.

Describe each node's meaning

In this example an int is a leaf whose total is itself; a list is a branch whose total is the sum of its children's totals. The empty list has no children, so total begins and stays at zero.

For [2, [3, 4]], the outer call adds 2 and the nested answer 7. It never changes the input lists. This contract accepts only integers and finite acyclic lists; a list containing itself is not a tree.

Choose order and storage deliberately

Summing does not care which child runs first, but flattening to a list does. An explicit stack usually needs children pushed in reverse order when left-to-right output matters.

Do not increase the recursion limit to accept arbitrary hostile depth. Iteration avoids recursive frames, but still stores pending nodes and can exhaust memory on huge data. State size and depth limits at the boundary.

The original example, step by step

These steps explain the original code below. They do not change when you edit your own experiment.

  1. if isinstance(node, int):

    Distinguish a leaf from a branch.

  2. total = 0

    Give even an empty branch a valid result.

  3. total += tree_sum(child)

    Add each complete child result, not the child list itself.

  4. print(tree_sum([2, [3, 4], []]))

    Combine 2, 7 and 0 into 9.

Tree traversal and divide-and-conquer can read naturally as recursion. For a very deep linked chain, an explicit stack or loop is safer in Python. Python does not guarantee tail-call elimination; tail-recursive spelling does not remove stack growth.

Predict before you run

What does tree_sum([]) return?

Sum a small nested treePYTHON 3

Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.

Preparing the editor controls. Run and editing become available when this page is interactive.

Browser Python limits

Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.

Change one thing; explain the difference.

Add a negative leaf.

Try: Append -4 to the outer list in the print call.

The total falls to 5; negative integers are leaves too.

Test one leaf.

Try: Replace the print argument with 7.

The base case returns 7 directly without creating a branch total.

Before you move on

For [[], [5, []], -2], what is the total, and do empty branches vanish by mutation?

Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.

Read a worked answer

The total is 3. Empty branches contribute zero; no branch is deleted or modified.

This is a self-check, not a required quiz or a saved score. You can revisit any concept.
03

A bounded recursive sum

An index-based recursive sum passes a position into the same list, avoiding a new sliced list on each call.

READ / UNDERSTAND / THEN EXPERIMENT

Understand first

Use this bounded example to separate the cost of recursion from the additional cost of copying input slices.

Words you will see

Index
A zero-based position in a sequence.
Unwinding
Returning through calls that were waiting for smaller answers.
Auxiliary space
Storage used in addition to the input and final result.

Walk to the end and back

visit starts at index 0. At index len(values), no item remains, so return 0. Earlier calls return their own item plus the answer for the next index.

For [2, 3, 4], visit(2) returns 4 + 0, visit(1) returns 3 + 4, and visit(0) returns 2 + 7. An empty list reaches the base case immediately.

Avoid one cost without hiding another

No input list is sliced or mutated. There are n + 1 visit calls for n items, so under fixed-cost numeric addition the time is O(n) and the call-frame space is O(n). Big integers can make addition more expensive.

A for loop or sum(values) is usually the better production tool for a flat sequence. The example teaches progress and return values, not a speed improvement. Python does not promise tail-call elimination.

The original example, step by step

These steps explain the original code below. They do not change when you edit your own experiment.

  1. if index == len(values):

    Recognize the position just beyond the last item.

  2. return values[index] + visit(index + 1)

    Read a valid item and delegate the remaining suffix by index.

  3. return visit(0)

    Begin at the first possible position.

  4. print(recursive_sum([]))

    The first index already equals length, so print 0.

The index advances to the base case. No sliced list is allocated at each call; the call stack still uses O(n) space.

Predict before you run

Does avoiding slicing make the stack constant size?

A bounded recursive sumPYTHON 3

Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.

Preparing the editor controls. Run and editing become available when this page is interactive.

Browser Python limits

Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.

Change one thing; explain the difference.

Sum one item.

Try: Replace [2, 3, 4] with [5].

The result is 5 from one non-base call plus the zero base answer.

Observe a different identity.

Try: Change the base return from 0 to 10.

Both totals rise by 10, including the empty total; zero was part of the sum contract.

Before you move on

For values [6, -1], what does visit(1) return and what does visit(0) return?

Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.

Read a worked answer

visit(1) returns -1 + 0 = -1. visit(0) returns 6 + -1 = 5. The source remains [6, -1].

This is a self-check, not a required quiz or a saved score. You can revisit any concept.
DETAILED WALKTHROUGH / NOT JUST A SUMMARY

Where this idea earns its place

Recursion expresses a problem in terms of smaller instances of the same contract. Tree walks and divide-and-conquer can become clearer when the shape is recursive. A linear counting task may be simpler as a loop, especially when depth is controlled by untrusted input.

Follow the mechanism step by step

Each invocation has its own local state and a return point. The base case returns without another recursive call; the recursive case must move toward that base. Trace a three-item sum as a stack of pending additions, then unwind the returns. Correctness requires both a valid recurrence and termination.

Work through a concrete application

Write the base case before the general step and decide what empty input means. Pass an index rather than allocating a sliced suffix at every level when the same sequence can be shared read-only. For a tree, define whether the traversal order matters and how a missing child is represented before collecting output.

Failure cases and misleading shortcuts

Python does not guarantee tail-call elimination, so a tail-recursive spelling still grows the call stack. Raising the recursion limit is not a general repair for unbounded depth and can threaten process stability. A cyclic graph also needs visited-state handling; treating it as a tree can repeat work or never terminate.

Cost, ownership and alternatives

Include stack space in complexity. A depth-d traversal can require O(d) pending frames even if it stores little explicit data. Repeated suffix copies can add quadratic work. Memoization can remove repeated subproblems only when the cache key captures all relevant state and the underlying operation is safe to reuse.

Verify the contract

Test the smallest base input, one recursive step, a representative larger shape and the maximum supported depth. For graph-like inputs include a cycle or explicitly reject cycles. Compare a small recursive implementation with an iterative reference so a changed traversal order or missing node becomes visible.

Transfer question: When would you replace recursion with an explicit stack?

Use an explicit stack when input depth can exceed a safe interpreter limit, when you need controlled memory/cancellation or when exposing traversal state helps debugging. Preserve the desired visitation order when pushing children; merely using a stack does not automatically reproduce the recursive order.

RECALL BEFORE YOU SCROLL

Can you explain it?

Try from memory. Feedback stays on this page and does not award judged progress.

Does tail recursion use constant stack space in normal Python?
TRANSFER THE IDEA

Rebuild: A bounded recursive sum

Without copying the worked code, reproduce its observable contract: The index advances to the base case. No sliced list is allocated at each call; the call stack still uses O(n) space. Then change one boundary input and explain the result.

Your practice starterPYTHON 3

Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.

Preparing the editor controls. Run and editing become available when this page is interactive.

Browser Python limits

Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.

MAKE THE RULE WORK ON NEW INPUTS

Guided practice and transfer

These are public local learning checks, not certified scores. Edited code is saved only with Save work and place. Run results are not stored as certified scores. Export useful unsaved work before leaving.

A short function primer before you begin

def names a reusable rule. The input names in parentheses are parameters. Indent its body; replace the starter's pass placeholder. The body runs when called, not when defined.

return hands a value back and ends that call. print only displays a value. The public assert checks call your function with fresh fixtures; a false condition raises AssertionError with its message.

Return a value, do not only print itPYTHON 3

Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.

Preparing the editor controls. Run and editing become available when this page is interactive.

Browser Python limits

Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.

GUIDED PRACTICE

Sum finite nested integer trees

Return the total of every integer leaf without changing any input list.

The contract

  • Input is an int or finite acyclic lists containing only the same kinds; booleans are outside this contract.
  • Return an int; empty branches contribute zero and repeated leaves count separately.
  • Preserve every nested list and its elements. Teaching inputs are shallow; use an explicit stack for arbitrary depth.
Sum finite nested integer treesPYTHON 3

Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.

Preparing the editor controls. Run and editing become available when this page is interactive.

Browser Python limits

Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.

Inspect 6 public checks

Transparent local learning checks, not exhaustive or tamper-proof grading.

  1. Tree total 1
    from copy import deepcopy
    tree = [2, [3, 4]]
    before = deepcopy(tree)
    result = nested_total(tree)
    assert type(result) is int and result == 9
    assert tree == before
    if type(tree) is list:
        assert result is not tree
  2. Tree total 2
    from copy import deepcopy
    tree = []
    before = deepcopy(tree)
    result = nested_total(tree)
    assert type(result) is int and result == 0
    assert tree == before
    if type(tree) is list:
        assert result is not tree
  3. Tree total 3
    from copy import deepcopy
    tree = [[], [0], []]
    before = deepcopy(tree)
    result = nested_total(tree)
    assert type(result) is int and result == 0
    assert tree == before
    if type(tree) is list:
        assert result is not tree
  4. Tree total 4
    from copy import deepcopy
    tree = [-3, [2, -3]]
    before = deepcopy(tree)
    result = nested_total(tree)
    assert type(result) is int and result == -4
    assert tree == before
    if type(tree) is list:
        assert result is not tree
  5. Tree total 5
    from copy import deepcopy
    tree = 7
    before = deepcopy(tree)
    result = nested_total(tree)
    assert type(result) is int and result == 7
    assert tree == before
    if type(tree) is list:
        assert result is not tree
  6. Tree total 6
    from copy import deepcopy
    tree = [1, [1, [1]]]
    before = deepcopy(tree)
    result = nested_total(tree)
    assert type(result) is int and result == 3
    assert tree == before
    if type(tree) is list:
        assert result is not tree
    Why is an empty branch zero rather than None?

    Zero is the additive identity, so callers can combine all branch answers uniformly. Visiting v nodes takes O(v) arithmetic operations and O(depth) recursive frames for this shallow-tree contract.

    GUIDED PRACTICE

    Flatten in left-to-right order

    Return the integer leaves as one new ordered list.

    The contract

    • Accept the same finite acyclic int/list trees as nested_total; booleans are excluded.
    • Return a fresh list of ints in left-to-right depth-first order; retain duplicates and ignore empty branches.
    • Never mutate any nested input. Repeated calls must return separate outer lists.
    Flatten in left-to-right orderPYTHON 3

    Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.

    Preparing the editor controls. Run and editing become available when this page is interactive.

    Browser Python limits

    Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.

    Inspect 6 public checks

    Transparent local learning checks, not exhaustive or tamper-proof grading.

    1. Flatten case 1
      from copy import deepcopy
      tree = [2, [3, 4]]
      before = deepcopy(tree)
      a = flatten_tree(tree)
      b = flatten_tree(tree)
      assert type(a) is list and type(b) is list and a == b == [2, 3, 4]
      assert a is not b and a is not tree and all(type(value) is int for value in a)
      assert tree == before
    2. Flatten case 2
      from copy import deepcopy
      tree = []
      before = deepcopy(tree)
      a = flatten_tree(tree)
      b = flatten_tree(tree)
      assert type(a) is list and type(b) is list and a == b == []
      assert a is not b and a is not tree and all(type(value) is int for value in a)
      assert tree == before
    3. Flatten case 3
      from copy import deepcopy
      tree = [[], [0], []]
      before = deepcopy(tree)
      a = flatten_tree(tree)
      b = flatten_tree(tree)
      assert type(a) is list and type(b) is list and a == b == [0]
      assert a is not b and a is not tree and all(type(value) is int for value in a)
      assert tree == before
    4. Flatten case 4
      from copy import deepcopy
      tree = [-3, [2, -3]]
      before = deepcopy(tree)
      a = flatten_tree(tree)
      b = flatten_tree(tree)
      assert type(a) is list and type(b) is list and a == b == [-3, 2, -3]
      assert a is not b and a is not tree and all(type(value) is int for value in a)
      assert tree == before
    5. Flatten case 5
      from copy import deepcopy
      tree = 7
      before = deepcopy(tree)
      a = flatten_tree(tree)
      b = flatten_tree(tree)
      assert type(a) is list and type(b) is list and a == b == [7]
      assert a is not b and a is not tree and all(type(value) is int for value in a)
      assert tree == before
    6. Flatten case 6
      from copy import deepcopy
      tree = [1, [1, [1]]]
      before = deepcopy(tree)
      a = flatten_tree(tree)
      b = flatten_tree(tree)
      assert type(a) is list and type(b) is list and a == b == [1, 1, 1]
      assert a is not b and a is not tree and all(type(value) is int for value in a)
      assert tree == before
      Why not collect leaves in a set?

      A set loses duplicates and does not express left-to-right traversal. For v visited nodes and k leaves, this routine takes O(v) time, O(k) output space and O(depth) call frames.

      TRANSFER / TRY BEFORE OPENING HINTS

      Transfer: enforce a nesting budget

      Requirements changed: return whether a tree fits a maximum list-nesting depth. Use an explicit stack rather than changing recursion settings.

      The contract

      • Input is a finite acyclic int/list tree; max_depth is a nonnegative integer.
      • An int has depth 0, [] has depth 1, and a list adds one to the maximum child depth; return an actual bool.
      • Preserve all input lists. Avoid recursive calls so a deep chain can be inspected without raising the runtime recursion limit.
      Transfer: enforce a nesting budgetPYTHON 3

      Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.

      Preparing the editor controls. Run and editing become available when this page is interactive.

      Browser Python limits

      Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.

      Inspect 6 public checks

      Transparent local learning checks, not exhaustive or tamper-proof grading.

      1. Depth case 1
        from copy import deepcopy
        tree = 7
        before = deepcopy(tree)
        result = within_depth(tree, 0)
        assert type(result) is bool and result is True and tree == before
      2. Depth case 2
        from copy import deepcopy
        tree = []
        before = deepcopy(tree)
        result = within_depth(tree, 0)
        assert type(result) is bool and result is False and tree == before
      3. Depth case 3
        from copy import deepcopy
        tree = []
        before = deepcopy(tree)
        result = within_depth(tree, 1)
        assert type(result) is bool and result is True and tree == before
      4. Depth case 4
        from copy import deepcopy
        tree = [1, [2]]
        before = deepcopy(tree)
        result = within_depth(tree, 1)
        assert type(result) is bool and result is False and tree == before
      5. Depth case 5
        from copy import deepcopy
        tree = [[], [2, 2]]
        before = deepcopy(tree)
        result = within_depth(tree, 2)
        assert type(result) is bool and result is True and tree == before
      6. Deep chain without recursion
        tree = 1
        for _ in range(1200):
            tree = [tree]
        root = tree
        result = within_depth(tree, 1200)
        assert type(result) is bool and result is True and tree is root
        node = tree
        for _ in range(1200):
            assert type(node) is list and len(node) == 1
            node = node[0]
        assert node == 1
        Why does an empty list consume a depth level?

        Depth describes nesting of list containers, not only routes to leaves. A stack can check each visited node once, using O(v) worst-case pending storage, and reject early on an excessive branch.

        A GOOD PLACE TO PAUSE

        Core route complete.

        If you can explain the checkpoint and attempt the practice, move on. Come back for the deep dive when you want the why behind the how.

        Save your core reading milestone

        Account for every allocation

        Recursive slicing copies progressively smaller containers; memoization instead stores answers to repeated subproblems under keys that describe the whole problem.

        READ / UNDERSTAND / THEN EXPERIMENT

        Understand first

        Count actual allocations and repeated work before optimizing a recursive routine. A short recurrence can hide expensive data movement.

        Words you will see

        Slice
        A new list containing references from a selected range.
        Memoization
        Remembering a result so an equivalent later subproblem can reuse it.
        Subproblem key
        The immutable description used to look up a previously computed answer.

        Copied suffixes add up

        This small sum passes values[1:] each time. For three items it copies two references, then one, then zero. For n items the copied lengths add to n(n - 1)/2.

        Under fixed-cost element operations, this creates O(n squared) copying time. Waiting calls also retain their suffix lists, so peak auxiliary storage can grow quadratically. An index avoids the slices but not recursive frames.

        Cache repeated problems, not unique suffixes blindly

        Memoization helps when different call paths ask the same question. A linear walk through unique indices has no repeated subproblems worth caching.

        A cache key must include every input that changes the answer. Caching by index alone while values changes gives stale results. Use immutable data or a deliberately scoped cache; keep memory growth and invalidation visible.

        The original example, step by step

        These steps explain the original code below. They do not change when you edit your own experiment.

        1. if not values:

          An empty suffix is the stopping input.

        2. return values[0] + sliced_sum(values[1:])

          Copy the remaining suffix before the next call.

        3. print(source)

          Confirm the original list was not shortened; slicing made new lists.

        Passing values[1:] in each call copies progressively smaller slices and can turn an apparently linear recurrence into quadratic copying. Memoization reduces repeated subproblems only when keys correctly represent all relevant state.

        Predict before you run

        Will memoizing a single linear suffix walk remove its slice allocations?

        See the slice boundaryPYTHON 3

        Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.

        Preparing the editor controls. Run and editing become available when this page is interactive.

        Browser Python limits

        Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.

        Change one thing; explain the difference.

        Use an empty source.

        Try: Replace source with [].

        The result is 0 and no nonempty suffix is copied.

        Grow the input by one.

        Try: Use source = [2, 3, 4, 5].

        The total becomes 14; suffix copying now moves 3 + 2 + 1 references instead of 2 + 1.

        Before you move on

        A four-item list is summed by slicing off its first item each call. How many references are copied into suffix lists?

        Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.

        Read a worked answer

        Six: suffix lengths 3 + 2 + 1 + 0. That triangular growth is why the copy cost is quadratic.

        This is a self-check, not a required quiz or a saved score. You can revisit any concept.

        Depth and adversarial inputs

        An explicit stack makes pending work visible in a container. It avoids recursive call depth without promising unlimited input size.

        READ / UNDERSTAND / THEN EXPERIMENT

        Understand first

        Choose this approach for deeply nested external structures. Bound their total size as well as avoiding recursion depth failures.

        Words you will see

        LIFO
        Last in, first out: the most recently pushed item is handled next.
        Tail call
        A call whose answer would be returned directly without more work.
        Depth limit
        A chosen maximum nesting level or the runtime's protection against excessive call frames.

        Replace waiting frames with pending nodes

        pending starts with the whole tree. pop removes the next node. An int is added to total; a branch contributes its children as future work through extend.

        For [1, [2, 3]], the last branch is processed first, then 3, then 2, then 1. Addition makes this order harmless. For ordered output, push reversed children instead.

        Iteration is a design change, not a permission change

        Python does not guarantee tail-call optimization. Rewriting a recursive traversal as a loop is safer than raising a process-wide recursion limit for untrusted depth.

        This traversal is O(v) time for v visited nodes and uses space for pending work, which can be O(v). A cyclic list can still loop forever. Reject cycles or state a finite-tree contract; an explicit stack alone does not solve cycles.

        The original example, step by step

        These steps explain the original code below. They do not change when you edit your own experiment.

        1. pending = [tree]

          Start with one task: handle the root.

        2. node = pending.pop()

          Take the latest task without changing the source tree.

        3. pending.extend(node)

          Schedule each child's work for a branch.

        4. return total

          Finish only when no scheduled node remains.

        A runtime recursion limit protects the interpreter stack, not your algorithm's data contract. Do not simply raise it for unbounded user input. Test a deep shape, bound accepted depth, or use an explicit stack whose memory budget you can control.

        Predict before you run

        Does this loop need sys.setrecursionlimit for a deep chain?

        Use a pending-work listPYTHON 3

        Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.

        Preparing the editor controls. Run and editing become available when this page is interactive.

        Browser Python limits

        Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.

        Change one thing; explain the difference.

        Swap the child order.

        Try: Change [1, [2, 3]] to [[3, 2], 1].

        The sum stays 6 although visit order changes.

        Sum an empty branch.

        Try: Pass [] to stack_sum.

        The root adds no children, leaving total at zero.

        Before you move on

        If a flattening routine pushes children [4, 5] onto a stack in that order, which leaf is popped first? How can it preserve left-to-right output?

        Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.

        Read a worked answer

        5 is popped first. Push reversed children, 5 then 4, so 4 is handled first.

        This is a self-check, not a required quiz or a saved score. You can revisit any concept.

        Make the explanation your own.

        Use Save work and place to store notes with your code. Unsaved edits stay in this course tab; export before leaving. Reading milestones remain separate.

        Take a versioned study copy

        Export this lesson's original theory, textual model explanations, worked examples, public exercise checks and local-runtime boundaries for reading/review. This is separate from exporting your private workspace: no learner code, notes, identity, saved place or results are included. Offline server/browser execution is not provided.

        Worked examples and explained concept checkpoints remain included. Reference answers for independent work are excluded unless you explicitly select them. A downloaded answer is not an earned pass.

        REFLECT, THEN CONTINUE

        Make this a milestone.

        Save a self-reported core reading milestone and confidence. Confidence 1-3 schedules a review when none is already set; higher confidence does not create a new review. This is not a code execution pass or proof of mastery. Deep-dive reading is optional and is not tracked separately yet.

        Your account

        Loading account...

        Sign in to save your work across devices.