…
…
Build the single round-robin fixture list of a campus five-a-side tournament with nested loops, parse the score lines, calculate wins, draws, losses, and goal difference, sort by points, goal difference, and goals for, and write the aligned table to a file.
In the Campus Spring Cup, six student teams play a single round-robin tournament on a five-a-side pitch: each team plays every other team once. The tournament committee writes the results line by line to results.txt every week, and until now it calculated the league table by hand. Last week a mistake in the goal difference made two teams appeal; the committee wants to leave this job to a program.
Output# Week 1
Falcons 3-1 Lightning
Blue Stars 2-2 Northerners
Storm 0-1 Night OwlsIn this project you will build the fixture list, parse the score lines, find the postponed match, work out each team's statistics, and sort the table by the rules: first points, then goal difference if points are equal, then goals for if that is equal too.
The table you will have at the end (league_table.txt):
Output Team P W D L GF GA GD Pts
1. Northerners 5 3 1 1 9 5 4 10
2. Falcons 5 3 1 1 11 9 2 10
3. Lightning 4 2 0 2 9 8 1 6
...The first two teams have equal points. Falcons scored more goals, but Northerners have the better goal difference; by the rule, Northerners are on top.
Lessons used: for and range (10), nested loops (13), functions (14–16), string methods and formatting (21–22), lists and enumerate (23–24), accumulating in dictionaries and records (26–28), tuples and sets (29), comprehensions (30), sorting with key and lambda (31), text files (33).
How to work: The steps share one session; the functions and variables you define in one step are used by the next steps, so run the steps in order. In each step, the comment lines tell you what to do; you write the parts that have ___. The check also tries your functions with other teams and scores, in addition to checking the output.
What you'll do
results.txtDownload file
Reading file…
Code cells are for members
You can read the steps. Sign up free to run the code, complete the steps and save your progress.
The Campus Spring Cup has six teams, and the tournament is single round-robin: each team plays every other team once. First you will build the fixture list, that is, the list of all the matches to be played.
This is a job for nested loops (lesson 13). The outer loop picks each team in turn; the inner loop goes over only the teams that come after it. If the inner loop started from the beginning, every team would be paired with itself, and every match would be written twice (A–B and B–A). Working with indexes solves this: if i is the index of the outer team, the inner loop is range(i + 1, len(teams)).
Each match goes into the list as a (home, away) tuple. In a single round-robin tournament with n teams there are n * (n - 1) / 2 matches; for six teams, 15.
This step's code cell is for members.Sign up free
Match results come from the referee's table as text lines like Falcons 3-1 Lightning. You will turn a line into a tuple the program can use: ("Falcons", 3, 1, "Lightning")
Code cells are for members
You can read the steps. Sign up free to run the code, complete the steps and save your progress.
The trick is the team names: Blue Stars has two words. If you split the line into words with split() and say "the first word is the home team and the last word is the away team", two-word names break. Instead, find the score: the part that contains a - is the score. The parts before it, joined with " ".join(...), give the home team, and the parts after it give the away team. You split the score into two with split("-") and convert the pieces with int.
split() without a separator drops leading, trailing, and extra spaces on its own (lesson 21); there are lines like that in the file.
This step's code cell is for members.Sign up free
All the results are in results.txt. Besides the match lines, the file has comment lines that start with # and blank lines that separate the weeks; you will skip these (lesson 33: you loop over the file line by line with for line in f:).
Then compare with the fixture list: is there a match that has not been played? Watch out: in the results file, the home team can be the reverse of the order in the fixture list (Night Owls 1-2 Falcons, while the fixture list has ("Falcons", "Night Owls")). So put the played matches into a set as (home, away) and ask about both directions of each match in the fixture list. The in question on a set is fast (lesson 29).
This step's code cell is for members.Sign up free
Now you will keep a row for each team: played (P), won (W), drawn (D), lost (L), goals for (GF), goals against (GA), and points (Pts). A win is worth 3 points, a draw 1 point, and a loss 0.
The table is a dictionary: the key is the team name, and the value is that team's statistics dictionary. empty_stats() gives the starting values. Build the table with a dictionary comprehension (lesson 30); the function must be called again for each team so that each team gets its own dictionary (the reference trap from lesson 25).
apply_match updates a single team's row: it takes the goals scored and conceded, and decides whether the team won, drew, or lost. Every match has two teams, so build_table calls apply_match twice for each match: for the home team with (home_goals, away_goals), and for the away team with (away_goals, home_goals).
This step's code cell is for members.Sign up free
The league table is sorted first by points. If points are equal, goal difference (goals for − goals against) is checked, and if that is equal too, goals for. If everything is equal, the teams are put in alphabetical order by name.
To sort by several criteria, the key function can return a tuple instead of a single number. Python compares tuples from left to right: if the first elements differ, the decision is made there; if they are equal, it moves to the second element. (10, 4) > (10, 2) is true, because the first elements are equal and 4 is larger in the second.
There is one problem: points, goal difference, and goals must go from largest to smallest, but the name must go from A to Z. reverse=True flips all of them at once. The solution is to put a minus sign in front of the numbers: in an ascending sort, -10 comes before -7, so the larger score moves to the front, while the name stays as it is:
key=lambda record: (-points, -goal_diff, -goals_for, name)table.items() gives a (name, stats) pair for each team; in the lambda, record[0] is the name and record[1] is the statistics dictionary.
This step's code cell is for members.Sign up free
The ranking is ready; now you will turn it into table text to pin on a notice board. table_text(ranked) returns all the lines as a single string: first the header line (provided), then one line for each team. Collect the lines in a list and join them with "\n".join(lines).
Aligning the columns is the formatting work from lesson 22: the position is right-aligned in 2 characters followed by a period, the team name is left-aligned in 16 characters, and the numbers are right-aligned. The widths must be the same as in the header so that the columns line up: 3 characters each for P W D L, and 4 characters each for GF GA GD Pts.
The function does not print; it returns the text. That way you can write the same text to a file in the next step.
This step's code cell is for members.Sign up free
The tournament committee will pin the table on the campus notice board. Write the text from the previous step to league_table.txt (lesson 33, the "w" mode), then read the file back and print how many lines it has.
Then pull out three pieces of information the committee asks for:
max(table, key=...) gives the name of the team that scored the most goals (lesson 31).sum or len).This step's code cell is for members.Sign up free