itertools permutations and combinations

Viewed 695

I am struggling with using itertools permutations and combinations together. Ultimately, I am trying to create a matrix of possible combinations of Customers across various permutations of machines. I believe I have the combinations piece, but have not been able to add permutations to the script.

Here's my code so far:

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

Ideally, I would like to solve all possible outputs of:

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

Any help or direction would be appreciated.

Update: Forgive my ignorance, using Product is not necessarily providing the results that I was driving towards. What am I trying to do is create a list of Customers on Machines, with each Customer only reflected on one machine (at a time), and then iteratively creating another matrix of this combination; for all possible combinations. I believe this is a combination, not a permutation problem, as for the output, I do consider 1: 1, 2, 3 and 1: 3, 2, 1 to be the same.

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

Followed by (as an example): (Cust1, Mach1); (Cust2, Mach2); (Cust3, Mach2); (Cust4, Mach2); (Cust5, Mach2); (Cust6, Mach3); (Cust7, Mach3); (Cust8, Mach3); (Cust9, Mach3); (Cust10, Mach4); (Cust11, Mach4); (Cust12, Mach4)

etc...

2 Answers

Neither product nor combinations is really what you want. You want to pair each item of Mach with a set of items from Cust.

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

Here is a recursive solution which uses itertools.combination. The idea is to choose the combination for the first machine and then recursively generate combinations for the remaining customers and machines.

This solution was developped in Python3, but should work for Python2.

Code

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

Example

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

for comb in groups:
    print(comb)

Output

{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)}
Related