Tracing the largest function

COSC 2306: Data Programming - Recursive Function Call Stack Visualizer

Call Stack

Stack is currently empty.
Enter a list of numbers and click "Step" to begin tracing.

Controls

Comma separated list of numbers.

# Largest recursion visualizer ready.

Understanding Recursion on Lists

A recursive function can operate on lists by slowly shrinking the list on each step until it reaches a base case:

  • Base Case: The condition where the list has only 1 element (e.g., len(l) == 1). The largest element in a single-element list is simply the element itself!
  • Recursive Step: Reduce the problem by slicing the list from the second element onward (e.g., l[1:]). Find the largest of the rest, then compare it with the first element (l[0]).

Notice how the function "winds" up the stack finding smaller and smaller slices until one element is left, then "unwinds" by making comparisons on the way back down!

Python Implementation
def largest(l):
    if len(l) == 1:
        return l[0]
    else:
        max = largest(l[1:])
        if l[0] >= max:
            return l[0]
        else:
            return max