Skip to content

Commit

Permalink
Added Leetcode Coding Question Bot
Browse files Browse the repository at this point in the history
  • Loading branch information
SarthVader2004 committed Oct 27, 2024
1 parent 16a55c6 commit a318fe9
Show file tree
Hide file tree
Showing 2 changed files with 71 additions and 0 deletions.
16 changes: 16 additions & 0 deletions coding_Q_bot/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
# LeetCode Random Problem Link Generator

This Python script retrieves a random coding problem link from LeetCode using the LeetCode GraphQL API. You can specify a difficulty level (easy, medium, or hard) to get a problem link suited to your preference.

## Features

- Fetches a random problem from LeetCode’s problem set.
- Allows difficulty selection: easy, medium, or hard.
- Generates a clickable link to the selected LeetCode problem.

## Prerequisites

Ensure you have Python installed. This script also requires the `requests` library. Install it via pip:

```bash
pip install requests
55 changes: 55 additions & 0 deletions coding_Q_bot/coding_question_bot.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import requests
import random

# LeetCode GraphQL endpoint
API_URL = "https://leetcode.com/graphql"
# Query to get problems by difficulty
QUERY = """
query getRandomProblem($difficulty: String!) {
problemsetQuestionList(
categorySlug: "algorithms"
filters: { difficulty: $difficulty }
limit: 50
skip: 0
) {
questions {
title
titleSlug
difficulty
}
}
}
"""

# Headers to mimic a browser request
HEADERS = {
"Content-Type": "application/json",
"Referer": "https://leetcode.com/problemset/all/",
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36"
}

def get_random_problem_link(difficulty):
"""Fetches a random problem link from LeetCode by difficulty."""
response = requests.post(API_URL, json={"query": QUERY, "variables": {"difficulty": difficulty}}, headers=HEADERS)

if response.status_code != 200:
return f"Failed to fetch problems (status code: {response.status_code})"

questions = response.json().get("data", {}).get("problemsetQuestionList", {}).get("questions", [])
if not questions:
return "No problems found for the given difficulty."

# Select a random problem
random_problem = random.choice(questions)
problem_title = random_problem.get("title")
problem_slug = random_problem.get("titleSlug")

# Return problem title and link
return f"{problem_title}: https://leetcode.com/problems/{problem_slug}"

if __name__ == "__main__":
# Example usage with random difficulty level
difficulties = ["EASY", "MEDIUM", "HARD"]
selected_difficulty = random.choice(difficulties)
print(f"Fetching a random {selected_difficulty} problem...")
print(get_random_problem_link(selected_difficulty))

0 comments on commit a318fe9

Please sign in to comment.