pythoncomputer-scienceleaderboard

how to make a ordered leader board in python


we have a computing project and in the final stages I have to make a ordered leader board (top5). however this is more confusing than i thought. I've got this far so far but it isn't ordered nor the top 5.

def leaderboard():
    print ("\n")
    print ("⬇ Check out the leaderboard ⬇") #LEADERBOARD SECTION
    f = open('H_Highscore.txt', 'r')
    leaderboard = [line.replace('\n','') for line in f.readlines()]
    i = 0
    limit = 5
    while i < limit:
        leaderboard_tuples = [tuple(x.split(',')) for x in leaderboard]
        leaderboard_tuples.sort(key=lambda tup: tup[0])
        i+=1
    for i in leaderboard:
        print(i)
    f.close()
    time.sleep(10)

user = str(input("Enter a name: "))
file = open ("H_Highscore.txt", "a")
score = str(input("enter you score: "))
file.write("\n")
file.write(user)
file.write(",")
file.write(str(score)) # (int(x)) can not be written
file.write("pts")
file.write("\n")
file.close()
time.sleep(0.5)
leaderboard() 

it would be great if got some help but it's fine if I can't find any help.


Solution

  • You are trying to sort on a string, eg 10pts. Key is to convert the string representation of the integer that is read from the text file back to an integer with int(), and then sort on that:

    def leaderboard():
        print ("\n")
        print ("⬇ Check out the leaderboard ⬇") #LEADERBOARD SECTION
        f = open('H_Highscore.txt', 'r')
        leaderboard = [line.strip().split(',') for line in f.readlines() if line.strip()]
        leaderboard = [(i[0], int(i[1][:-3])) for i in leaderboard]
        leaderboard.sort(key=lambda tup: tup[1], reverse=True)
        for i in leaderboard[:5]:
            print(i[0], i[1],'pts')
        f.close()
        time.sleep(10)
    
    user = str(input("Enter a name: "))
    file = open ("H_Highscore.txt", "a")
    score = str(input("enter you score: "))
    file.write(f"{user},{score}pts\n")
    file.close()
    time.sleep(0.5)
    leaderboard()