-2

I was wondering how I could generate a list of random number (1, 2) but with different probability. ie : 1 has a probability of 0.6 and 2 has a probability of 0.4.

Thanks!

  • http://stackoverflow.com/q/11373192/5351549 – ewcz May 03 '17 at 18:07
  • 2
    I wouldn't be surprised if this is a duplicate of some question, but since that other question specifically asks for a scipy/numpy solution, I don't see how it could count as a duplicate (especially since scipy/numpy are overkill for this.) – John Coleman May 03 '17 at 18:23
  • Perfect example of how the dup flag is abused on SO. – Abhijit Sarkar Jan 08 '20 at 04:06
  • `random.choices` will do it, but if using a library function isn't allowed, `random.choice([j for i in range(len(nums)) for j in [i] * int(10 * probabilities[i])])` works, assuming the numbers are unique to begin with – Abhijit Sarkar Jan 08 '20 at 04:19

1 Answers1

-3

Use random.choice

import random
random.choice([1,1,1,1,1,1,2,2,2,2])

You can also write

data = [1]*6 + [2]*4
choice = random.choice(data)
Zohaib Ijaz
  • 21,926
  • 7
  • 38
  • 60
  • Thanks for the reply. But what if we have a probability of 0.53251? – Christopher van Hoecke May 03 '17 at 18:10
  • Can anyone tell me the reason for down vote? – Zohaib Ijaz May 03 '17 at 18:10
  • @ZohaibIjaz This method only works for the most simplistic of cases. The asker asked a question that would be difficult to achieve with your solution. – sethmlarson May 03 '17 at 18:11
  • @SethM.Larson Read question again. Exact same question was asked that I answered. choose 1 with probability 0.6 and 2 with 0.4. – Zohaib Ijaz May 03 '17 at 18:13
  • Read what OP posted as a comment to your answer. In case you missed it: `Thanks for the reply. But what if we have a probability of 0.53251?` – sethmlarson May 03 '17 at 18:14
  • But that was not asked @SethM.Larson – Zohaib Ijaz May 03 '17 at 18:17
  • @ZohaibIjaz I agree the question is bad. It states a simple case, and then OP asks for probability of Pi/sqrt(45) – Jean-François Fabre May 03 '17 at 18:18
  • 2
    I don't think that it is fair for someone to penalize you for answering the original question (instead of one that popped up in the comments), although it is still a valid criticism of your answer that it isn't very flexible. There are more flexible versions which are just as easy to write (e.g. `1 if random.random() < 0.6 else 2`.) – John Coleman May 03 '17 at 18:27