1

I am trying to recreate np.random.randn() for entertainment without using numpy library.

The function np.random.randn() could accept arbitrary number of arguments specifying length of each dimension. For example, np.random.randn(2, 3, 4) creates a 2 * 3 * 4 matrix where each entry is of standard normal distribution.

I have completed the following but get stuck in assigning each entry value (the line enclosed by #####...)

import random
from itertools import product

def getStandardNormalTensor(*dimList):
    # create empty list
    lst = 0
    for dim in dimList: lst = [lst] * dim
    # populate list with N(0, 1) number
    for idx in product(*[list(range(dim)) for dim in dimList]):
    #######################################
        lst[idx] = random.gauss(0, 1)
    #######################################
    
    return lst

where obviously lst does not accept indexing like lst[(1, 2, 3)] but only lst[1][2][3].

The difficulty I am having now is that I could not get indexing to work as I do not know how many dimensions are there in dimList (i.e. the length of dimList).

Could someone help me? Thank you in advance!

Mr.Robot
  • 349
  • 1
  • 16
  • 1
    You've got a more fundamental problem with this code than the indexing - since you're using multiplication to initialize the lists, you have *one* actual list with numbers, with multiple references to that one list in the second-level list, and so on. In other words, even if the indexing worked, only the first index would matter as to what element you were accessing. (One quick solution to indexing would be to use a dict instead of a list, in which case a tuple works just fine as an index. This also eliminates any need to initialize values.) – jasonharper Dec 03 '20 at 00:28
  • @jasonharper Thanks for pointing this out. I found someone else made the similar mistake as I did (see this [answer](https://stackoverflow.com/a/26067367/7784797)). – Mr.Robot Dec 03 '20 at 02:28

1 Answers1

0

You could try building a flat list of the correct length and then converting it into the nested list. Not sure how to recreate numpy's reshape off the top of my head, though.

  • Welcome to StackOverflow and thank you for your answer. I have actually considered this solution. But it seems that the solutions I could find to create multidimensional list all involve the use of `numpy`. The whole point of my efforts (for amusement) is to avoid using libraries other than Python standard library. – Mr.Robot Dec 03 '20 at 02:33