Breaking Ties Without Reversing the Sort
By points alone, two pairs of teams in the provisional table are level: Rovers and Athletic on 16, Dynamo and Wanderers on 13. In this lesson, you ported the line of Nadia’s script that ranks them.
Here’s her step, with provisional holding the six teams in alphabetical order:
def standings(teams):
return sorted(
teams,
key=lambda t: (
t["points"],
t["scored"] - t["conceded"],
),
reverse=True,
)
for t in standings(provisional):
print(t["team"], t["points"])
- Python compares two tuples field by field. Rovers and Athletic have the same points, so goal difference decides, and Rovers’ +9 beats Athletic’s +6. Dynamo and Wanderers are level on both, so their tuples are equal, and Python leaves them in the order the list had them: Dynamo stays third.
- Ported a part at a time, the goal difference becomes a small function,
goalDifference(), and the key turns into a compare function fortoSorted(), handed two teams. JavaScript has no tuples to compare, so you write the “then” yourself with||, JavaScript’s or operator. - Like Python’s
or,||hands back its left side when that’s truthy, and otherwise its right side. For Dynamo and United, the points give 4, which is truthy, so that’s the answer. For Rovers and Athletic, they give 0, which is falsy in both languages, so||moves on to the goal difference. Dynamo and Wanderers give 0 for both, and 0 says the two are equal. - Last lesson, b minus a replaced the negated key,
-t["points"]. Nothing in this key is negated: its direction isreverse=True. Keeping the direction out of the compare function too means sorting smallest first and calling.toReversed()on the sorted copy. That runs without an error, but it prints Wanderers third and Dynamo fourth, while Python keeps Dynamo third. - Before the reverse, Dynamo and Wanderers compare as 0, so they keep their list order. A sort that keeps equal items in their order is called stable. Python’s sort is stable, and JavaScript has guaranteed it since 2019.
.toReversed()then turns the whole list round, the tied pair too. - Python’s
reverse=Truesorts largest first instead, and still keeps ties in list order. Python’sreversed()on the sorted list would swap them too. - So put the direction inside the compare function: for largest first, swap
aandb, b minus a, for every field, and drop the reverse. Nothing turns the list round now, so the stable sort leaves Dynamo ahead of Wanderers, asreverse=Truedoes. - Dynamo is above Wanderers only because the list arrived in alphabetical order. In last week’s order, with Wanderers ahead, the function would put Wanderers third, and so would Python’s line. A last tie-breaker that can’t tie, the team names compared with
localeCompare(), keeps Dynamo third whatever order the records arrive in. In Python, you can sort twice, by name and then by the key, and twotoSorted()calls work the same way.