Join us and get access to thousands of tutorials and a community of expert Pythonistas.
This lesson is for members only. Join us and get access to thousands of tutorials and a community of expert Pythonistas.
Building Relay Teams
00:00 In this lesson, you’ll pick relay teams for a community swim club by composing groupby(), min(), sorted(), and batched() into one pipeline. The swim club has a season’s worth of race times in a CSV file, and it needs relay teams for next season.
00:18 Every stroke gets an A team and a B team. The four swimmers with the best times make the A team, and the next four make the B team. Each race was timed by three stopwatches, and the official time is the median of the three.
00:35 Start with the building blocks for a single race. You need the median of three times, so import the statistics module. Event is another named tuple, with a stroke, a swimmer’s name, and a time.
00:50 Its less-than method compares times, so min() finds the fastest event. median_time() parses the three stopwatch strings into time objects and returns their median.
01:01 The median is the middle value, so one stopwatch that’s a little fast or slow can’t skew the result. Now read the file. read_events() names only the first three columns.
01:14 With restkey set to Times, the reader collects the three stopwatch columns into one list. Then each row becomes an Event with its median time.
01:30 Read all the events into a tuple.
01:34 There are sixteen hundred events, and the first one is Emma’s freestyle race, with a median time of just under fifty-one seconds. Here’s the plan. First, group the events by stroke.
01:46 Then, within each stroke, group the events by swimmer, and keep each swimmer’s best time with min(). Sort those best times from fastest to slowest. Finally, batched() cuts the ranking into groups of four, and zip() pairs the first two batches with the letters A and B.
02:03 Start with a function that handles a single stroke. relay_teams() groups the events by name, keeps each swimmer’s best time, and ranks them. Then it batches the ranking into fours.
02:15 Since zip() stops at the shortest input, you get exactly two teams, however many swimmers there are. Each team is a label, A or B, paired with a tuple of four swimmers.
02:27 Now loop over the strokes. For each stroke, print both teams. That’s eight relay teams, two per stroke. Notice that a few strong all-round swimmers make more than one team.
02:39 Each team lists its swimmers from fastest to slowest. Elizabeth, Addison, and Madison, for example, each swim in two different strokes. In this lesson, you built a complete data pipeline that turns a season of race times into relay teams, using groupby(), batched(), and a few built-ins.
02:59 Next up, you’ll review everything you’ve learned in this course.
Become a Member to join the conversation.