【问题标题】:itertools permutations and combinationsitertools 排列组合
【发布时间】:2018-10-29 19:11:52
【问题描述】:

我正在努力同时使用 itertools 排列和组合。最终,我试图在各种机器排列中创建一个可能的客户组合矩阵。我相信我有组合片段,但无法在脚本中添加排列。

到目前为止,这是我的代码:

import itertools

Mach = [1,2,3,4]
Cust = [1,2,3,4,5,6,7,8,9,10,11,12]

a = len(Cust)

for n in range(a):
    print list(itertools.combinations(Cust,n))
    n = n+1

理想情况下,我想解决以下所有可能的输出:

1 - 1,2,3
2 - 4,5,6
3 - 7,8,9
4 - 10,11,12

任何帮助或指导将不胜感激。

更新: 原谅我的无知,使用 Product 并不一定能提供我所追求的结果。我想做的是在机器上创建一个客户列表,每个客户(一次)只反映在一台机器上,然后迭代地创建这个组合的另一个矩阵;对于所有可能的组合。我相信这是一个组合,而不是一个排列问题,至于输出,我确实认为 1: 1, 2, 3 和 1: 3, 2, 1 是相同的。

示例: (Cust1, Mach1); (Cust2, Mach1); (Cust3, Mach2); (Cust4,Mach2); (Cust5,Mach2); (Cust6, Mach3); (Cust7,Mach3); (Cust8, Mach3); (Cust9, Mach3); (Cust10, Mach3); (Cust11,Mach4); (Cust12, Mach4)

后跟(例如): (Cust1, Mach1); (Cust2, Mach2); (Cust3, Mach2); (Cust4,Mach2); (Cust5,Mach2); (Cust6, Mach3); (Cust7,Mach3); (Cust8, Mach3); (Cust9, Mach3); (Cust10, Mach4); (Cust11,Mach4); (Cust12, Mach4)

等等……

【问题讨论】:

  • 注意,n = n+1 绝对没有用处
  • 你好像想要itertools.product(Mach, Cust)
  • 您的预期结果是什么?或者您可能期望结果看起来像什么......输出表或其他东西?
  • Dave,我的预期结果是各个机器上各种客户的所有可能组合,然后我可以将特定要求映射到机器约束以进行分析以获得最佳拟合。我的想法更像是一种蛮力优化浪费的方法(由机器定边器的整体利用率定义)。
  • 我认为这些是一样的。

标签: python python-2.7 itertools


【解决方案1】:

productcombinations 都不是您真正想要的。您想将Mach 中的每一项与Cust 中的一组 项配对。

n = len(cust)/len(m)
for i, m in enumerate(mach):
    print(m, cust[n*i: n*(i+1)])

【讨论】:

  • 感谢您的指导和见解。以下是我一直在寻找的最终结果:
  • import itertools Mach = [1,2,3,4] Cust = [1,2,3,4,5,6,7,8,9,10,11,12] a = len(Cust) for n in range(a): print list(itertools.product(Mach,itertools.combinations(Cust,n)))
【解决方案2】:

这是一个使用itertools.combination 的递归解决方案。这个想法是为第一台机器选择组合,然后为剩余的客户和机器递归生成组合。

此解决方案是在 Python3 中开发的,但应该适用于 Python2。

代码

import itertools

def group_combinations(machines, customers):
    if not machines:
        yield {}
    else:
        for group in itertools.combinations(customers, len(customers) // len(machines)):
            remaining = [c for c in customers if c not in group]
            for others in group_combinations(machines[1:], remaining):
                arrangement = {machines[0]: group}
                arrangement.update(others)
                yield arrangement

示例

machines = [1, 2]
customers = [1, 2, 3, 4]
groups = group_combinations(machines, customers)

for comb in groups:
    print(comb)

输出

{1: (1, 2), 2: (3, 4)}
{1: (1, 3), 2: (2, 4)}
{1: (1, 4), 2: (2, 3)}
{1: (2, 3), 2: (1, 4)}
{1: (2, 4), 2: (1, 3)}
{1: (3, 4), 2: (1, 2)}

【讨论】:

    猜你喜欢
    • 2018-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-27
    相关资源
    最近更新 更多