These fours 'teams' consequently did total number of 'goals':
teams = ['W', 'X', 'Y', 'Z']
goals = [4, 5, 1, 9]
Now, how to know which team did following goals?
given_goals = [3, 2, 7, 15]
The expected answer should be in this form:
answers = [('W', (2, 3)),
('X', 7),
('Z', 15)]
W
made 4 consecutive goals therefore the 2nd and 3rd goal is theirs. Then X
made 5 consecutive goals (5-10) after W
so goal number 7 is theirs and so on.
I tried but it seems difficult way:
teams_ = [team for team, goal in zip(teams, goals) for g in range(goal)]
teams_goals = [teams_[g-1] for g in given_goals]
print teams_goals
Is there an easier way?
That's the most efficient way I believe:
import bisect
import itertools
teams = ['W', 'X', 'Y', 'Z']
goals = [4, 5, 1, 9]
# Create the max goal of each team
goal_ranges = itertools.accumulate(goals)
# Create sorted tuples of goals and teams (comes sorted because of accumulate)
ordered_teams = list(zip(goal_ranges, teams))
def get_team(goal_number):
# Get the leftmost occurence of the goal number, and extract the team from the tuple
return ordered_teams[bisect.bisect_left(ordered_teams, (goal_number,))][1]
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments