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
student1instead ofstudenti,questionsinstead ofquestions1— 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.choiceon 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 pickskunique elements from a list without replacement, so no duplicates per student.withstatements: These automatically close your files after use, avoiding resource leaks and the need for manualclose()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
NameErrorexceptions.
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
相关产品推荐
相关产品推荐

