我想在均匀分布中生成[1,4]
范围内的4个随机整数。例如,对于12个元素的序列,每个数字出现3次。
答案 0 :(得分:0)
您可以使用列表执行此任务,以确保您的可用数字池不包含任何重复项。我不确定你是否需要它们出现在12列表中的集合块中,或者你是否希望它完全随机化。如果是前者,请删除最后一次随机播放。
from random import shuffle
choice_pool = [x for x in range(1, 5)]
random_output = []
number_of_runs = 4
for x in range(number_of_runs):
shuffle(choice_pool)
random_output += choice_pool
shuffle(random_output)
print random_output
答案 1 :(得分:0)
这种方法应该有效:
import random
foo = [i for i in range(1, 5)] * 4
print random.sample(foo, len(foo))
输出:[2, 2, 3, 1, 4, 4, 3, 4, 1, 1, 3, 2, 1, 4, 3, 2]
答案 2 :(得分:0)
这可能会帮助你 -
import random
def foo(number_of_runs, lower_limit, upper_limit):
turns = number_of_runs // (upper_limit - lower_limit + 1)
arr = list(range(lower_limit, upper_limit + 1)) * turns
random.shuffle(arr)
return arr
print(foo(12, 1, 4))
答案 3 :(得分:0)
试试这个,
import random
x = [i for i in range(1, 5)] * 3
random.shuffle(x) # shuffle the sequence x in place
# Output
[4, 3, 1, 3, 2, 2, 3, 4, 4, 1, 2, 1]
如果元素是浮点数或双精度数,使用numpy.random.uniform
可以更轻松地回答这些问题import numpy as np
x = np.random.uniform(1, 5, 12)
# Output
array([ 4.18515267, 4.87403138, 3.43580119, 2.62828693, 3.77675348,
4.15627119, 4.02190688, 3.56667674, 1.31115154, 1.74971624,
3.20515834, 1.75240044])
答案 4 :(得分:0)
你可以使用发电机:
from random import randint
def getNum1To4(runs):
occurences = {n+1:0 for n in range(4)}
for i in range(runs):
options = [n for n in occurences if occurences[n] < runs / 4]
choice = options[randint(0, len(options) - 1)]
occurences[choice] += 1
yield choice
输出:
>>> runs = 8
>>> gen = getNum1To4(8)
>>> for n in range(runs): print gen.next()
2
1
3
1
3
4
4
2
答案 5 :(得分:0)
要根据给定范围[1,50]中的“均匀随机分布”生成随机整数,大小为5,
$scope.cData =$sce.trustAsHtml(htmlDataFromServer)
输出:
from scipy.stats import randint as sp_randint
values = sp_randint.rvs(1, 50, size=5, random_state=0)
print(values)
请注意,[94 97 50 53 53]
是写的必要条件,否则每次运行都会给您随机输出。有关更多详细信息,请查看documentation.