【问题标题】:Calculate permutations计算排列
【发布时间】:2014-12-14 14:18:31
【问题描述】:

假设我有一个元组:

my_tuple = ((1,2), 10)

还有一本字典:

diction = {1:(1,2,3,4,5,6,7,8,9), 2:(1,2,3,4,5,6,7,8,9), 3:(1,2,3,4,5,6,7,8,9)}

元组的第一个元素表示一些变量,每个变量都可以赋值为 1,...,9(根据字典)。

如何计算这些变量的所有排列(不重复)。 我唯一的限制是我希望我的变量的值总和为 10。

例如:

(var1) = 9
(var2) = 1

所以 (9,1) 的和为 10,是一个有效的排列。

我试过的是:

lst = []

first_var = my_tuple[0][0]
sec_var = my_tuple[0][1]

for i in diction[first_var]:
    for j in diction[sec_var]:
        if i != j:
            if (i + j) == my_tuple[1]:
                lst.append((i,j))

我的问题是带有变量的元组并不总是相同的大小(在这种情况下为 2)。它可能有 3 或 4 个变量,所以上面的循环不起作用。

有什么方法可以计算更一般情况下的排列吗?例如,((1,2,3), 20)?

【问题讨论】:

  • 是否应该使用与元组中的键对应的每个字典值中的一个值?
  • 您可以为您的示例添加示例输出吗?
  • 对于元组 = ((1,2,3), 20),有效的排列是 (8,9,3)。问题是我的循环仅适用于 2 个变量。
  • @prokiz 你为什么要检查i != j? 5 + 5 也是 10,对吧?
  • 我想要没有重复的排列。 :]

标签: python algorithm python-2.7 permutation


【解决方案1】:

使用迭代器:

def solve(d, target, total, keys, avoid):
  if total <= target:     # omit this check if values can be negative
    if keys:
      k = keys[0]
      for v in d[k]:
        if not (v in avoid):
          for s in solve(d, target, total+v, keys[1:], avoid.union([v]) ):
            yield s + [(k,v)]
    elif target == total:
      yield []

def test1():
  d = {'a':(1,2,3), 'b':(4,5), 'c':(1,3,5) }
  for s in solve(d, 10, 0, "abc", set([])):
    print s

def test2():
  d = {'a':(1,2,3), 'b':(1,2,3), 'c':(1,2,3) }
  for s in solve(d, 6, 0, "abc", set([])):
    print s

test1 的输出:

[('c', 5), ('b', 4), ('a', 1)]
[('c', 3), ('b', 5), ('a', 2)]

test2 的输出:

[('c', 3), ('b', 2), ('a', 1)]
[('c', 2), ('b', 3), ('a', 1)]
[('c', 3), ('b', 1), ('a', 2)]
[('c', 1), ('b', 3), ('a', 2)]
[('c', 2), ('b', 1), ('a', 3)]
[('c', 1), ('b', 2), ('a', 3)]

【讨论】:

  • 谢谢。无论如何我可以将整数作为键而不是字符串?
  • 同样的代码可以工作。而不是"abc",只需传入一个列表,例如[1,2,3].
猜你喜欢
  • 2021-06-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多