B C
B C

Reputation: 318

Make a changing number more probable in Python

I have 6 colours associated with the values 1 to 6 that are all equally probable:

    randc = random.randint(1,6)
    if randc == 1:
        print 'red'
    elif randc == 2:
        print 'green'
    elif randc == 3:
        print 'purple'
    elif randc == 4:
        print 'yellow'
    elif randc == 5:
        print 'orange'
    elif randc == 6:
        print 'brown'

Now I want a second colour to print such that 50% of the time it will be the same as the first colour. In the past I have used numpy to augment probability, but I only makes a set value more probable:

    randcol = numpy.random.choice((1,2), p=[0.8, 0.2])
    if randcol == 1:
        print 'red'  # will occur 80% of the time
    elif randcol == 2:
        print 'green' # will occur 20% of the time

How do I change the probability such that it will make a previous selection more likely?

Upvotes: 0

Views: 132

Answers (2)

smb564
smb564

Reputation: 353

Try this without using numpy or any other library,

randc = random.randint(1,6)
probList = range(1,7) + [randc]*4
next = probList[random.randint(0,len(probList)-1)]

next will have the 50% probability you wanted.

Since the probList will be filled with 5 times the last color out of 10, it is 50% probability. And for the rest of the colors probability is equally divided.

Example:

Lets say randC= 5

Now probList will become

[1,2,3,4,5,6,5,5,5,5]

Thus getting 5 from the above list will have a probability of 50%.

Upvotes: 1

kennytm
kennytm

Reputation: 523304

You could change the p or the input every time you call it.

colors = ['red', 'green', 'purple', 'yellow', 'orange', 'brown']
prev_choice = numpy.random.choice(colors)
print(prev_choice)
# pick the first color uniformly.

for _ in range(100):
    prev_choice = numpy.random.choice([prev_choice] + colors, p=[0.4] + [0.1]*6)
    print(prev_choice)
    # we pick the new color same as the previous one with 40% chance,
    # and all of the colors uniformly with 10% each.
    # (so the total chance of choosing the previous color is 40% + 10% = 50%)

Upvotes: 2

Related Questions