My problem involves a bit more complexity, but the issue can be written rather generically with an example: I have a list of pools (pools
) that need to have a list of children (children
) distributed evenly amongst the list of pools
.
The children
list is already sorted, so it's safe to assume it can be distributed over the pools
in the current order.
For example, if I had [pool1, pool2]
and [child1, child2, child3]
I would expect pool1
to be assigned child1
and child3
and pool2
would be assigned child2
:
pools = ['pool1', 'pool2']
children = ['child1', 'child2', 'child3']
def print_assignment(pool, child)
print('{} assigned to {}'.format(child, pool)
# The expectation is that distribute would perform the core logic and
# call print_assignment during each assignment
distribute(pools, children, print_assignment)
With the expected output being:
child1 assigned to pool1
child2 assigned to pool2
child3 assigned to pool1
The expectation is that the count of pools
and children
can be any size, however, the following is always true: len(pools) < len(children)
.
You can use itertools.cycle
for the task:
from itertools import cycle
pools = ['pool1', 'pool2']
children = ['child1', 'child2', 'child3']
c = cycle(pools)
for child in children:
print('{} assigned to {}'.format(child, next(c)))
Prints:
child1 assigned to pool1
child2 assigned to pool2
child3 assigned to pool1