You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python实现为学生分配不重复随机题目的技术问询

Fixing Duplicate Questions in Student Assignment Code

Let's break down why your current code isn't preventing duplicate questions, and fix it up properly:

The main issues with your original code:

  • Variable name typos: You have mismatched names like student1 instead of studenti, questions instead of questions1 — these would actually throw errors before even getting to the duplication problem.
  • Ineffective deduplication logic: Your check for duplicates runs after you've already written all k questions to the file, and only checks the last question you picked. That's way too late to prevent duplicates.
  • Reusing the same question list: Using random.choice on the full list every time means you can easily pick the same question multiple times for one student.

Here's the corrected code:

import random

# Get number of questions per student
k = int(input("How many questions do you want? - "))

# Read all questions and students (using with to auto-close files)
with open("questions.txt", 'r') as questions_file:
    all_questions = [q.strip() for q in questions_file.read().split('\n') if q.strip()]  # Remove empty lines

with open("students.txt", 'r') as students_file:
    all_students = [s.strip() for s in students_file.read().split('\n') if s.strip()]  # Remove empty lines

# Assign unique questions to each student
for student in all_students:
    # Use random.sample to pick k UNIQUE questions from the list
    assigned_questions = random.sample(all_questions, k)
    
    # Write to student's file
    with open(f"{student}.txt", "w") as student_file:
        for question in assigned_questions:
            student_file.write(f"{question}\n")

print("Question assignment completed successfully!")

Key improvements made:

  • random.sample(): This function is designed exactly for this use case — it picks k unique elements from a list without replacement, so no duplicates per student.
  • with statements: These automatically close your files after use, avoiding resource leaks and the need for manual close() calls.
  • Cleaned up input lists: We filter out empty lines from both the questions and students files, so you don't end up creating empty student files or assigning blank questions.
  • Fixed variable name errors: All variable names are consistent now, so you won't get NameError exceptions.

If you need to ensure that different students don't get overlapping question sets (on top of no duplicates per student), let me know — we can adjust the code to handle that too!

内容的提问来源于stack exchange,提问作者user9198426

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 07:48:41