Send Close Add comments: (status displays here)
Got it!  This site "www.robinsnyder.com" uses cookies. You consent to this by clicking on "Got it!" or by continuing to use this website.  Note: This appears on each machine/browser from which this site is accessed.
Python: Random class instances
by RS  admin@robinsnyder.com : 1024 x 640


1. Python: Random class instances
Python has the ability to create random class instances, each a separate RNG (Random Number Generator)

This allows multiple independent random number generators to be created and used that do not share state.

This is done with the random.Random class.

2. Usefulness
This can be useful for certain simulations whereby certain types of repeatable randomness is needed in the presence of parts of a program that change.

3. Python program
Here is the Python code [#1]

Here is the output of the Python code.

The random numbers for the lower-left (2, 1) cell and the upper-right (1, 2) cell are different for the shared RNG but the same when using and independent RNG for each cell.

4. Table structure
One way to represent a 2D table structure is as follows, using lists of lists.
[ [(0,0,"a"), (0,1,"b")], [(1,0,"c"), (1,1,"d")] ]

There is no easy or convenient way to store meta information about the table in the list structure.

5. Dictionary approach
For many applications, where appropriate, I use the following approach for a 2D table that uses a dictionary.
{ "title" : "example", "rows": 2, "cols": 2, (0,0): "a", (0,1): "b", (1,0): "c", (1,1): "d", }

The tuples represent the cells, but other meta information can be used.

Note: A class can be used to load, save, etc., but this structure makes the JSON save/load convenient.

In same cases, the list structure can become one dictionary key, if needed.

by RS  admin@robinsnyder.com : 1024 x 640