在 Python 中增加更改数字的可能性
Make a changing number more probable in Python
我有 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
如何更改概率,使之前的选择更有可能?
您可以在每次调用时更改 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%)
在不使用 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%。
我有 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
如何更改概率,使之前的选择更有可能?
您可以在每次调用时更改 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%)
在不使用 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%。