Try it on paper first. A hint, the key idea and the worked solution are here when you need them.
This function should give the average of a list, but gives a wrong answer for [2, 4, 6] (it gives 5.0, and the average is 4). Explain the bug in one sentence, and fix it.
Have you tried it?
Work it out on paper first. It is fine to get stuck or make a mistake: that is how we learn. When you are ready, go through the solution one step at a time, and check each step against your own.
Plan. Follow it by hand for [2, 4, 6]. The loop adds 2, 4 and 6, so total is 12, and count is 3. The function returns 12 / 3 + 1, which is 5.0. The expected average is 4.
The bug in a sentence: the function adds 1 at the end (+ 1), so the answer is always one too big. (The line count = len(numbers) inside the loop is not the cause here, but it is wasteful, and for an empty list the loop never runs, so count is never made and the function would fail with a NameError.)
The fix.
Check. [2, 4, 6] gives 4.0, and an empty list gives 0.0.
Answer: The stray + 1 makes the result one too big (5.0 instead of 4.0). Remove it, and handle the empty list.
Log in to join the discussion.
Loading…