Merge chunk summaries without changing behavior

An event-processing program computes an integer summary using a reduction, which combines successive values into one running result through a supplied callback.


Python
def fold(combine, initial, values):
    result = initial
    for value in values:
        result = combine(result, value)
    return result

def append_code(total, code):
    return 3 * total + code

codes = [2, 4, 1, 5, 3]
whole = fold(append_code, 0, codes)

left = fold(append_code, 0, codes[:3])
right = fold(append_code, 0, codes[3:])
naive = append_code(left, right)


The first slice contains the first three codes, and the second contains the last two. A developer proposes replacing the sequential computation with separately computed chunk summaries.


Find whole and naive. Then find the constant multiplier w such that w * left + right reproduces the sequential result for every possible choice of integer codes with these same chunk lengths. Enter all three answers as exact, unitless integers.

Your answers

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

More Higher-Order Functions Questions: