random

random is a lot of fun and has a bunch of functions we easily forget about, since they are not used often.

One note we would like to especially bring to your attention: In testing the little routines you will find below, we discovered that you MUST use “random.seed()” before every call to another random function or you will eventually (some times it takes a while) end up with very statistically improbable “runs” of duplicate results.

Like in our other module recaps, this isn’t everything in random; but covers most of it’s utility. First….

.seed(a=None, version=2) use it or don’t blame us for the results.
Here is a short list of our favorite random functions:
.random() Return the next random floating point number in the range [0.0, 1.0)
.randint(a, b) – an alias for
.randrange(stop) or
.randrange(start, stop[, step])
.getstate()
.setstate(state)
.getrandbits(k)
.choice(seq)
.choices(population, weights=None, *, cum_weights=None, k=1)¶
.shuffle(x[, random])
.uniform(a, b)    Return random floating point number N such that a <= N <= b for a <= b and b <= N <= a for b < a.
.triangular(low, high, mode) mode argument defaults to the midpoint between the bounds, giving a symmetric distribution.

A couple of notes: getstate() and setstate(state) enable you to duplicate a random result. Try this:

Import random
x=random.getstate()
myint=random.randint(1,1000)
print(myint)
random.setstate(x)
myint=random.randint(1,1000)
print(myint)

….yields….
745
745
(or two other identical numbers)
Here is another example you can try for yourself by deleting the “random.seed()” line after the for function:

Import random
colors=['red','orange','yellow','green','blue','indigo','violet']
for i in range(1,20):
   random.seed()
   print(random.choice(colors))

….and while we have a color list handy take a look at the shuffle command:

Import random
colors=['red','orange','yellow','green','blue','indigo','violet']
print(colors)
print("afterusingshuffle")
random.shuffle(colors)
print(colors)

…..you will get something like:
[‘red’, ‘orange’, ‘yellow’, ‘green’, ‘blue’, ‘indigo’, ‘violet’]
after using shuffle
[‘yellow’, ‘green’, ‘red’, ‘indigo’, ‘blue’, ‘violet’, ‘orange’]

One more note. The “.choice(sequence)” and “.choices(pop,weights….etc)” function could have lots of applications but one is not so obvious. You can use dictionaries as a “sequence” as long as your keys are consecutive integers starting with 0. Here is an example that also includes a warning about using “.seed()”:

random.seed()
mydict={0:"fillin",1:"dog",2:"cat",3:"foo",4:"bar"}
for i in range(1,10):
    random.seed() #remove this line - "runs" of duplicates occur
    try:
        print(random.choice(mydict))
    except:
        print("zero?")