- Fetch Details from Leaderboard Database Concept: First, we need to retrieve data from a database. For simplicity, we simulate a database using a list of dictionaries.
# Simulated leaderboard database
leaderboard = [
{"name": "Alice", "difficulty": "Easy", "attempts": 3},
{"name": "Bob", "difficulty": "Hard", "attempts": 5},
{"name": "Charlie", "difficulty": "Medium", "attempts": 2},
{"name": "David", "difficulty": "Easy", "attempts": 4}
]
# Function to display leaderboard
def show_leaderboard(data):
for user in data:
print(user)
# Show all details
show_leaderboard(leaderboard)
Explanation:
Each entry represents a user.
Data is stored as dictionaries inside a list.
show_leaderboard() prints all records.
- Sorting Based on Difficulty and Attempts
Concept: Use sorted() with a custom key.
Step 1: Define difficulty order
Since difficulty is text, we assign a ranking.
difficulty_order = {"Easy": 1, "Medium": 2, "Hard": 3}
Step 2: Sort Leaderboard
(A) Ascending Order
sorted_data = sorted(
leaderboard,
key=lambda x: (difficulty_order[x["difficulty"]], x["attempts"])
)
show_leaderboard(sorted_data)
(B) Descending Order
sorted_data_desc = sorted(
leaderboard,
key=lambda x: (difficulty_order[x["difficulty"]], x["attempts"]),
reverse=True
)
show_leaderboard(sorted_data_desc)
Explanation
lambda function defines sorting logic
First sorted by difficulty, then by attempts
reverse=True gives descending order
- Optional: User Choice for Sorting
Concept: Make program interactive.
choice = input("Enter sorting order (asc/desc): ").lower()
if choice == "asc":
result = sorted(
leaderboard,
key=lambda x: (difficulty_order[x["difficulty"]], x["attempts"])
)
else:
result = sorted(
leaderboard,
key=lambda x: (difficulty_order[x["difficulty"]], x["attempts"]),
reverse=True
)
show_leaderboard(result)
Explanation:
In a real-world application, users may want to view data in different ways.
Some may prefer:
Ascending order is smaller values first
Descending order is larger values first
To make the leaderboard flexible, we allow the user to choose the sorting order dynamically.
Top comments (0)