PCEP-30-02 · Question #348
What is the expected output of the following code? ``python def iterate(end, foo = 0): if end > 0: foo = iterate(end - 1, foo + end) return foo print(iterate(2)) ``
The correct answer is D. 3. D (3) is correct because this function recursively accumulates a running sum. Tracing the calls: iterate(2) → iterate(1, 2) → iterate(0, 3), at which point end > 0 is false, so foo=3 unwinds back through every caller and 3 is printed. Why the distractors fail: A (0) - the…
Question
def iterate(end, foo = 0):
if end > 0:
foo = iterate(end - 1, foo + end)
return foo
print(iterate(2))
Options
- A0
- B1
- C2
- D3
How the community answered
(21 responses)- A5% (1)
- B14% (3)
- C10% (2)
- D71% (15)
Explanation
D (3) is correct because this function recursively accumulates a running sum. Tracing the calls: iterate(2) → iterate(1, 2) → iterate(0, 3), at which point end > 0 is false, so foo=3 unwinds back through every caller and 3 is printed.
Why the distractors fail:
- A (0) - the default value of
foo- is never returned;foogets overwritten on every recursive call before returning. - B (1) - would only be correct if
endstarted at 1; the function adds both 2 and 1 to the accumulator. - C (2) - only the first level's contribution; it ignores that 1 is also added in the deeper recursive call.
Memory tip: This function silently computes triangular numbers (1+2+…+n). For any call iterate(n), the result is n*(n+1)/2 - so iterate(2) = 2*3/2 = 3. Recognizing this pattern will let you skip the full trace on similar questions.
Community Discussion
No community discussion yet for this question.