ENع
→Space and depth
الدرس 03 · Measuring cost

Proving space cost: auxiliary space and recursion depth

لم يُترجم بعد؛ يُعرض باللغة الإنجليزية

12 دقيقة8 خطوات5 أسئلةBeginner
عن هذا الدرس

Time is not the only cost. Here you measure memory: the extra space a function needs on top of its input. Watch a recursive Python function stack one frame per waiting call, find the peak, and prove it needs Θ(n) extra space, while a loop doing the same job needs Θ(1). The Software lesson "How fast is fast? Big O" introduces counting steps, and the Software lesson "Recursion" shows how a function calls itself; the Maths lessons "Logarithms and exponents" and "Recurrences: describing a value by smaller cases" cover the functions and recurrences used here.

ستتعلّم

حدّد ما تشعر بأنك أتقنته. هذا التقييم الذاتي لا يؤثر في درجة الدرس.

شكل 3 · تفاعلي
01 / 08

Space means extra memory

Time counts steps; space counts memory. The list a = [4, 1, 5, 2] is the input, n = 4 numbers. It is in memory before any call, so we count only the extra memory a function makes: its auxiliary space.

a = [4, 1, 5, 2]      n = 4

total space     = input + auxiliary
auxiliary space = extra memory the function
                  uses while it runs

the input is the same for every algorithm,
so space cost counts only the auxiliary part
جارٍ تحميل الرسم…
أو ← →
اقرأ الدرس خطوة بخطوة
  1. Space means extra memory

    Time counts steps; space counts memory. The list a = [4, 1, 5, 2] is the input, n = 4 numbers. It is in memory before any call, so we count only the extra memory a function makes: its auxiliary space.

    a = [4, 1, 5, 2]      n = 4
    
    total space     = input + auxiliary
    auxiliary space = extra memory the function
                      uses while it runs
    
    the input is the same for every algorithm,
    so space cost counts only the auxiliary part
  2. Each call gets a frame

    Call rsum(a). Python gives every running call a frame: a small block of memory for its local names, here a and i. Frames stack up on the call stack. One call running means one frame.

    rsum([4, 1, 5, 2])
    
    frame for i = 0
      a  -> the same list (a reference, not a copy)
      i  =  0
    
    call stack: 1 frame
  3. A call waits for its call

    Line 4 cannot add a[i] until rsum(a, i + 1) answers. So the frame for i = 0 waits, and a new frame goes on top for i = 1, then 2, then 3. Every waiting call keeps its frame.

    i = 0  waits for rsum(a, 1)
    i = 1  waits for rsum(a, 2)
    i = 2  waits for rsum(a, 3)
    i = 3  waits for rsum(a, 4)
    
    call stack: 4 frames, all still in memory
  4. The base case: the peak

    At i = 4, i == len(a), so this call returns 0 without calling again. Right now 5 frames are in memory at once, one for each i from 0 to 4. That is n + 1, the highest the stack gets.

    i = 4:  i == len(a)  ->  return 0
    
    frames at this moment: i = 0, 1, 2, 3, 4
    peak = n + 1 = 5 frames
  5. Unwinding frees the frames

    Now each call finishes and its frame is freed. i = 3 returns 2 + 0 = 2, i = 2 returns 5 + 2 = 7, then 8, then 12. The stack shrinks to nothing, but the peak ring stays at 5.

    i = 4  returns 0
    i = 3  returns a[3] + 0 = 2 + 0 = 2
    i = 2  returns a[2] + 2 = 5 + 2 = 7
    i = 1  returns a[1] + 7 = 1 + 7 = 8
    i = 0  returns a[0] + 8 = 4 + 8 = 12
    
    rsum([4, 1, 5, 2]) == 12
    frames over time: 1 2 3 4 5 4 3 2 1 0
  6. Space is the peak

    Auxiliary space is the most extra memory in use at once, not the total ever used. rsum peaks at n + 1 frames, each a fixed size, so its auxiliary space is Θ(n). With no depth limit, a million numbers need a million frames.

    each frame holds i and a reference to a:
    the same size for every n
    
    space(n) = (n + 1) · one frame
             = Θ(n)
    
    freed memory is reused, so the cost is the
    peak (n + 1), not the sum of all frames
  7. A loop needs one frame

    lsum adds the same list with a loop. The counters now track lsum: one call, one frame, holding total and x. They are overwritten each pass, so memory stays the same for any n: auxiliary space Θ(1). Both take Θ(n) time.

    lsum([4, 1, 5, 2]) == 12
    
    one frame:  a, total, x
    total = 0, 4, 5, 10, 12  (one box, rewritten)
    
    lsum: peak 1 frame   -> Θ(1) auxiliary space
    rsum: peak n + 1     -> Θ(n) auxiliary space
  8. Python caps the depth

    Deep stacks are a real limit. CPython allows 1000 nested calls by default (see sys.getrecursionlimit()) and then raises RecursionError. So rsum fails on a list of 2,000 numbers, while lsum adds a million without trouble.

    import sys
    sys.getrecursionlimit()   # 1000 in CPython
    
    rsum(list(range(2000)))
      RecursionError: maximum recursion depth exceeded
    lsum(list(range(1_000_000)))
      499999500000

اختبار يتاح بعد الخطوة الأخيرة.