Geek With A Keyboard Geek With A Keyboard - 15 days ago 6
Python Question

How to increase chance of item being randomly generated?

I'm working on some Python code, just messing around. The purpose of my algorithm is to generate a 256x256 grey square with green mossy bits. The algorithm does not actually generate the pixels, it just compiles a dictionary with 65536 attributes, either "Grey" or "Green, RGB colour code". I want to generate a mossy looking slab, and I would like to have clumps of green. Is it possible to increase the chance of having multiple occurrences of the generated value "Green" in a row, either with the Random module ir through another technique?

Answer

You can use random.choice() to get random value from the list. Increase the occurrence of Green by the amount you want to increase the probability of it's occurrence. For example:

>>> import random

>>> color = ['Green', 'Green', 'Red', 'Blue']    
# Here probability of generating:
#      "Green": 50%
#      "Red"  : 25%
#      "Blue" : 25%

# For getting the number from list, do:
>>> random.choice(color)
Comments