如果我需要将例如 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 - 将数分成随机数的随机元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10305292/