Python3:如何让小球路径每行生成全新独立序列而非累加?
Fix: Generate Independent Ball Paths per Line
Got it, let's sort out this issue! The problem with your current code is that the path list is defined globally—every time you call BallPath(), you're adding more elements to the same list instead of creating a brand new one for each line. That's why each row ends up being an accumulation of all previous paths.
Here's the modified code that generates independent paths for each line:
import random number_of_balls = int(input("Enter number of balls: ")) number_of_slots = int(input("Enter number of slots: ")) direction = ["L", "R"] def BallPath(): # Create a fresh empty list for each path (no more global accumulation!) path = [] # Generate a full path for the current line for _ in range(number_of_balls): # Pick a random direction directly (cleaner than randint) path.append(random.choice(direction)) # Print the complete path for this line print(' '.join(path)) # Generate the requested number of independent paths for _ in range(number_of_slots): BallPath()
Key changes made:
- Moved
pathinside theBallPathfunction: Now every time you call the function, it creates a new empty list, so each line's path is totally separate from the others. - Simplified direction selection: Used
random.choice(direction)instead of calculating an index withrandint—it does the same thing but is more readable. - Cleaned up print logic: Replaced the loop over
pathwith' '.join(path)to print the entire path in one line, which is more efficient and concise. - Removed unused variables: Got rid of the
slotslist and unnecessaryivariable since they weren't being used in the logic.
Example Output:
If you input 3 for number of balls and 2 for number of slots, you'll get something like:
L R L
R R L
Each line is a completely independent sequence of directions, no more accumulation!
内容的提问来源于stack exchange,提问作者Ashley Raymond
相关产品推荐
相关产品推荐

