Objective
- Retrieve leaderboard records from the database
- Arrange records based on difficulty level and number of attempts
Data Structure
Each record in the leaderboard contains:
- Name
- Difficulty level
- Attempts count
Approach
- Collect all leaderboard entries
- Convert difficulty levels into comparable values
- Apply sorting logic using both difficulty and attempts
Difficulty Priority
To ensure proper ordering:
- Easy is considered lowest
- Medium is next
- Hard is highest
This helps in comparing difficulty levels during sorting.
Sorting Logic
- Compare two entries
- First check difficulty level
- If difficulty is same, compare attempts
- Swap positions if required
- Repeat until the list is sorted
Code (Python)
```python id="lb32x1"
leaderboard = [
{"name": "Alice", "difficulty": "Medium", "attempts": 5},
{"name": "Bob", "difficulty": "Easy", "attempts": 3},
{"name": "Charlie", "difficulty": "Hard", "attempts": 7},
{"name": "David", "difficulty": "Easy", "attempts": 6}
]
difficulty_rank = {"Easy": 1, "Medium": 2, "Hard": 3}
for i in range(len(leaderboard)):
for j in range(len(leaderboard) - i - 1):
current = leaderboard[j]
next_item = leaderboard[j + 1]
if (difficulty_rank[current["difficulty"]] > difficulty_rank[next_item["difficulty"]]) or \
(difficulty_rank[current["difficulty"]] == difficulty_rank[next_item["difficulty"]] and
current["attempts"] > next_item["attempts"]):
leaderboard[j], leaderboard[j + 1] = leaderboard[j + 1], leaderboard[j]
for item in leaderboard:
print(item)
---
## Explanation
* Leaderboard data is stored using dictionaries
* Difficulty values are mapped to numbers for comparison
* Sorting is done using two conditions
* First by difficulty
* Then by attempts if difficulty is same
* Bubble sort ensures correct ordering step by step
---
## Example
Input:
* Alice, Medium, 5
* Bob, Easy, 3
* Charlie, Hard, 7
* David, Easy, 6
Output:
* Bob, Easy, 3
* David, Easy, 6
* Alice, Medium, 5
* Charlie, Hard, 7
---
## Conclusion
This implementation ensures that leaderboard data is organized clearly based on difficulty and performance. It improves readability and helps users understand rankings effectively.
Top comments (0)