-1

I'm trying to sort my simple game's leaderboard and print out the top 5 scores, but it just prints out the whole list in the order it was saved as and not organised after adding for eachline in y[:5]: print(eachline) , as without this code, it prints the entire list in numerical order from smallest to highest, which isn't what I need. Any help would be much appreciated. Leaderboard file link: https://drive.google.com/open?id=1w51cgXmmsa1NWMC-F67DMgVi3FgdAdYV

leaders = list()
filename = 'leaderboard.txt'
with open(filename) as fin:
for line in fin:
    leaders.append(line.strip())

y = sorted(leaders, key = lambda x: float(x[0]))
for eachline in y[:5]: #after this and the next line it prints just the file contents
    print(eachline)
Mentlegenn
  • 13
  • 2
  • 1
    Take the last five elements and reverse their order. Either should be a trivial task to solve by simple research. – Ulrich Eckhardt Jan 23 '20 at 19:19
  • 1
    Not sure that is what is going wrong if it "just prints the file contents". Can you provide the leaderboard.txt file so we can debug? – Leon Jan 23 '20 at 19:22

1 Answers1

0

This is partly because your input files are strings structured like "Integer : String". When you open the file and start reading line by line and you call line.strip(), what you do is remove all excess whitespace from the start and end of each line string.

With that in mind, when you sort, you use the key lambda x: float(x[0]). This tells the sorted function to take every person in the leaders list and take the first character of each string (because all the members of the leaders list are strings!), and convert that first character into a float. The value of float(x[0]) for all the people in the leaderboard is 1, which means that the sort algorithm thinks that your values are already sorted!

In order to fix that, you can use split().

leaders = list()
filename = 'leaderboard.txt'
with open(filename) as fin:
    for line in fin:
        leaders.append(line.split())
y = sorted(leaders, key = lambda x: float(x[0]), reverse=True)
for eachline in y[:5]: #after this and the next line it prints just the file contents
    print(" ".join(eachline))

Output:

19 : Felix
16 : Muhammad
14 : Steve
13 : David
12 : Alex

You can sort in descending order by adding keyword reverse=True to the sort method.

y = sorted(leaders, key = lambda x: float(x[0]), reverse=True)
Lapis Rose
  • 644
  • 3
  • 15