RustyShackleford
RustyShackleford

Reputation: 3677

How to skew random choice probability towards one option?

I am using the random library in python to select win or lose.

import random

choice = random.choice(['win','lose'])

Is there anyway I can say set the probability in the code to say I want more lose than win everytime the code runs?

Upvotes: 1

Views: 432

Answers (2)

Severin Pappadeux
Severin Pappadeux

Reputation: 20130

Well, @CloC is technically right, you could do that, but better use the standard Python library as it is designed, less code, less bugs

F.e., sampling with probability of Win being 60%

v = random.choices(["Win", "Lose"], weights=[60, 40], k=1)

Upvotes: 2

SivolcC
SivolcC

Reputation: 3618

A way to control random (which wont be random...) would be to:

Generate a number between 1 and 100:

n = random.randint(1,101)

and then compare it with the percentage of win/loses you want :

chances_to_win = 51  # 50%

if n < chances_to_win:
    print(str(chances_to_win-1) +"% chances to Win")
    choice = "Win"
else:
    print(str(100-(chances_to_win-1)) +"% chances to Lose")
    choice = "Lose"

That way, you can control what is the percentage of wins and loses.

Upvotes: 1

Related Questions