DEV Community

JAYA SRI J
JAYA SRI J

Posted on • Edited on

number guessing game

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

Explanation:
Each entry represents a user.
Data is stored as dictionaries inside a list.
show_leaderboard() prints all records.

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

(B) Descending Order

sorted_data_desc = sorted(
    leaderboard,
    key=lambda x: (difficulty_order[x["difficulty"]], x["attempts"]),
    reverse=True
)
show_leaderboard(sorted_data_desc)
Enter fullscreen mode Exit fullscreen mode

Explanation
lambda function defines sorting logic
First sorted by difficulty, then by attempts
reverse=True gives descending order

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

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)