DEV Community

Tharunya K R
Tharunya K R

Posted on

Fetch and Sort Leaderboard by Difficulty and Attempts

Setup Leaderboard Table

CREATE TABLE leaderboard (
id INT PRIMARY KEY,
username VARCHAR(50),
score INT,
difficulty INT,
attempts INT
);

INSERT INTO leaderboard (id, username, score, difficulty, attempts) VALUES
(1, 'Alice', 80, 3, 2),
(2, 'Bob', 90, 2, 5),
(3, 'Charlie', 85, 1, 1);

Python Code to Fetch Data

import sqlite3
conn = sqlite3.connect("leaderboard.db")
cursor = conn.cursor()
cursor.execute("SELECT id, username, score, difficulty, attempts FROM leaderboard")
data = cursor.fetchall()

print("Original Data:")
for row in data:
print(row)

conn.close()

Output Example:

(1, 'Alice', 80, 3, 2)
(2, 'Bob', 90, 2, 5)
(3, 'Charlie', 85, 1, 1)

** Sort Data**

Sort by Difficulty Ascending

sorted_by_difficulty = sorted(data, key=lambda x: x[3]) # difficulty is index 3
print("\nSorted by Difficulty (ASC):")
for row in sorted_by_difficulty:
print(row)

Output:
(3, 'Charlie', 85, 1, 1)
(2, 'Bob', 90, 2, 5)
(1, 'Alice', 80, 3, 2)

Sort by Attempts Descending

sorted_by_attempts = sorted(data, key=lambda x: x[4], reverse=True) # attempts is index 4
print("\nSorted by Attempts (DESC):")
for row in sorted_by_attempts:
print(row)

Output:
(2, 'Bob', 90, 2, 5)
(1, 'Alice', 80, 3, 2)
(3, 'Charlie', 85, 1, 1)

Top comments (0)