用于将数字划分为(几乎)相等的整数的算法 [英] Algo for dividing a number into (almost) equal whole numbers
问题描述
我遇到的情况是,我收到的发票电子表格中包含跨越多个月的单行,而数量列包含包含所有跨越月份的数量之和的数量列.
I have a situation where I have invoice spreadsheets incoming with single rows that span multiple months with a quantity column containing the summation of the quantity for all months spanned.
为了进行逐月分析,我们需要在n行中将总数量分成相等的数量,其中n是跨月数.
In order to run month-by-month analytics, we need to split the total quantity into equal(ish) quantities across n rows where n is the number of months spanned.
这些数字可以相差一两个,但是每个元素之间的差异越小越好.
These numbers can be off by one or two, but the smaller the difference between each element the better.
我在python中做了一个粗略的模型,但是我觉得有一种更好的方式可以做到这一点.注意:请原谅...一切:
I have a rough mockup I did in python but I feel there's a better way to do this somehow. Note: Please excuse... everything:
from __future__ import division
import math
def evenDivide(num, div):
splits = []
sNum = str(num/div)
remainder = float(sNum[sNum.index('.'):])
#print "Remainder is " + str(remainder)
integer = math.floor(num/div)
#print "Integer is " + str(integer)
totRemainder = round(remainder * div, 2)
#print "Total Remainder is " + str(totRemainder)
for index in range(div):
if (totRemainder > 0):
totRemainder -= 1 if (index%2 == 0) else 0
if (index % 2 == 0):
splits.append(int(integer + 1))
else:
splits.append(int(integer))
else:
splits.append(int(integer))
for index in range(div):
if(totRemainder > 0):
if (index % 2 == 1):
splits[index] += 1
totRemainder -= 1
return splits
def EvalSolution(splits):
total = 0
for index in range(len(splits)):
total += splits[index]
return total
def testEvenDivide():
for index in range(20000):
for jndex in range(3, 200):
if (EvalSolution(evenDivide(index, jndex)) != index):
print "Error for " + str(index) + ", " + str(jndex)
推荐答案
如果空间不足,那么这种单线可能会有所帮助:
If space is an issue, this one-liner may help:
num, div = 15, 4
print ([num // div + (1 if x < num % div else 0) for x in range (div)])
# result: [4, 4, 4, 3]
这篇关于用于将数字划分为(几乎)相等的整数的算法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!