In each of the 10000 iterations, we select the player with the least total score to play a game, where he will earn a random score.
I think the slowest part of the code in each iteration appears to be the summing of all the players score.
sum(g.score for g in players[x])
Since only one player's score is updated in each iteration, it seems that caching may help speed up the current O(N) implementation into a O(1).
What is a good way to make use of caching? Thank you!
import random
class Game:
def __init__(self, score):
self.score = score
players = {f"player{i}": [] for i in range(8)}
for i in range(10000):
player = min(players, key=lambda x: sum(g.score for g in players[x]))
players[player].append(Game(random.randint(0, 10)))
for player, games in players.items():
print(player, ":", sum(g.score for g in games))