比方说,我想将多个项目(n)分配到固定大小(x)的数组中。 困难的部分是我必须使用灵活性数组来分发项目。
假设x = 4
,n = 11
和flexibility = [20, 20, 30, 30]
与len(flexibility) == x
一起。
我的问题是: 如何使用f中定义的百分比将n个元素分布在长度等于x的数组中?
最后我想要的是这样的
n = 11
x = 4
flexibility = [20, 20, 30, 30]
distributed = distribute_elements_in_slots(n, x, flexibility)
print(distributed)
# distributed = [2, 2, 3, 4]
在弹性值相等的情况下,最终结果将取决于我们决定应用所有项目的规则。在前一种情况下,使用[2,2,3,4]和[2,2,4,3]最终结果会很好。
编辑:我想要的方法示例如下:
def distribute_elements_in_slots(n, x, flexibility=[25,25,25,25]):
element_in_slots = []
element_per_percentage = x / 100
for i in range(x):
element_in_slots.append(round(slots_per_point_percentage * flexibility[i])
编辑2 :我找到的解决方案之一是:
def distribute_elements_in_slots(n, x, flexibility=[25,25,25,25]):
element_in_slots = [f * n / 100 for f in flexibility]
carry = 0
for i in range(len(element_in_slots)):
element = element_in_slots[i] + carry
element_in_slot[i] = floor(element)
carry = element- floor(element)
if np.sum(element_in_slots) < n:
# Here the carry is almost 1
max_index = element_in_slots.index(max(flexibiliyt))
appointments_per_slot[max_index] = appointments_per_slot[max_index] + 1
这将根据灵活性阵列几乎均匀地分配插槽。
答案 0 :(得分:1)
您需要做的是根据数组中给定的百分比对数字11进行分割,因此最初它变为percentage * number(11)
。然后我们得到余数,然后将其分配到您认为是最后一个元素的某个位置。
In [10]: [i*n/100 for i in f]
Out[10]: [2.2, 2.2, 3.3, 3.3]
In [11]: b=[i*n/100 for i in f]
In [12]: rem = sum(b) - sum(map(int,b))
In [13]: rem
Out[13]: 1.0
In [24]: b= list(map(int,b))
In [26]: b[-1] +=rem
In [27]: b
Out[27]: [2, 2, 3, 4.0]
希望有帮助。 :)
答案 1 :(得分:1)
就像阿尔宾·保罗(Albin Paul)一样,我们需要为每个老虎机百分比分配整数数量。剩余的食物需要分配,首先要分配最大的食物。
def distribute_elements_in_slots(total, slots, pct):
# Compute proportional distribution by given percentages.
distr = [total * pct[i] / 100 for i in range(slots)]
# Truncate each position and store the difference in a new list.
solid = [int(elem) for elem in distr]
short = [distr[i] - solid[i] for i in range(slots)]
print(distr)
print(solid)
print(short)
# allocate leftovers
leftover = int(round(sum(short)))
print(leftover)
# For each unallocated item,
# find the neediest slot, and put an extra there.
for i in range(leftover):
shortest = short.index(max(short))
solid[shortest] += 1
short[shortest] = 0
print("Added 1 to slot", shortest)
return solid
n = 11
x = 4
flexibility = [20, 20, 30, 30]
distributed = distribute_elements_in_slots(n, x, flexibility)
print(distributed)
# distributed = [2, 2, 3, 4]
输出:
[2.2, 2.2, 3.3, 3.3]
[2, 2, 3, 3]
[0.2, 0.2, 0.3, 0.3]
1
Added 1 to slot 2
[2, 2, 4, 3]