1

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).

Joshua Gilman
  • 1,174
  • 4
  • 16
  • 32

3 Answers3

3

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
Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91
1

This is a slight modification of Andrej's answer which I think is a little more readable:

from itertools import cycle

pools = ['pool1', 'pool2']
children = ['child1', 'child2', 'child3']

for child, pool in zip(children, cycle(pools)):
    print(f'{child} assigned to {pool}')

Outputs:

child1 assigned to pool1
child2 assigned to pool2
child3 assigned to pool1
shmulvad
  • 636
  • 4
  • 15
0

You can do it like so :

for elem in children:
    if children.index(elem) % 2 == 0:
        print(f"{elem} to {pools[0]}")
    else:
        print(f"{elem} to {pools[1]}")

Considering you only have two pools you can assign the children to the pool1 if his index is an odd number.

Tom Planche
  • 116
  • 11