0
votes

I am trying to figure out how to use a percent chance in order to output a letter.

How my program works is that the user will enter a whole numeric value between 1 and 100, then my program converts that into decimal value. Also the user enters the amount of iterations the loop will occur in the next step.

The next step involves outputting either a x or a y based on the probability entered in the first step, so if the user entered 70, then there will be a 70% (0.7 probability) chance of x being outputted during the z amount of iterations.

Right now I am trying to figure out how to get my program to use the user entered probability in order to determine how many x's it should output.

Thanks in advance, not to sure if it all made sense (newbie programmer here..)

2
Please include a sample of your code as there are a number of ways to do this (scipy, numby, using math) and we need to see what you've tried so far to advise you on your problem. - LinkBerest
Get a uniformly distributed random number between 0 to 1. There is about 70% of chance that it is less than 0.7. - YS-L
@JGreenwell sorry I'm pretty new here, will do next question! - ev884

2 Answers

6
votes

Run the following code. It will output an x with a 70% chance:

>>> import random
>>> 'yx'[random.randrange(100)<70]
'x'

How it works:

  • import random

    This imports a module that we need.

  • random.randrange(100)

    This generates a random integer from 0 to 99.

  • random.randrange(100)<70

    This generates False (0) or a True (1)

  • 'yx'[random.randrange(100)<70]

    This selects the character based on the result of the random number.

Alternative

As suggested by achampion, the above can also be accomplished with a ternary statement:

'x' if random.randrange(100) < 70 else 'y'
0
votes

A possible solution.

x_prob = 70 # for example
iter_times = 100 # for example

for i in xrange(iter_times):
    prob = random.randint(1, 100) # produce an integer in [1, 100]
    if prob <= x_prob:
        print x
    else:
        print y