from comprehension_history import DIMENSIONS, PLACE, Seat from failure import Failure from larv_review.seats import FIRST_SEATS, SPLIT_SEATS, vote_line VOTES = ("better", "same", "worse") def votes(seats: list[Seat]) -> dict[str, list[str]] | Failure: """Each seat's five votes as written, in DIMENSIONS' order.""" names = [seat.name for seat in seats] if names[:2] != list(FIRST_SEATS) or names[2:] not in ([], list(SPLIT_SEATS)): return Failure(f"a paired ruling's seats are {' and '.join(FIRST_SEATS)}, then, when their overall votes differ, {' and '.join(SPLIT_SEATS)}, in that order; the file has {', '.join(names) or 'none'}") said = {} for seat in seats: line = vote_line(seat.name, seat.said) if isinstance(line, Failure): return line if unnamed := [place for place in seat.places if not place_dimensions(place)]: return Failure(f"{seat.name}'s place does not open with the dimensions it moves, each one of {', '.join(DIMENSIONS)}, then `: `: {unnamed[0]}") said[seat.name] = line first, second, *more = (each[-1] for each in counted(seats, said).values()) if more and first == second: return Failure(f"{' and '.join(FIRST_SEATS)} both count as {first} overall, which settles the ruling; drop the other seats' lines") return said def counted(seats: list[Seat], said: dict[str, list[str]]) -> dict[str, list[str]]: """Each seat's votes as they count: a dimension's vote counts as same unless one of the seat's `path:line` places opens with that dimension, and the overall vote unless the seat names any such place.""" return {seat.name: [vote if names_a_place(seat, name) else "same" for name, vote in zip(DIMENSIONS, said[seat.name])] for seat in seats} def names_a_place(seat: Seat, dimension: str) -> bool: return any(PLACE.search(place) and (dimension == DIMENSIONS[-1] or dimension in place_dimensions(place)) for place in seat.places) def place_dimensions(place: str) -> list[str]: """The dimensions a place opens with, as in `Locality, Shape: `path:line` ...`; empty when any name before the first `: ` is no dimension.""" named = place.partition(": ")[0].split(", ") return named if all(name in DIMENSIONS for name in named) else [] def ruling(counted: list[str]) -> str | None: """The vote that leads each other vote by two or more, else same; None when only the first two seats voted and they differ, so two more must vote.""" if len(counted) == 2 and counted[0] != counted[1]: return None for vote in VOTES: if all(counted.count(vote) >= counted.count(other) + 2 for other in VOTES if other != vote): return vote return "same" def fallen(counted: dict[str, list[str]]) -> list[str]: """Each dimension, Overall aside, that the seats rule worse by a lead of two.""" return [name for name, column in zip(DIMENSIONS[:-1], zip(*counted.values())) if ruling(list(column)) == "worse"]