Python NumPy For Your Grandma - 3.10 Challenge: Psycho Parent

Contents

Setup

Eager to make your mark on the PTA, you decide the best way to hide eggs for for the upcoming Easter egg hunt is to use NumPy. You represent the field as a 10x10 array of 0s. Now your goal is to insert twenty random normal values at random (non repeating) locations in the grid that tell you how much candy to hide at each spot and where.

``````import numpy as np

field = np.zeros(shape = (10, 10))
print(field)
## [[0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
##  [0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
##  [0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
##  [0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
##  [0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
##  [0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
##  [0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
##  [0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
##  [0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
##  [0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]]
``````

Solution

``````np.set_printoptions(linewidth=999)
generator = np.random.default_rng(1234)
vals = np.round(generator.normal(size = 20), 2)
locs = generator.choice(field.size, len(vals), replace = False)
field.ravel()[locs] = vals
print(field)
## [[ 0.52  0.    0.   -1.48  0.    2.91  0.    0.    0.    0.  ]
##  [ 0.   -1.27  0.    0.    0.   -1.6   0.    1.73  0.    0.  ]
##  [ 0.    0.    0.    0.    0.43  0.    0.    0.    0.    0.  ]
##  [ 0.    0.    0.    0.    0.    0.34  0.    0.    0.   -1.67]
##  [ 0.    0.86  0.74  0.    0.    0.    1.32  0.    0.52  0.  ]
##  [ 0.   -1.    0.    0.    0.    0.15  0.    0.    0.    0.  ]
##  [ 0.   -0.51  0.   -0.86  0.    0.    0.    0.    0.    0.  ]
##  [ 0.    0.    0.    0.    0.    0.    0.    0.    0.    0.  ]
##  [ 0.    0.    0.    0.   -2.16  0.    0.95  0.    0.    0.  ]
##  [ 0.    0.    0.    0.    0.    0.    0.    0.    0.    0.06]]
``````