I am designing code in Python that needs to generate a random outcome given a probability.
Example: There are two possible outcomes: attack or no attack. Given a probability of 25% of an attack occurring, how do I generate an outcome based on that probability?
Let represent 1 for ATTACK
and 0 for NO-ATTACK
and we create a att_or_not
list in which selecting 1
is 0.25
so we use random.randint(0, 3)
to select a item from list. Check out logic here
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)