在一定数量的块之间分配数字的算法

时间:2018-05-18 05:17:40

标签: python

我正在寻找一种算法来分割一定数量的块之间的数字。 真实的例子是:根据任务总数为所有工人分配初始容量。

例如,如果有3个人和6个任务。每个人都有初始容量          = 6 / 3 = 2

我想出了一个实现。但是,我不确定它是实现它的最佳方式。

def capacity_distribution(task_size, people_size):
    """
    It distributes initial capacity to each person.
    """
    div = task_size // people_size

    remainder = task_size % people_size

    first_chunk_size = people_size - remainder
    second_chunk_size = people_size - first_chunk_size

    first_capacity_list = []
    second_capacity_list = []
    first_capacity_list = [div for _ in range(first_chunk_size)]
    second_capacity_list = [div + 1 for _ in range(second_chunk_size)]
    first_capacity_list.extend(second_capacity_list)

    return first_capacity_list



print(capacity_distribution(6, 2))
print(capacity_distribution(7, 3))
print(capacity_distribution(11, 3))
print(capacity_distribution(18, 5))

输出:

[3, 3]
[2, 2, 3]
[3, 4, 4]
[3, 3, 4, 4, 4]

这个还有其他有效方法吗?

3 个答案:

答案 0 :(得分:0)

也许:

def capacity_distribution(task_size, people_size):
    each = math.floor(task_size/people_size) # everyone gets this many
    extra = task_size % people_size # this many get 1 extra

    distribution = [each for x in range(people_size)]
    for x in range(people_size):
        if x < extra:
            distribution[x] += 1

    return distribution

答案 1 :(得分:0)

这个怎么样?

def capacity_distribution(task_size, people_size):
    modulus = task_size % people_size
    div = task_size // people_size

    dist = []

    if modulus:
        dist.append(div)
        dist.extend(capacity_distribution(task_size-div, people_size-1))
    else:
        dist.extend([div]*people_size)

    return dist

答案 2 :(得分:0)

我的解决方案是:

def cap_distr(ts, ps):
    l = [ts // ps for _ in range(ps)]
    for i in range(ts % ps):
        l[i] += 1
    return l

试验:

for test in [(6, 2), (7, 3), (11, 3), (18, 5)]: print(cap_distr(*test))
[3, 3]
[3, 2, 2]
[4, 4, 3]
[4, 4, 4, 3, 3]

PS:如果你不介意导入numpy,它甚至会缩短一行:

from numpy import ones

def cap_distr(ts, ps):
    arr = ones(ps) * (ts // ps)
    arr[:ts % ps] += 1
    return arr.astype(int)