1. Joining stringsEasy
Building the ID list for a log line crashes with "expected str instance, int found". What fixes it?
line = ", ".join(order_ids)
", ".join(order_ids) → ", ".join(map(str, order_ids))", ".join(order_ids) → str(", ").join(order_ids)", ".join(order_ids) → ", ".join(order_ids, str)", ".join(order_ids) → ", " + str(order_ids)
Show answer
Answer: A. ", ".join(order_ids) → ", ".join(map(str, order_ids))
str.join only accepts strings. Convert as you go with map(str, ...) or a generator: ", ".join(str(i) for i in order_ids).
4. IterationEasy
Pairing user IDs with names, one user silently goes missing. What does this print?
print(list(zip([1, 2, 3], "ab")))
What does it output?
- [(1, 'a'), (2, 'b')]
- [(1, 'a'), (2, 'b'), (3, None)]
- [(1, 'ab'), (2, 'ab'), (3, 'ab')]
- ValueError
Show answer
Answer: A. [(1, 'a'), (2, 'b')]
zip stops at the shortest input, silently dropping the 3. Use itertools.zip_longest to pad, or zip(..., strict=True) (3.10+) to raise on a length mismatch.
5. Context managersEasy
Which review comment matters most on this report export?
f = open(path, "w")
f.write(render(report))
f.close()
- If
render raises, the file stays open; use with open(...) - Open with mode
"a" so an earlier export is never overwritten - Call
f.flush() before f.close(), or the final write can be lost - Write the file in binary mode, which makes the export faster
Show answer
Answer: A. If render raises, the file stays open; use with open(...)
with open(path, "w") as f: closes the file even when render throws. Leaked handles add up in long-running services, and on Windows an open file can’t be replaced or deleted.
8. CollectionsEasy
Counting words crashes with KeyError on the very first word. What fixes it?
counts = {}
for word in words:
counts[word] += 1
counts = {} → counts = defaultdict(int)counts[word] += 1 → counts[word] = 1counts = {} → counts = set()for word in words → for word in set(words)
Show answer
Answer: A. counts = {} → counts = defaultdict(int)
defaultdict(int) creates 0 for a missing key, so += 1 works. collections.Counter(words) does the whole job in one call, and counts.get(word, 0) + 1 works with a plain dict.