Shuffling a list, splitting data or simulating orders all need random numbers. A computer makes them from a starting number called the seed. The same seed always gives the same numbers, in the same order. That is why lessons and experiments set one: everyone who runs the code sees the same results.
The tools: np.random.default_rng(seed) gives back a generator, an object whose methods make random numbers. rng.integers(low, high, size=n) gives back n whole numbers from low up to, but not including, high. rng.normal(mean, spread, size=n) gives back n decimal numbers, most of them close to mean. rng.permutation(array) gives back a shuffled copy and leaves the original array alone.
gen = np.random.default_rng(42)
codes = gen.integers(100, 1000, size=3) # 3 whole numbers from 100 to 999
print("Coupon codes:", codes)
Each call takes the next numbers from the generator, so the order of your calls matters. To get the first numbers again, make a new generator with the same seed. The products array and its print are already in the editor. The finished script prints:
Products: ['Mug' 'Lamp' 'Pen' 'Plant' 'Teapot'] Dice: [6 4 4 2 2] Order sizes: [20.5 17.3 21.8 26.5] Shuffled: ['Mug' 'Pen' 'Plant' 'Teapot' 'Lamp'] Dice again: [6 4 4 2 2]
Your task: make a generator rng with the seed 0. Print "Dice:" with 5 whole numbers from 1 to 6, "Order sizes:" with 4 numbers around 20 with spread 5, rounded to 1 decimal with np.round, and "Shuffled:" with products in a random order. Then make a second generator again with the same seed 0 and print "Dice again:" with 5 rolls from it.
Assignment
Follow the Coding Tutorial to draw dice rolls, order sizes and a shuffle from a seeded generator, then repeat the dice with a second generator.
Hinthigh is left out, so dice from 1 to 6 need integers(1, 7, size=5). Keep the calls in the order of the steps: each one takes the next numbers from rng, so a different order prints different numbers.
Free plan: 30 tutor messages. PRO is unlimited.
