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

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 path inside the BallPath function: 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 with randint—it does the same thing but is more readable.
  • Cleaned up print logic: Replaced the loop over path with ' '.join(path) to print the entire path in one line, which is more efficient and concise.
  • Removed unused variables: Got rid of the slots list and unnecessary i variable 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 10:09:26