随机列表生成器,增量为5,总计为100%

时间:2019-03-11 10:29:28

标签: python arrays python-3.x

让我们说我有21种产品。可以为产品分配5%的增量。在所有产品中,它们的总和必须为100%。产品上允许分配0%,因此100%也可以。

sample = ['10', '15', '5', '35', '15', '5', '15', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0']

我需要找出百分比分配的每种组合。我尝试过代码,其中有一个数字数组,以5为增量,0-100,只要总计数不超过100,我就拉一个增量。如果它填充数组中的最后一个元素,则填充100 -总计数。

但是,列表末尾的产品没有分配任何东西。我需要每一种可能的组合(或尽可能多的组合),而现在我做的方式要花很长时间,因为我正在创建一个随机数组,然后检查它是否已经存在。有更好的方法吗?

def createUniqueArray():
#Array of numbers in increments of 5 
array_of_nums = [0,5,10,15,20,25,30,35,40,45,50,55,60,65,70,75,80,85,90,95,100]

#Stores sum of 21 numbers needed for array
count_to_hundred = 0

#To store array of 21 numbers
array = []

#Number of products
numProducts = 21

for col in range(numProducts):
    #If not on the last pass
    if col != numProducts:
        #Creating boolean and setting it to false
        suitable_num = False;

        #If already at 100
        if count_to_hundred == 100:
            array.append(0)
        else:
            while suitable_num == False:
                #Find a number between 1 - 20
                value = array_of_nums[random.randint(1,20)]

                if value + count_to_hundred <= 100:
                    #Adding to count
                    count_to_hundred += value
                    #Updating boolean to stop while loop
                    suitable_num = True
                    #Adding value to array
                    array.append(value)          
    else:
        #Getting remaing amount that will add to give 100
        leftOver = 100 - count_to_hundred
        #Add it to array
        array.append(leftOver)
        #Update count
        count_to_hundred = count_to_hundred + leftOver

#Add array to array list
if array not in arrayOfArrays:
    arrayOfArrays.append(array)

0 个答案:

没有答案