doctest random output?
Peter Otten
__peter__ at web.de
Mon Aug 28 06:07:23 EDT 2017
Leam Hall wrote:
> Is this a good way to test if random numeric output? It seems to work
> under Python 2.6 and 3.6 but that doesn't make it 'good'.
>
> ### Code
> import random
>
> def my_thing():
> """ Return a random number from 1-6
> >>> 0 < my_thing() <=6
> True
> >>> 6 < my_thing()
> False
> """
These are fine as illustrative tests that demonstrate how my_thing() is
used.
If you want to test the "randomness" -- that's hard. You could run more
often
all(1 <= mything() <= 6 for _ in range(1000))
but that doesn't guarantee that the 1001st attempt is outside the specified
range. You could have a look at the distribution
>>> c = Counter(my_thing() for _ in range(1000))
>>> set(c) == set(range(1, 7))
True
but that *should* occasionally fail even though in practice
>>> dict(c) == {3: 1000}
True
would be a strong indication that something is broken rather than that you
are really lucky...
More information about the Python-list
mailing list