Reputation: 191
I'd like to compare one element of the list after another. I achieved my goal but it's not a well-written code. Please look at my code and give my a some advices. By the way I have a few other questions
players_list = ( {'player_name': 'Tom',
'player_flag': 'is_human',
'player_decision': None,
'player_points': 1}
{'player_name': 'Peter',
'player_flag': 'is_computer',
'player_decision': None,
'player_points': 2}
{'player_name': 'John',
'player_flag': 'is_computer',
'player_decision': None,
'player_points': 0.5}
{'player_name': 'Greg',
'player_flag': 'is_computer',
'player_decision': None,
'player_points': 2}
)
players_list = sorted(players_list, key = lambda k: k['player_points'], reverse = True)) #(1)
iterator = 0 #(2)
while players_list[iterator]['player_points'] == players_list[iterator + 1]['player_points']:
iterator += 1
print(' >> The Winner Is...', end = ' ')
if iterator == 0:
print(players_list[0]['player_name'].upper(), '!!!') #(3)
elif iterator > 0:
print('There Is a Draw Between ', end = '')
for j in range (0, iterator + 1):
print(players_list[j]['player_name'], end = ', ') # (4))
print() # (5)
(1): Is it the best way in this case to sort my list by values of dictionaries?
(2): It is my idea to compare to solve the problem. Could you give your opinion and- if it is needed - propose better solution, please?
(3): What way of printing in this case would be the most 'pythonic'?
print(players_list[0]['player_name'].upper(), '!!!') # 1
print(%s!!! (players_list[0]['player_name'].upper())) # 2
print({player_name}!!!.format(player_name = players_list[0] ['player_name']).upper()) # 3
(4): How to display list of players in one line without the ',' at the end?
print(players_list[j]['player_name'], end = ', ')
>> Peter, Greg, Tom, John,
(5) I used an empty print() to display '/n' after displaying players in one line. Is there a better solution?
Many thanks
Upvotes: 0
Views: 655
Reputation: 2544
Your code fails when all players have the same number of points.
In any case, you do not need, nor want, to sort the list. You want to scan it, looking for the element(s) with the maximum number of points.
Untested code:
winners = None
winner_points = None
for p in players_list:
points = p['player_points']
if winner_points is None or winner_points < points:
winners = [p]
winner_points = points
elif winner_points == points:
winners.append(p)
if not winners:
print("Nobody played today!")
elif len(winners) == 1:
print("The winner is", winners[0]['player_name'])
else:
print("There is a draw between %d players: %s" % (len(winners), ", ".join(p['player_name'] for p in winners))
Also, coding style:
player_XXX
. player['XXX']
is much more readable. Using objects, i.e. player.XXX
, even more so.Upvotes: 1