[英]Algorithm for distributing a number between certain number of chunks
I am looking for an algorithm to split up a number between a certain number of the chunk. 我正在寻找一种算法,用于在一定数量的块之间拆分数字。 The real example is: assigning initial capacity to all the workers based on the total number of tasks. 真正的例子是:根据任务总数为所有工作人员分配初始能力。
eg If there are 3 persons and 6 tasks. 例如,如果有3个人和6个任务。 Each will have an initial capacity = 6 / 3 = 2
每个将具有初始容量= 6 / 3 = 2
I come up with an implementation. 我想出一个实现。 But, I am not sure it is an optimal way to achieve it. 但是,我不确定这是否是实现它的最佳方法。
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))
Output : 输出:
[3, 3]
[2, 2, 3]
[3, 4, 4]
[3, 3, 4, 4, 4]
Is there any other efficient way for this one? 还有其他有效的方法吗?
Maybe: 也许:
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
How about this? 这个怎么样?
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
My solution would be: 我的解决方案是:
def cap_distr(ts, ps):
l = [ts // ps for _ in range(ps)]
for i in range(ts % ps):
l[i] += 1
return l
test: 测试:
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: if you don't mind importing numpy, it would be even one line shorter: PS:如果您不介意导入numpy,它甚至会短一行:
from numpy import ones
def cap_distr(ts, ps):
arr = ones(ps) * (ts // ps)
arr[:ts % ps] += 1
return arr.astype(int)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.