"""Easy-tier Python fixes (written 2026-10-12): two straightforward (mutable default argument,
rstrip used as suffix removal), then two subtler ones (split(" ") vs split() with a maxsplit that
must survive the fix; removing from a list while iterating it, where the contract is in place so
rebinding to a comprehension does not count). Graded with python3 (3.9 on the Mac)."""
CONTEXT = "Target: Python 3.9, standard library only."
ITEMS = [
{
"id": "python-mutable-default", "lang": "python", "cat": "bugfix", "context": CONTEXT,
"symptom": "Calling collect_errors(['10:01 ERROR disk full']) and then collect_errors(['11:00 INFO all good']) returns ['10:01 ERROR disk full'] from the second call, which should be [] because that log has no errors.",
"buggy": '''def collect_errors(lines, errors=[]):
"""Append the ERROR lines of lines (stripped) to errors and return it.
Callers pass their own list to accumulate into, or leave it out to get a new list.
"""
for line in lines:
if " ERROR " in line:
errors.append(line.strip())
return errors
''',
"fix": '''def collect_errors(lines, errors=None):
"""Append the ERROR lines of lines (stripped) to errors and return it.
Callers pass their own list to accumulate into, or leave it out to get a new list.
"""
if errors is None:
errors = []
for line in lines:
if " ERROR " in line:
errors.append(line.strip())
return errors
''',
"test": '''import sys
from solution import collect_errors
fails = []
def check(label, got, want):
if got != want:
fails.append("%s: got %r, want %r" % (label, got, want))
first = collect_errors(["10:01 ERROR disk full\\n", "10:02 INFO rotated\\n"])
check("first call", first, ["10:01 ERROR disk full"])
second = collect_errors(["11:00 INFO all good\\n"])
check("second call on a clean log", second, [])
check("first result left alone", first, ["10:01 ERROR disk full"])
acc = ["09:00 ERROR earlier"]
out = collect_errors(["12:00 ERROR timeout", "12:01 WARN slow"], acc)
check("accumulates into the caller's list", acc, ["09:00 ERROR earlier", "12:00 ERROR timeout"])
check("returns the caller's list", out is acc, True)
empty = []
out = collect_errors(["13:00 ERROR boom"], empty)
check("fills an empty caller list", empty, ["13:00 ERROR boom"])
check("returns that empty caller list", out is empty, True)
check("later default call", collect_errors([]), [])
if fails:
print("\\n".join(fails))
sys.exit(1)
print("OK")
''',
},
{
"id": "python-strip-domain", "lang": "python", "cat": "bugfix", "context": CONTEXT,
"symptom": "short_name('mail.example.com', 'example.com') returns 'mai' instead of 'mail', and short_name('pool.corp.lan', 'corp.lan') returns '' instead of 'pool' (short_name('web01.example.com', 'example.com') correctly gives 'web01').",
"buggy": '''def short_name(fqdn, domain):
"""Return fqdn without its trailing ".<domain>"; names outside domain come back unchanged."""
return fqdn.rstrip("." + domain)
''',
"fix": '''def short_name(fqdn, domain):
"""Return fqdn without its trailing ".<domain>"; names outside domain come back unchanged."""
suffix = "." + domain
if fqdn.endswith(suffix):
return fqdn[:-len(suffix)]
return fqdn
''',
"test": '''import sys
from solution import short_name
cases = [
("web01.example.com", "example.com", "web01"),
("mail.example.com", "example.com", "mail"),
("pool.corp.lan", "corp.lan", "pool"),
("app.prod.example.com", "example.com", "app.prod"),
("db01.example.org", "example.com", "db01.example.org"),
("mail.example.com.au", "example.com", "mail.example.com.au"),
("notexample.com", "example.com", "notexample.com"),
("example.com", "example.com", "example.com"),
]
fails = []
for fqdn, domain, want in cases:
got = short_name(fqdn, domain)
if got != want:
fails.append("short_name(%r, %r) = %r, want %r" % (fqdn, domain, got, want))
if fails:
print("\\n".join(fails))
sys.exit(1)
print("OK")
''',
},
{
"id": "python-df-columns", "lang": "python", "cat": "bugfix", "context": CONTEXT,
"symptom": "parse_df_line('/dev/sda1 41152736 12345678 26693908 32% /') returns ('26693908 32% /', 12345678) instead of ('/', 32); lines where the columns are separated by single spaces parse correctly.",
"buggy": '''def parse_df_line(line):
"""Parse one data line of `df -P -k` output into (mount_point, percent_used).
Columns: Filesystem, 1024-blocks, Used, Available, Capacity, Mounted on.
The mount point is the last column and may contain spaces.
"""
fields = line.split(" ", 5)
return fields[5], int(fields[4].rstrip("%"))
''',
"fix": '''def parse_df_line(line):
"""Parse one data line of `df -P -k` output into (mount_point, percent_used).
Columns: Filesystem, 1024-blocks, Used, Available, Capacity, Mounted on.
The mount point is the last column and may contain spaces.
"""
fields = line.split(None, 5)
return fields[5], int(fields[4].rstrip("%"))
''',
"test": '''import sys
from solution import parse_df_line
cases = [
("/dev/sda1 41152736 12345678 26693908 32% /", ("/", 32)),
("/dev/sdb1 976284628 878656165 97628463 91% /srv/backup", ("/srv/backup", 91)),
("tmpfs 819200 0 819200 0% /run/user/1000", ("/run/user/1000", 0)),
("/dev/disk5s2 1953513560 1758162204 195351356 91% /Volumes/Backup Disk",
("/Volumes/Backup Disk", 91)),
("//user@fileserv/media 3906250000 3906250000 0 100% /Volumes/media (nas) 2",
("/Volumes/media (nas) 2", 100)),
("/dev/nvme0n1p2 487652564 12 487652552 1% /mnt/old disk", ("/mnt/old disk", 1)),
]
fails = []
for line, want in cases:
try:
got = parse_df_line(line)
except Exception as e: # noqa: BLE001
got = "raised %r" % e
if got != want or not isinstance(got[1], int):
fails.append("parse_df_line(%r) = %r, want %r" % (line, got, want))
if fails:
print("\\n".join(fails))
sys.exit(1)
print("OK")
''',
},
{
"id": "python-prune-in-place", "lang": "python", "cat": "bugfix", "context": CONTEXT,
"symptom": "With hosts a(up), b(down), c(down), d(up), drop_down returns 1 and leaves the list as [a, c, d]; it should return 2 and leave [a, d].",
"buggy": '''def drop_down(hosts):
"""Remove every host whose status is "down" from hosts and return how many were removed.
hosts is a list of dicts with "name" and "status"; callers keep using the same list
object afterwards, so it is changed in place.
"""
removed = 0
for host in hosts:
if host["status"] == "down":
hosts.remove(host)
removed += 1
return removed
''',
"fix": '''def drop_down(hosts):
"""Remove every host whose status is "down" from hosts and return how many were removed.
hosts is a list of dicts with "name" and "status"; callers keep using the same list
object afterwards, so it is changed in place.
"""
kept = [host for host in hosts if host["status"] != "down"]
removed = len(hosts) - len(kept)
hosts[:] = kept
return removed
''',
"test": '''import sys
from solution import drop_down
fails = []
def run(spec, want_removed, want_names):
hosts = [{"name": n, "status": s} for n, s in spec]
inventory = hosts
removed = drop_down(hosts)
names = [h["name"] for h in inventory]
if removed != want_removed or names != want_names:
fails.append("%r: removed=%r left=%r, want removed=%r left=%r"
% (spec, removed, names, want_removed, want_names))
run([("a", "up"), ("b", "down"), ("c", "down"), ("d", "up")], 2, ["a", "d"])
run([("p", "down"), ("q", "down"), ("r", "down")], 3, [])
run([("e", "down"), ("f", "up"), ("g", "down"), ("h", "down"), ("i", "up")], 3, ["f", "i"])
run([("x", "up"), ("y", "maintenance")], 0, ["x", "y"])
run([], 0, [])
if fails:
print("\\n".join(fails))
sys.exit(1)
print("OK")
''',
},
]