python - 如何获得这个组合列表?

标签 python python-3.x algorithm combinations permutation

我有两个数字,N 和 L(比如 5 和 3)。

如何生成所有可能的 list,其中列表的总和等于 N (5) 并且每个 list 的长度为 L (3)?

示例输出(在本例中):

[0, 0, 5]
[0, 1, 4]
[0, 2, 3]
[0, 3, 2]
...
[0, 5, 0]
...
[1, 4, 0]
...
[5, 0, 0]

我已经检查了 itertools 及其组合排列 函数,但它们似乎不适合这项任务。

最佳答案

您可以创建一个递归函数来生成具有给定条件的所有可能排列,然后过滤以仅保留总和为所需值的列表:

def list_results(a, b):
   return [i for i in permutations(b) if sum(i) == a]

def permutations(d, current = []):
   if len(current) == d:
     yield current
   else:
     for i in range(10):
        yield from permutations(d, current+[i])

print(list_results(5, 3))

输出:

[[0, 0, 5], [0, 1, 4], [0, 2, 3], [0, 3, 2], [0, 4, 1], [0, 5, 0], [1, 0, 4], [1, 1, 3], [1, 2, 2], [1, 3, 1], [1, 4, 0], [2, 0, 3], [2, 1, 2], [2, 2, 1], [2, 3, 0], [3, 0, 2], [3, 1, 1], [3, 2, 0], [4, 0, 1], [4, 1, 0], [5, 0, 0]]

编辑:稍微快一点需要在递归函数中进行额外检查:

import time
def timeit(f):
   def wrapper(*args, **kwargs):
      c = time.time()
      results = list(f(*args, **kwargs))
      print("Result from function '{}' achieved in {}".format(f.__name__, abs(c-time.time())))
      return results
   return wrapper

@timeit
def outer_permutations():
   def permutations1(d, b, current = []):
     if len(current) == d:
       yield current
     else:
       for i in range(10):
         if len(current) < 2 or sum(current+[i]) == b:
           yield from permutations1(d, b, current+[i])
   yield from permutations1(3, 5)

@timeit
def list_results(a, b):
   return [i for i in permutations(b) if sum(i) == a]


v = outer_permutations()
v1 = list_results(3, 5)

输出:

Result from function 'outer_permutations' achieved in 0.0006079673767089844
Result from function 'list_results' achieved in 0.09148788452148438

请注意,这两个函数的输出是:

[[0, 0, 5], [0, 1, 4], [0, 2, 3], [0, 3, 2], [0, 4, 1], [0, 5, 0], [1, 0, 4], [1, 1, 3], [1, 2, 2], [1, 3, 1], [1, 4, 0], [2, 0, 3], [2, 1, 2], [2, 2, 1], [2, 3, 0], [3, 0, 2], [3, 1, 1], [3, 2, 0], [4, 0, 1], [4, 1, 0], [5, 0, 0]]

关于python - 如何获得这个组合列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50088789/

相关文章:

python - Sin(x)^4 的梯度与导数计算时不同

python - 如何在 Python 3 的 assertRegex 中表达多行正则表达式?

php - 在 PHP 中压缩多维数组?

php - 如何在不解压/重新压缩的情况下连接(连接)两个压缩值

Python:使用循环创建函数

python - 如何在peakutils [python]中设置峰的最大高度

python - Python 中的链接方法

python-3.x - 如何在Python中动态更新cv2窗口标题的FPS

python - 在 Linux 上使用 discord.py 我得到错误 'Bot' object has no attribute 'join_voice_channel'

algorithm - 二叉树中的平衡和