Search code examples
pythonprobabilityweighted-average

Random amount calculator


I'm trying to figure out a random amount calculator but by rarity for example:

choices = [10,100,1000,10000]

10 being the most common, 100 more common, 1000 rare, and 10000 extremely rare

I've tried this

import random
def getAmmounts():
    choices = [10, 100, 1000, 10000]
    values = [random.choice(choices) for i in range(10)]
    return values

Which returns a good amount of values but they're not that random 10000 appears quite often when it should almost hardly ever appear when I called on it the data what I received was:

[1000, 10000, 100, 1000, 10000, 10, 1000, 10000, 100, 100]

Two 10000's are in there and hardly any 10 values when 10s and 100s should be most common then an occasional 1000 in the mix but hardly ever a 10000 value. Is there any way to set up a priority type function that does this? Some good example data of what this should return after all said in done would be:

[10,10,100,10,10,100,1000]

And the occasional 10000 but it should be extremely rare, any idea on how to set this up?


Solution

  • Your code does not assign any probabilities. You might intend for 10 to be less rare than 10000 but Python isn't going to know that.

    You can simulate probability using the random.random to generate a random number between 0 and 1 and returning the appropriate number depending on the number generated.

    For example

    import random
    
    def make_number():
      val = random.random()
      if val < 0.1: #10%
        return 10000
      elif val < 0.3: # 20%
        return 1000
      elif val < 0.6: # 30%
        return 100
      else: # 40%
        return 10
    
    values = [make_number() for i in range(10)]
    print (values)