Reputation: 19
I am writing a program which saves the last 3 scores in a text file for each user of my game. I have already written the code that saves it I am now bringing the data back into the program which will work out the users high scores . I also already have the scores saved in separate lists All users 1st score saved in 1 list all users 2nd score in another and the same for 3rd score. I am trying to put these in their own high score list so when I joint the lists with the names(in another list) I will be able to sort by score but will be attached to name. Bellow is the code I have written:
for i in range (2):
if score1[i] > score2[i] or score1[i]> score3[i]:
highscores.append(score1[i])
elif score2[i] > score1[i] or score2[i] > score3[i]:
highscores.append(score2[i])
elif score3[i] > score1[i] or score3[i] > score2[i]:
highscores.append(score3[i])
By the way it is in a for loop for i in range 2 as their are currently only 2 users. I know I'm being incredibly stupid by having the or as it means only one event needs to be true for it to work but when I tried and it didn't work either. Please work along these lines as my tutor said 'I had the right idea' I also hope this helps anyone else which is comparing list items with integers in python as I couldn't find anything on the internet . Thanks, I await guidance
Upvotes: 0
Views: 98
Reputation: 155684
Probably not allowed for this assignment, but for others who need to do something similar, the easy/fast way to select the top 3 values from a large sequence of values is to use heapq.nlargest
. If you have multiple sequences, you can itertools.chain
them to avoid concatenating (avoid increases in peak memory usage). You can even attach the names (with zip
and itertools.repeat
) to each input sequence so the selected high scores include the associated user:
from heapq import nlargest
from itertools import chain, repeat
highscores = nlargest(3, chain(zip(score1, repeat('user1')),
zip(score2, repeat('user2')),
zip(score3, repeat('user3'))))
highscores
would then be a list
with three elements (from highest to lowest score, ties broken by user name), each element being a tuple
of the form (score, username)
.
Upvotes: 1
Reputation: 81684
and
, not or
.a < b < c
syntax instead of using and
.What you should really do is use Python's built-in max
function. A clean, single-liner instead of that 6-line if-elif
block.
highscores.append(max(score1[i], score2[i], score3[i]))
Upvotes: 2