如何获取解题过程中的分数?如何每10分钟采集分数用于报告?
Hey there! Let's tackle your two questions with practical, actionable solutions—whether you're working on a custom system or integrating with an existing platform:
The approach depends on where your score data lives, so let's break down common scenarios:
自研系统(自己开发的解题平台)
If scores are stored in a database or memory cache, you can directly query them. For example:- SQL query to pull the latest score for a user and problem:
SELECT score FROM problem_solving_records WHERE user_id = 'your_target_user' AND problem_id = 'target_problem' ORDER BY update_time DESC LIMIT 1; - For real-time score updates (e.g., points added as the user completes steps), use event listeners or WebSockets to get live updates. Here's a quick frontend WebSocket example:
const scoreSocket = new WebSocket('ws://your-server.com/real-time-scores'); scoreSocket.onmessage = (event) => { const { currentScore, step } = JSON.parse(event.data); console.log(`完成步骤 ${step},当前分数: ${currentScore}`); // Render the score to your UI or store it locally };
- SQL query to pull the latest score for a user and problem:
第三方解题平台
Check if the platform provides an API for score queries. Most services expose endpoints like/api/v1/users/{userId}/problems/{problemId}/score—send a GET/POST request to this endpoint, then extract thescorefield from the JSON response.
To build this, you'll need three core parts: scheduled data collection, storage, and report generation.
Step 1: Set up scheduled score collection
Backend-based scheduling is far more reliable than frontend (since browser tabs can be throttled or closed). Here are examples for common tech stacks:
Python with
schedulelibraryimport schedule import time import sqlite3 def collect_and_store_score(): # Fetch latest score (reuse the query from question 1) conn = sqlite3.connect('your_database.db') cursor = conn.cursor() cursor.execute(""" SELECT score FROM problem_solving_records WHERE user_id = 'target_user' AND problem_id = 'target_problem' ORDER BY update_time DESC LIMIT 1 """) latest_score = cursor.fetchone()[0] # Save collected data to a report table cursor.execute(""" INSERT INTO score_reports (user_id, problem_id, score, collect_time) VALUES (?, ?, ?, datetime('now')) """, ('target_user', 'target_problem', latest_score)) conn.commit() conn.close() print(f"Collected score: {latest_score} at {time.strftime('%Y-%m-%d %H:%M:%S')}") # Run every 10 minutes schedule.every(10).minutes.do(collect_and_store_score) # Keep the scheduler running while True: schedule.run_pending() time.sleep(1)Node.js with
node-scheduleconst schedule = require('node-schedule'); const { Pool } = require('pg'); // Using PostgreSQL as example const pool = new Pool({ /* your DB config */ }); const collectScore = async () => { // Fetch latest score const scoreResult = await pool.query(` SELECT score FROM problem_solving_records WHERE user_id = $1 AND problem_id = $2 ORDER BY update_time DESC LIMIT 1 `, ['target_user', 'target_problem']); const latestScore = scoreResult.rows[0].score; // Save to report table await pool.query(` INSERT INTO score_reports (user_id, problem_id, score, collect_time) VALUES ($1, $2, $3, NOW()) `, ['target_user', 'target_problem', latestScore]); console.log(`Collected score: ${latestScore} at ${new Date().toISOString()}`); }; // Schedule every 10 minutes schedule.scheduleJob('*/10 * * * *', collectScore);
Step 2: Generate a score change report
Once you have enough collected data, you can build visual or tabular reports. For example, using Python to create a line chart:
import pandas as pd import matplotlib.pyplot as plt import sqlite3 def generate_score_trend_report(): conn = sqlite3.connect('your_database.db') # Pull all collected scores for the target user/problem df = pd.read_sql_query(""" SELECT collect_time, score FROM score_reports WHERE user_id = 'target_user' AND problem_id = 'target_problem' ORDER BY collect_time """, conn) conn.close() # Create a line chart plt.figure(figsize=(12, 6)) plt.plot(df['collect_time'], df['score'], marker='o', linestyle='-', color='#2563eb') plt.title('Problem Solving Score Trend Over Time') plt.xlabel('Collection Time') plt.ylabel('Score') plt.xticks(rotation=45) plt.tight_layout() plt.savefig('score_trend_report.png') print("Score trend report generated: score_trend_report.png") # Run this function manually or schedule it daily generate_score_trend_report()
内容的提问来源于stack exchange,提问作者Kent Zhang

