so I need to sort some high scores into order and here is the code I already have:
def sortscores():namelist = []scorelist = []hs = open("hst.txt", "r")hscounter = 0for line in hs:if counter%2 !=0:name = lineothername = name[0:len(name)-1]namelist.append(othername)else:scorelist.append(int(line))
This puts the names and scores into lists so now I need to have them sorted but I can't use the .sort() function because I have to write the sort myself so can anyone tell me how I would do this? (sort the scores into descending order whilst keeping the names with the correct scores)
If you store your high scores in (name, score)
tuples, then you can easily keep them together. Since you need to write the sort function yourself, it might be helpful to look at an example of using tuples in another problem. Here's an example of simply finding the maximum score while keeping the name and scores together.
First, set up the data. You can use zip
for this
names = ['John', 'Jane', 'Tim', 'Sara']
scores = [100, 120, 80, 90]
data = list(zip(names, scores)) # For Python 2.X you don't need the 'list' constructor
print(data)
Outputs:
[('John', 100), ('Jane', 120), ('Tim', 80), ('Sara', 90)]
Now find the maximum entry:
max_entry = ('', 0)
for entry in data:if entry[1] > max_entry[1]:max_entry = entryprint(max_entry)
Outputs:
('Jane', 120)