我关心的是什么是生成 10 - 15 个数字的列表的好方法,这些数字的总和总是可以被 n 整除。
输出应该是
-8378302799
到目前为止,这是我得到的,但它还不是一个有效的脚本。
import random
import numpy as np
def get_num(x, y, n):
return [random.choice(range(x, y, n)) if x % n != 0 else random.choice(range(x - (x % n) + n, y, n)) for x in x]
def get_list():
numb = get_num(0, 9, 2)
return ''.join(np.random.multinomial(numb, [1/10], size=1))
while True:
amount = int(input("How many Do you want to generate?" + "\n"))
for i in range(1,amount):
get_list()
@Samer Ayoub,答案是我需要的,只是添加了 sep='' 所以它如我所料。
import random
n, m, k= 3, 9, 14
lis = [random.choice(range(0, m)) for i in range(k)]
tot = sum(lis)
print(*lis, sep = '')
while tot%n != 0:
tot -= lis.pop()
last = random.choice(range(0, m))
lis.append(last)
tot += last
最佳答案
也许有点迂腐,但是如果将来阅读本文的人有一个用例,其中概率分布问题很重要,他们应该知道随机选择除最后一个数字以外的所有数字然后选择最后一个数字的算法数字以满足约束,在最后一个数字中引入偏差。作为概念证明:
import random, math
def f(k,a,b):
"""generates k random integers in a,b which sum to an even number"""
start = [random.randint(a,b) for _ in range(k-1)]
if sum(start) % 2 == 0:
#pick an even number
start.append(2*random.randint(math.ceil(a/2),math.floor(b/2)))
else:
#pick an off number
start.append(1 + 2*random.randint(math.ceil((a-1)/2),math.floor((b-1)/2)))
return start
例如,f(3,1,5)
的典型运行产生了 [1, 5, 2]
。
但是:
trials = [f(3,1,5) for _ in range(10000)]
print(sum(trial[0]%2 == 0 for trial in trials)/10000) #percentage of first nums which are even
print(sum(trial[2]%2 == 0 for trial in trials)/10000) #percentage of last nums which are even
典型输出:
0.3996
0.5198
这显示出明显的偏见。
关于python - 生成总和可被 n 整除的随机数列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57954340/