Python 根据百分比分配元素
假设我想将若干项n分配到一个固定大小x的数组中。 困难的部分是我必须使用灵活的数组来分发项目 假设x=4,n=11,弹性=[20,20,30,30],弹性=x 我的问题是: 如何使用f中定义的百分比将n个元素分布在长度等于x的数组中 最后我想要的是:Python 根据百分比分配元素,python,algorithm,Python,Algorithm,假设我想将若干项n分配到一个固定大小x的数组中。 困难的部分是我必须使用灵活的数组来分发项目 假设x=4,n=11,弹性=[20,20,30,30],弹性=x 我的问题是: 如何使用f中定义的百分比将n个元素分布在长度等于x的数组中 最后我想要的是: n = 11 x = 4 flexibility = [20, 20, 30, 30] distributed = distribute_elements_in_slots(n, x, flexibility) print(distributed)
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
这将根据灵活性数组几乎均匀地分配插槽。您需要做的是根据数组中给定的特定百分比分割数字11,使其最初成为百分比*数字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]
希望有帮助 正如阿尔宾·保罗所做的那样,我们需要为每个插槽的百分比分配总数。剩菜需要分配,首先是最大的
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]
你是怎么解决这个问题的,你能提供吗code@DeveshKumarSingh我添加了我的初始错误解决方案。你能解释一下输出[2,2,3,4]吗?正如我所说,这就是我想要的。遵循灵活性的元素的分布。4是因为它可能碰巧有另一个我们想添加的元素。是什么使[2,2,3,4]成为正确答案,而不是[2,3,4,3]?我认为这两种都可以接受?谢谢!这是可行的,但在某些情况下,它会返回错误的结果。例如,如果f=[24,26,26,24]且n=10,它将返回b=[2,2,2,4],而不是b=[2,3,3,2]。@spassador是的,这取决于您在哪里添加余数