Complete worked example
python
def summarize(rows, country):
if not isinstance(rows, list) or not isinstance(country, str) or not country.strip():
raise ValueError("Expected records and a country")
fields = ("id", "company", "country")
by_id = {}
for row in rows:
if not isinstance(row, dict) or type(row.get("active")) is not bool:
raise ValueError("Expected a boolean active field")
if not all(isinstance(row.get(key), str) and row[key].strip() for key in fields):
raise ValueError("Expected nonempty fields")
clean = {key: row[key].strip() for key in fields}
clean["country"] = clean["country"].upper()
clean["active"] = row["active"]
identity = clean["id"]
if identity in by_id and by_id[identity] != clean:
raise ValueError("Conflicting identity")
by_id[identity] = clean
selected = [row for row in by_id.values()
if row["active"] and row["country"] == country.strip().upper()]
ids = sorted(row["id"] for row in selected)
companies = len({row["company"] for row in selected})
return {"ids": ids, "companies": companies}- Reasoning
- Canonical conflicts are checked before the selected view; equal duplicates count once.