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

如何自动实现嵌套循环以生成mⁿ行的全唯一组合表格?

Generate All State Combinations for Any m and n (No Manual Nested Loops)

Manually writing nested loops works for fixed values of n, but it's tedious to adjust the code every time n changes. Instead, we can leverage Python's built-in tools or a custom iterative approach to create a fully flexible solution. Here's how to do it:

Using itertools.product (Simplest Approach)

Python's itertools.product is designed specifically to generate Cartesian products—exactly what we need for all possible state combinations. It eliminates the need for any manual loop nesting.

Solution Code

import itertools

def generate_state_combinations(m, n):
    # Generate all n-length tuples of values from 1 to m
    all_combinations = itertools.product(range(1, m + 1), repeat=n)
    # Print each combination as a space-separated string
    for combo in all_combinations:
        print(' '.join(map(str, combo)))

# Test with your examples
print("=== m=2, n=3 ===")
generate_state_combinations(2, 3)

print("\n=== m=2, n=4 ===")
generate_state_combinations(2, 4)

How It Works

  • itertools.product(range(1, m+1), repeat=n) creates every possible tuple of length n where each element is between 1 and m (matching your original output's 1-based numbering).
  • We convert each tuple to a space-separated string for printing, just like your manual loop examples.
  • If you need to store the combinations instead of printing them, convert the product object to a list: list(itertools.product(...)).

Verified Output

For m=2, n=3, the output will match your example exactly:

1 1 1
1 1 2
1 2 1
1 2 2
2 1 1
2 1 2
2 2 1
2 2 2

Bonus: No External Libraries (Custom Iterative Approach)

If you can't use itertools, you can build combinations incrementally without recursion:

def generate_state_combinations(m, n):
    # Start with all 1-length combinations
    combinations = [[num] for num in range(1, m + 1)]
    
    # Build up to n-length combinations
    for _ in range(n - 1):
        new_combos = []
        for combo in combinations:
            for num in range(1, m + 1):
                new_combos.append(combo + [num])
        combinations = new_combos
    
    # Print each combination
    for combo in combinations:
        print(' '.join(map(str, combo)))

This works by starting with single-element lists, then repeatedly appending each possible value to existing combinations until we reach the desired length n.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 09:00:25