编程语言
首页 > 编程语言> > python – 将数字除以随机元素的随机数?

python – 将数字除以随机元素的随机数?

作者:互联网

如果我需要将例如7除以随机大小的随机数元素,我该怎么做?

所以有时我会[3,4],有时[2,3,1],有时[2,2,1,1,0,1]?

我想这很简单,但我似乎无法得到结果.这是我试图以代码方式做的事情(不起作用):

def split_big_num(num):
    partition = randint(1,int(4))
    piece = randint(1,int(num))
    result = []
    for i in range(partition):
        element = num-piece
        result.append(element)
        piece = randint(0,element)
#What's next?
        if num - piece == 0:
            return result
    return result

编辑:每个结果数应小于初始数,零数应不小于分区数.

解决方法:

我会选择下一个:

>>> def decomposition(i):
        while i > 0:
            n = random.randint(1, i)
            yield n
            i -= n

>>> list(decomposition(7))
[2, 4, 1]
>>> list(decomposition(7))
[2, 1, 3, 1]
>>> list(decomposition(7))
[3, 1, 3]
>>> list(decomposition(7))
[6, 1]
>>> list(decomposition(7))
[5, 1, 1]

但是,我不确定这种随机分布是否完全一致.

标签:python,random,math,integer-division
来源: https://codeday.me/bug/20190712/1444415.html