【问题标题】:How to generate unto n digit combinations of an integer? [closed]如何生成整数的 n 位组合? [关闭]
【发布时间】:2021-06-25 16:59:44
【问题描述】:

我正在尝试在 python 中创建一个程序,它为给定数字生成所有可能的组合(非重复)

如果输入是“123”,输出应该是

123,132,213,231,312,321

12,13,21,23,31,32

1,2,3

我当前的代码是

    import itertools
    
    a=[1,2,3]
        
    for i in range(1,len(a)+1):
        print(list(itertools.combinations(a,i)))

【问题讨论】:

  • 你已经添加了python标签,但是你没有为你的问题添加代码。
  • 贴出你写的代码。
  • 运行时会打印什么?

标签: python python-3.x combinations permutation


【解决方案1】:

你可以使用itertools.permutations:

import itertools

def permute_all(value):
    return [''.join(permutation) for i in range(len(value)) for permutation in itertools.permutations(value, i+1)]
    
print(permute_all('123'))
# Outputs ['1', '2', '3', '12', '13', '21', '23', '31', '32', '123', '132', '213', '231', '312', '321']

【讨论】:

    【解决方案2】:

    考虑不重复所有可能的组合和输出。

    from itertools import permutations
    N = str(int(input()))
    for length in range(len(N),0,-1):
        currOrder = []
        for order in permutations(N,length):
            comb = ''.join(order)
            if comb not in currOrder:
                currOrder.append(comb)
        print(*currOrder,sep=",")
    
    

    【讨论】:

      猜你喜欢
      • 2015-02-22
      • 1970-01-01
      • 1970-01-01
      • 2023-03-03
      • 2020-10-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多