Example: Carrying a Quality-Control Summary

In accumulative recursion, each recursive call carries a summary of the input already processed. An accumulator is a parameter that holds such a summary. This lets you preserve useful context while advancing through a list.


A laboratory records collected volumes of [12, 7, 15, 10] mL. It accepts only vials containing at least 10 mL and wants the mean volume of the accepted vials. Treat these recorded volumes as exact for this calculation. Use Python and process the list from left to right without changing it.


a) Specify the meanings and initial values of the helper's state, then write an accumulative recursive helper that returns the accepted total volume and accepted count.


Use i for the index of the next volume to inspect. Use total_ml for the sum of accepted volumes before that index, and count for their number. Initially, i is zero, the total is ________, and the accepted count is ________.


The invariant is that the accumulators describe only the processed prefix. If TiT_i and CiC_i are the total and count on entry to index ii, processing volume viv_i gives


(Ti+1,Ci+1)={(Ti+vi,Ci+1),vi≥10 mL,(Ti,Ci),vi<10 mL.(T_{i+1},C_{i+1})= \begin{cases} (T_i+v_i,C_i+1),&v_i\ge 10\text{ mL},\\ (T_i,C_i),&v_i<10\text{ mL}. \end{cases}


The helper implements those two updates. The numeric list entries represent volumes in millilitres.


Python
def accepted_summary(volumes, i, total_ml, count):
    if i == len(volumes):
        return (total_ml, count)

    volume = volumes[i]
    if volume >= 10:
        return accepted_summary(volumes, i + 1,
                                total_ml + volume, count + 1)
    return accepted_summary(volumes, i + 1, total_ml, count)


Both branches advance the index, but only the accepting branch changes the accumulators. When the index reaches the list length, every volume has been considered, so the existing pair is the answer.


A current recursive call passes an updated index, total, and count to the next call.


b) Trace the helper from its initial call and state the pair it returns for the laboratory's data.


Begin with accepted_summary([12, 7, 15, 10], 0, 0, 0). The first volume qualifies, so adding it to the initial total gives ________, and the accepted count becomes ________. The next call has index one.


The second volume is 7 mL. It fails the acceptance condition, so the next call advances to index two while preserving the total and count.


The third volume is 15 mL. Adding it to the carried total gives ________, and increasing the accepted count gives ________. The next call has index three.


The fourth volume is exactly 10 mL. Because the condition includes equality, this vial qualifies:


new total=27+10=37 mL,\text{new total}=27+10=37\text{ mL},


new count=2+1=3.\text{new count}=2+1=3.


The next call has index four, equal to the list length. It returns (37, 3), representing 37 mL across three accepted vials.


c) Calculate the mean accepted volume to one decimal place. Explain where the summary arithmetic occurs and how an input with no accepted vials should be handled.


For these data, divide the accepted total by the accepted count:


mean accepted volume=37 mL3=12.333… mL.\text{mean accepted volume}=\frac{37\text{ mL}}{3}=12.333\ldots\text{ mL}.


The mean is 12.3 mL to one decimal place. Dividing by four would incorrectly include the rejected vial in the denominator while excluding its volume from the numerator.


The helper performs its summary arithmetic while constructing the arguments for the next call. Each non-base branch returns that call directly, without adding anything to its returned result. At termination, the pair already contains the completed summary.


For a different input, calculate the mean only when the returned count is positive. A zero count means there are no accepted vials; report that outcome rather than divide by zero or invent a mean of zero.

A packaging program multiplies a nonempty list of positive integer factors. Its recursive helper carries the product of the factors already processed.


Python
def product(factors, i, acc):
    if i == len(factors):
        return acc
    return product(factors, i + 1, acc * factors[i])


Which initial call correctly includes every factor exactly once, including when the list contains just one factor?

Choose an answer

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

Match each term used in accumulator-style recursion to the description of the role it plays when a recursive function must remember information about the elements it has already seen.

Match each term
A.

The elements that come before the first element of a call's remaining list

B.

The public entry point that hides the extra parameter from callers and starts the recursion

C.

The argument supplied on the very first call, chosen so that it correctly describes an empty set of handled elements

D.

An extra parameter that carries information about earlier elements into each recursive call

E.

The call on an empty remaining list, where the carried information now describes the whole input

F.

A statement, true on every call, of exactly what the extra parameter records about the elements already handled

Accumulator

Terminating call

Initial accumulator value

Accumulator invariant

Processed prefix

Wrapper function

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

A shop begins with 80 items in stock and records sales of 9, 14, and 6 items, in that order. No other stock changes occur.


Python
def remaining(sales, i, stock):
    if i == len(sales):
        return stock
    return remaining(sales, i + 1, stock - sales[i])

result = remaining([9, 14, 6], 0, 80)


Complete the stock accumulator on entry to each call, including the terminating call. Enter exact integer numbers of items.

Call index iStock on entry (items)
080
1
2
3

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

Extra Practice