Python: tournament
This commit is contained in:
parent
bae42c9a49
commit
2ef852f257
4 changed files with 302 additions and 0 deletions
51
python/tournament/tournament.py
Normal file
51
python/tournament/tournament.py
Normal file
|
|
@ -0,0 +1,51 @@
|
|||
from collections import defaultdict
|
||||
|
||||
SCORES = {'win': 3, 'draw': 1, 'loss': 0}
|
||||
GUEST_RESULT = {'win': 'loss', 'draw': 'draw', 'loss': 'win'}
|
||||
FORMAT = '{0:<30} | {1:>2} | {2:>2} | {3:>2} | {4:>2} | {5:>2}'
|
||||
|
||||
|
||||
class TeamStats:
|
||||
def __init__(self):
|
||||
self.win = 0
|
||||
self.draw = 0
|
||||
self.loss = 0
|
||||
self.__points = None
|
||||
|
||||
def add_game(self, result):
|
||||
setattr(self, result, getattr(self, result) + 1)
|
||||
self.__points = None
|
||||
|
||||
def played(self):
|
||||
return sum(getattr(self, x) for x in SCORES.keys())
|
||||
|
||||
def points(self):
|
||||
|
||||
if self.__points is None:
|
||||
self.__points = sum(SCORES[x]*getattr(self, x)
|
||||
for x in SCORES.keys())
|
||||
|
||||
return self.__points
|
||||
|
||||
|
||||
def tally(rows):
|
||||
|
||||
table = [FORMAT.format('Team', 'MP', 'W', 'D', 'L', 'P')]
|
||||
stats = defaultdict(TeamStats)
|
||||
|
||||
for team_stats in rows:
|
||||
home_team, guest_team, result = team_stats.split(';')
|
||||
|
||||
if result not in SCORES.keys():
|
||||
raise ValueError("Invalid game result")
|
||||
|
||||
stats[home_team].add_game(result)
|
||||
stats[guest_team].add_game(GUEST_RESULT[result])
|
||||
|
||||
for team, team_stats in sorted(stats.items(),
|
||||
key=lambda x: (-x[1].points(), x[0])):
|
||||
table.append(FORMAT.format(team, team_stats.played(), team_stats.win,
|
||||
team_stats.draw, team_stats.loss,
|
||||
team_stats.points()))
|
||||
|
||||
return table
|
||||
Loading…
Add table
Add a link
Reference in a new issue