我有6种颜色与值1到6相关,这些颜色都是同等可能的:
randc = random.randint(1,6)
if randc == 1:
print 'red'
elif randc == 2:
print 'green'
elif randc == 3:
print 'purple'
elif randc == 4:
print 'yellow'
elif randc == 5:
print 'orange'
elif randc == 6:
print 'brown'
现在我想要第二种颜色进行打印,这样50%的时间它将与第一种颜色相同。在过去,我使用numpy来增加概率,但我只是设定值更有可能:
randcol = numpy.random.choice((1,2), p=[0.8, 0.2])
if randcol == 1:
print 'red' # will occur 80% of the time
elif randcol == 2:
print 'green' # will occur 20% of the time
如何更改概率,以便更有可能进行先前的选择?
答案 0 :(得分:2)
每次调用时都可以更改p
或输入。
colors = ['red', 'green', 'purple', 'yellow', 'orange', 'brown']
prev_choice = numpy.random.choice(colors)
print(prev_choice)
# pick the first color uniformly.
for _ in range(100):
prev_choice = numpy.random.choice([prev_choice] + colors, p=[0.4] + [0.1]*6)
print(prev_choice)
# we pick the new color same as the previous one with 40% chance,
# and all of the colors uniformly with 10% each.
# (so the total chance of choosing the previous color is 40% + 10% = 50%)
答案 1 :(得分:1)
在不使用numpy或任何其他库的情况下尝试此操作
randc = random.randint(1,6)
probList = range(1,7) + [randc]*4
next = probList[random.randint(0,len(probList)-1)]
接下来将有50%的概率。
由于probList将填充10次中最后一种颜色的5倍,因此概率为50%。而对于剩下的颜色,概率是平分的。
示例:
让我们说randC= 5
现在probList将成为
[1,2,3,4,5,6,5,5,5,5]
因此,从上面的列表中获得5将有50%的概率。