Menu

Random Library

Independent random choices

When a program needs two random values, calling a random function twice gives two independent choices: the second call knows nothing about the first, so it takes its value from the full range all over again.

import random

delay1 = random.randint(1, 4)
delay2 = random.randint(1, 4)
print("First bus was late by", delay1, "minutes")
print("Second bus was late by", delay2, "minutes")

Output:

First bus was late by 4 minutes
Second bus was late by 1 minutes

Adding two random numbers

Because each call is independent, adding the two results does not spread the chance evenly across the totals. Some totals can be made in several different ways, so they come up more often than others. With each bus delay between 1 and 4 minutes, every pair is just as likely as any other, and there are sixteen pairs in total:

Total delayPairs that make itNumber of pairs
21 + 11
31 + 2, 2 + 12
41 + 3, 2 + 2, 3 + 13
51 + 4, 2 + 3, 3 + 2, 4 + 14
62 + 4, 3 + 3, 4 + 23
73 + 4, 4 + 32
84 + 41

So a total of 5 is four times as likely as a total of 2. Generating random.randint(2, 8) once would instead give every total exactly one chance in seven, a flat pattern with no peak in the middle.

Repeats are allowed

Independence also means repeats. Two separate calls can return the same value, because the function keeps no memory of what it produced before and never avoids an earlier result. Often that is exactly what you want, such as two buses both being 3 minutes late.

Making values unique

Sometimes repeats are not allowed. A teacher giving four different project topics, numbered 1 to 10, to four students must not pick the same number twice, so the program has to check rather than assume:

  1. Generate a random number.
  2. Compare it with every number already chosen.
  3. If it matches one of them, discard it, generate a fresh number and compare that one as well.
  4. Store the number only once it matches nothing.

Going round again until a new value appears needs iteration, and the comparison needs selection; those are separate ideas. What matters here is that a random function never guarantees unique results on its own, so a program that needs distinct values must compare each new one with those already stored and generate again when it is a repeat.

Practise this