A network administrator uses a Python script to analyze firewall logs. The script reads a CSV file with columns 'src_ip', 'dst_ip', 'action', 'time'. It needs to build a list of source IPs that have been blocked more than 3 times. The current code: blocked_count = {} blocked_ips = [] for row in logs: if row['action'] == 'block': if row['src_ip'] in blocked_count: blocked_count[row['src_ip']] += 1 else: blocked_count[row['src_ip']] = 1 for ip, count in blocked_count.items(): if count > 3: blocked_ips.append(ip) The script runs correctly but slowly on large logs. The administrator wants to optimize it. Which change would most improve performance?
Counter is optimized for frequency counting.
Why this answer
Using `collections.Counter` replaces the manual dictionary increment logic with a single optimized C-level operation, reducing Python bytecode execution overhead. The Counter's `most_common()` method or direct iteration over items still requires a second loop, but the first loop's increment is significantly faster due to internal C implementation, which is the primary bottleneck in large log processing.
Exam trap
The trap here is that candidates focus on the second loop's syntax (list comprehension) or data structure (set) instead of recognizing that the first loop's manual counting logic is the real performance bottleneck, which `Counter` optimizes via C-level internals.
How to eliminate wrong answers
Option A is wrong because converting the second loop to a list comprehension only marginally reduces overhead (avoids `.append()` calls) but does not address the main performance bottleneck—the first loop's manual dictionary increment. Option B is wrong because pre-allocating the list (e.g., `blocked_ips = [None] * n`) is not feasible here since the number of blocked IPs is unknown until after counting, and Python lists already handle dynamic resizing efficiently. Option C is wrong because using a set for `blocked_ips` would prevent duplicates but does not improve the counting loop's performance; the current code already ensures uniqueness by appending only once per IP due to the `count > 3` condition.