'Split a list of dicts containing a count value into n nodes such that the nodes have equal or close to equal sums of count

I got a task to write a function in Python that gets a list of company campaigns and Nodes number

And it needs to evenly distribute the workload between the number of nodes

we want to send each node a similar number of campaigns (as possible).

For example

input:

companies = [{campaigns: {campaign1}, count: 20}, {campaigns: {campaign2}, count: 40}, {campaigns: {campaign3}, count: 15}]

nodes = 2
  • The count key represents the number of campaigns of the same type

Expected result:

[{campaigns: [campaign1, campaign3], count: 35}, {campaigns: [campaign2], count: 40}]

how would you split the list into n nodes such that the nodes have equal (or close to) count values (which are the sums of different campaigns count key values) and keep the original order

EDIT:

I tried this and it gives me the right answer if I give it the example I gave as input

import heapq


def split_workloads(campaigns, nodes):
    result = [{'campaigns': [], 'count': 0} for _ in range(nodes)]
    totals = [(0, i) for i in range(nodes)]
    heapq.heapify(totals)
    for campaign in campaigns:
        total, index = heapq.heappop(totals)
        result[index]['campaigns'].append(campaign['campaigns'].pop())
        result[index]['count'] += campaign['count']
        heapq.heappush(totals, (total + campaign['count'], index))
    return result

but if I give it as input:

companies = [
                  {'campaigns': {'campaign1'}, 'count': 3},
                  {'campaigns': {'campaign2'}, 'count': 2},
                  {'campaigns': {'campaign3'}, 'count': 1},
                  {'campaigns': {'campaign4'}, 'count': 6}
                  ]
nodes = 2

I get the wrong output:

[{'campaigns': ['campaign1', 'campaign4'], 'count': 9}, {'campaigns': ['campaign2', 'campaign3'], 'count': 3}]

The correct output should be:

[{'campaigns': ['campaign1','campaign2', 'campaign3'], 'count': 6}, {'campaigns': ['campaign4'], 'count': 6}]


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source