'Using higher order functions to filter/sort/reduce nested dictionaries
I have been given a class exercise to solve in Python and I have no idea how to go about it:
get_wins(wsu_games, team)
Assume you would like to find the scores for the games WSU won against a given team. Write a functionget_winsthat takes the WSU game data and a team name as input, and returns a list of tuples that includes the years and scores of each game WSU played and won against that team.For example,
get_wins(wsu_games,'UTAH')returns[(2018, (28, 24))](WSU played 4 games with 'UTAH' but won only the 2018 game)get_wins(wsu_games,'STAN')returns[(2018, (41, 38)), (2019, (49, 22)), (2021, (34, 31))](WSU played 3 games with 'STAN' and won all 3 games)The dataset:
wsu_games = { 2018: { "WYO":(41,19), "SJSU":(31,0), "EWU":(59,24), "USC":(36,39), "UTAH":(28,24), "ORST":(56,37), "ORE":(34,20), "STAN":(41,38), "CAL":(19,13), "COLO":(31,7), "ARIZ":(69,28), "WASH":(15,28), "ISU":(28,26)}, 2019: { "NMSU":(58,7), "UNCO":(59,17), "HOU":(31,24), "UCLA":(63,67), "UTAH":(13,38), "ASU":(34,38), "COLO":(41,10), "ORE":(35,37), "CAL":(20,33), "STAN":(49,22), "ORST":(54,53), "WASH":(13,31), "AFA":(21,31) }, 2020: { "ORST":(38,28), "ORE":(29,43), "USC":(13,38), "UTAH":(28,45)}, 2021: { "USU":(23,26), "PORT ST.":(44,24), "USC":(14,45), "UTAH":(13,24), "CAL":(21,6), "ORST":(31,24), "STAN":(34,31), "BYU":(19,21), "ASU":(34,21), "ORE":(24,38), "ARIZ":(44,18), "WASH":(40,13), "CMU":(21,24)} }
We are not allowed to use loops of any kind to solve problems in this class. (Solving with loops would be relatively easy, higher order functions not so much).
How can I do this?
Solution 1:[1]
Try:
def get_wins(games, team):
return list(
map(
lambda v: (v, games[v][team]),
filter(
lambda k: team in games[k]
and games[k][team][0] > games[k][team][1],
games,
),
)
)
print(get_wins(wsu_games, "STAN"))
Prints:
[(2018, (41, 38)), (2019, (49, 22)), (2021, (34, 31))]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Andrej Kesely |
