生成二元结果 给定概率的随机结果
Generate Binary Outcome Random Outcome Given A Probability
我正在 Python 中设计代码,需要在给定概率的情况下生成随机结果。
示例:
有两种可能的结果:攻击或不攻击。给定 25% 的攻击发生概率,我如何根据该概率生成结果?
让我们代表 1 for ATTACK
和 0 for NO-ATTACK
我们创建一个 att_or_not
列表,其中 selecting 1
是 0.25
所以我们使用random.randint(0, 3)
到 select 列表中的一项。 在这里检查逻辑
import random
rand_num = random.randint(0, 3)
def prob(rand_num, list_):
if list_[rand_num]:
return 'Attack'
return 'No-Attack'
# [1, 0, 0, 0] => here 1 represent ATTACK and 0 represent NO_ATTACK
att_or_not = [1, 0, 0, 0]
result = prob(rand_num ,att_or_not)
print(result)
我正在 Python 中设计代码,需要在给定概率的情况下生成随机结果。
示例: 有两种可能的结果:攻击或不攻击。给定 25% 的攻击发生概率,我如何根据该概率生成结果?
让我们代表 1 for ATTACK
和 0 for NO-ATTACK
我们创建一个 att_or_not
列表,其中 selecting 1
是 0.25
所以我们使用random.randint(0, 3)
到 select 列表中的一项。 在这里检查逻辑
import random
rand_num = random.randint(0, 3)
def prob(rand_num, list_):
if list_[rand_num]:
return 'Attack'
return 'No-Attack'
# [1, 0, 0, 0] => here 1 represent ATTACK and 0 represent NO_ATTACK
att_or_not = [1, 0, 0, 0]
result = prob(rand_num ,att_or_not)
print(result)