DEV Community

Lokeshwaran S
Lokeshwaran S

Posted on

Number Guessing Game - CA03

Objective

  1. Retrieve leaderboard records from the database
  2. Arrange records based on difficulty level and number of attempts

Data Structure

Each record in the leaderboard contains:

  • Name
  • Difficulty level
  • Attempts count

Approach

  1. Collect all leaderboard entries
  2. Convert difficulty levels into comparable values
  3. 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]
Enter fullscreen mode Exit fullscreen mode

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.
Enter fullscreen mode Exit fullscreen mode

Top comments (0)