如何提升random.randint()随机性?解决数学题重复出现问题
random.randint() Hey Zach, awesome work building your first program—starting with dice rolls and expanding to math challenges is such a cool way to learn Python! Let’s fix that duplicate problem you’re running into.
First off, the issue isn’t that random.randint() lacks randomness—it’s doing exactly what it’s supposed to: picking a random number from your range (1-5) every time. But with only 5 possible problems, random chance means you’ll occasionally get repeats. The fix isn’t "improving" the randomness—it’s controlling which problems get selected so you don’t repeat them until you want to.
Solution 1: No Repeats Until All Problems Are Used
If you want to cycle through all 5 problems without repeating, then reset once they’re all used, you can track available problems with a list:
- Initialize a list of available problem IDs at the start of your program:
import random # Keep track of which problems haven't been used yet available_problems = ['1', '2', '3', '4', '5']
- When you need to call a math problem, pick a random item from the list, remove it, and pass it to your function. If the list is empty, reset it:
elif guess > rand: print('HALT! YOU MAY PROCEED ONLY IF YOU...') # Reset the list if all problems have been used if not available_problems: available_problems = ['1', '2', '3', '4', '5'] # Pick a random unused problem oof = random.choice(available_problems) available_problems.remove(oof) # Call your math problem function mathproblem(oof)
This way, you’ll never get a repeat until every problem has been shown once, then it starts over.
Solution 2: Avoid Immediate Repeats
If you don’t mind repeats eventually but just don’t want the same problem to show up back-to-back, you can track the last problem used and re-generate if there’s a match:
- Add a variable to track the last problem ID outside your loop:
last_problem = None
- When generating a new problem, check if it’s the same as the last one, and keep generating until it’s different:
elif guess > rand: print('HALT! YOU MAY PROCEED ONLY IF YOU...') # Generate a random problem ID (convert to string to match your function's input) oof_str = str(random.randint(1, 5)) # Make sure it's not the same as the last one while oof_str == last_problem: oof_str = str(random.randint(1, 5)) last_problem = oof_str mathproblem(oof_str)
This lets repeats happen eventually but prevents the annoying "same question twice in a row" scenario.
Bonus: Clean Up Your mathproblem Function
While we’re at it, you can make your math problem function way easier to maintain by using a dictionary instead of a long chain of if/elif statements. This makes adding new problems a breeze:
def mathproblem(stuff): # Store all problems in a dictionary for easy access problem_data = { '1': { 'question': 'sqrt(169)+4', 'answer': 17, 'correct_msg': 'correct you may proceed', 'wrong_msg': '' }, '2': { 'question': '47.9+36-14.8', 'answer': 69.1, 'correct_msg': 'YEEEET', 'wrong_msg': 'you filthy wanker' }, '3': { 'question': '32^2 -sqrt(625)', 'answer': 399, 'correct_msg': 'WOOOO', 'wrong_msg': 'Wow... that was awful' }, '4': { 'question': 'ln(1)-e^0', 'answer': -1, 'correct_msg': 'MISSION ACCOMPLISHED', 'wrong_msg': 'your parents probably hate you' }, '5': { 'question': 'sqrt(-1)', 'answer': 'i', 'correct_msg': 'wow you must be a genius', 'wrong_msg': 'L' } } # Get the problem details prob = problem_data[stuff] user_input = raw_input(f"can you solve: {prob['question']}") # Handle different answer types (numbers vs strings) try: # Convert input to number if possible if '.' in user_input: user_answer = float(user_input) else: user_answer = int(user_input) except ValueError: # If conversion fails, keep it as a string (for 'i' in problem 5) user_answer = user_input.strip() # Check answer and return result if user_answer == prob['answer']: print(prob['correct_msg']) return True else: if prob['wrong_msg']: print(prob['wrong_msg']) return False
Now you can add a new problem by just adding a new key-value pair to the problem_data dictionary—no more writing extra elif blocks!
内容的提问来源于stack exchange,提问作者Zach Lederman

