1.Show an option to get the details from the leaderboard db.
2.And find a way to sort it based on difficulty and attempts(Either descending or ascending).
CODE:
`leaderboard = [
{"name": "Alice", "difficulty": "Easy", "attempts": 3},
{"name": "Bob", "difficulty": "Hard", "attempts": 7},
{"name": "Charlie", "difficulty": "Medium", "attempts": 5},
{"name": "David", "difficulty": "Easy", "attempts": 2}
]
difficulty_order = {"Easy": 1, "Medium": 2, "Hard": 3}
def show_leaderboard(data):
print("\n--- Leaderboard ---")
for player in data:
print(f"{player['name']} | {player['difficulty']} | Attempts: {player['attempts']}")
def sort_by_attempts(data, reverse=False):
return sorted(data, key=lambda x: x["attempts"], reverse=reverse)
def sort_by_difficulty(data, reverse=False):
return sorted(data, key=lambda x: difficulty_order[x["difficulty"]], reverse=reverse)
while True:
print("\n1. Show Leaderboard")
print("2. Sort by Attempts (Ascending)")
print("3. Sort by Attempts (Descending)")
print("4. Sort by Difficulty (Ascending)")
print("5. Sort by Difficulty (Descending)")
print("6. Exit")
choice = input("Enter choice: ")
if choice == "1":
show_leaderboard(leaderboard)
elif choice == "2":
show_leaderboard(sort_by_attempts(leaderboard))
elif choice == "3":
show_leaderboard(sort_by_attempts(leaderboard, True))
elif choice == "4":
show_leaderboard(sort_by_difficulty(leaderboard))
elif choice == "5":
show_leaderboard(sort_by_difficulty(leaderboard, True))
elif choice == "6":
break
else:
print("Invalid choice!")`
OUTPUT:
--- Leaderboard ---
Alice | Easy | Attempts: 3
David | Easy | Attempts: 2
Charlie | Medium | Attempts: 5
Bob | Hard | Attempts: 7
EXPLANATION:
The leaderboard is stored as a list of dictionaries, where each player has name, difficulty, and attempts.
The leaderboard is displayed using a loop.
Sorting is done using the sorted() function with a lambda function.
-Attempts are sorted directly since they are numbers.
Difficulty is sorted using a custom order (Easy < Medium < Hard).
A menu allows the user to choose how to view or sort the leaderboard.
Top comments (0)