This program has a famous bug. Each line of input should start with an empty basket, but the items keep piling up.
What to build
A fixed version of the function in the starter.
Requirements
- Find the cause of the bug and fix it in
collect. - Each call of
collect(words)must return a list holding only that line's words. - Keep the same parameter name,
basket.
Input
The first line has n. Each of the next n lines has some words.
Output
One line per input line: its words, separated by spaces.
Constraints
n is from 1 to 50.
Example
Input:
2
a b
c
Output:
a b
c
Why it works
A default value is worked out once, when the function is defined, so a default list is one shared object. None is safe because the new list is then created during each call.
Examples
2 a b c
a b c
3 pen book bag
pen book bag
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
Run the starter on two lines and look at the second line's output.
Hint 2
A default list is created once, when the def line runs, and every call shares it.
Hint 3
Use basket=None, and make a new list inside the function when it is None.
Solution
Show one correct solution (try it yourself first)
def collect(words, basket=None):
if basket is None:
basket = []
for word in words:
basket.append(word)
return basket
n = int(input())
for _ in range(n):
print(" ".join(collect(input().split())))