#!/usr/bin/env python3 """Rebuild the four-team tied table from six verified historical results.""" import argparse import json from pathlib import Path def calculate(source): names = ['Romania', 'Belgium', 'Slovakia', 'Ukraine'] table = {name: {'team': name, 'played': 0, 'won': 0, 'drawn': 0, 'lost': 0, 'gf': 0, 'ga': 0, 'points': 0} for name in names} seen = set() for match in source['matches']: h, a, hg, ag = (match[k] for k in ('home', 'away', 'home_goals', 'away_goals')) pair = frozenset((h, a)) if len(pair) != 2 or pair in seen or h not in table or a not in table: raise ValueError('Expected one match per distinct pair.') if any(type(n) is not int or n < 0 for n in (hg, ag)): raise ValueError('Invalid goals.') seen.add(pair) for team, gf, ga in ((h, hg, ag), (a, ag, hg)): row = table[team] row['played'] += 1 row['gf'] += gf row['ga'] += ga outcome = 'won' if gf > ga else 'drawn' if gf == ga else 'lost' row[outcome] += 1 row['points'] += 3 if gf > ga else 1 if gf == ga else 0 if len(seen) != 6 or {r['points'] for r in table.values()} != {4}: raise ValueError('This exercise requires all four teams tied after six matches.') for row in table.values(): row['gd'] = row['gf'] - row['ga'] # All four teams are in the tie: their mini-table is the whole group. # This case separates every row at GD/GF, so no recursive tie rule is needed. rows = sorted(table.values(), key=lambda r: (r['gd'], r['gf']), reverse=True) if len({(r['gd'], r['gf']) for r in rows}) != 4: raise ValueError('This narrow example does not implement later tie rules.') assert [r['team'] for r in rows] == names assert sum(r['gf'] for r in rows) == sum(r['ga'] for r in rows) == 11 return rows if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('input_json', type=Path) args = parser.parse_args() print(json.dumps(calculate(json.loads(args.input_json.read_text())), ensure_ascii=False, indent=2))