I am having trouble with getting the names and scores I am appending to scoreboard list to show the top 3 when the print_leaderboard() function is called. Any help would be great!
Here is the code I have.
class ScoreEntry:
def __init__(self,name,score):
self.name = name
self.score = score
def get_score(score_entry):
return score_entry.score
class Scoreboard:
def __init__ (self):
self.scoreboard = []
def add_score(self,name,score):
new_entry = ([name], [score])
self.scoreboard.append([new_entry])
return ([new_entry])
def print_leaderboard():
scoreboard.sort(reverse=True)
print(scoreboard[0:2])
#Get list of scores, sort them into numerical order by score, then use print to display top three by slicing in descending order
# Write your methods here
scoreboard = Scoreboard ()
scoreboard.add_score('Alice', 7821)
scoreboard.add_score('Bob', 12103)
scoreboard.add_score('Charlie', 8762)
scoreboard.add_score('Denise', 6753)
Scoreboard.print_leaderboard ()
That is what I have tried. But I keep getting the error Scoreboard object has no attribute sort What can I do to make this function work. I assume I will need to change some of the other defined functions too.
There are a few issues:
Not sure why you're wrapping all these things in list literals. You're also not using your
ScoreEntryclass for anything currently. Might as well use it? Also, I don't think this method needs to return anything:Next:
This is not an instance method. Notice how this function takes no parameters (unlike
add_scorewhich takesselfas the first parameter.) This is a static method (for no good reason?)scoreboardwithin the scope of this function hasn't been defined, so Python will step out of the current scope and look for that variable in the next more-global scope, which in this case is just the global scope.scoreboardis defined in the global scope, but it's bound to aScoreboardobject, not a list. Lists have asortmethod, butScoreboardobjects do not. I think you just want this to be an instance method:The
keykeyword parameter is required in this case, becauseself.scoreboardis a list ofScoreEntryobjects, and you need to define how they can be sorted/compared.And then in the calling code:
Scoreboard.print_leaderboard()->scoreboard.print_leaderboard()