【问题标题】:How to get this list of combinations?如何获得此组合列表?
【发布时间】:2018-04-29 16:22:08
【问题描述】:

我有两个数字,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 及其 combinationspermutations 函数,但它们似乎不适合这项任务。

【问题讨论】:

  • 请(两位)反对者解释原因吗?
  • 我认为列表中的数字只能是正数?
  • @Colin 是的,N、L 和列表中的数字只能是正数(否则会有无限可能的列表!)
  • 您尝试了几件事,但它们似乎并不“正确”。为什么不呢?
  • 对于所有关闭/关闭的选民,我不认为这个问题“过于宽泛”,因为要求非常明确且可以理解。

标签: python python-3.x algorithm combinations permutation


【解决方案1】:

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

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]]

【讨论】:

  • 谢谢!我现在试试这个......有没有办法让它更有效率? (因为 N 可以是数百个)
  • @Adi219 是的,有 - 请参阅链接副本上的答案 :)
  • @Adi219 请看我最近的编辑。我添加了一个稍微快一点的方法,以及两种方法的总时间。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-02
  • 1970-01-01
  • 2022-11-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多