0

What is equivalent pure python code?

A = np.random.randint(2, size=(4,2))

array([[0, 1],
       [0, 1],
       [0, 0],
       [1, 0]])
1
  • What exactly was the problem when you tried to do this? Commented Aug 12, 2020 at 10:20

2 Answers 2

4

This could suit you.

from random import randint

A = [[randint(0, 1) for y in range(2)]   for x in range(4)]

print(A)

output:

>>> [[0, 0], 
     [0, 0],
     [0, 1],
     [0, 1]]
Sign up to request clarification or add additional context in comments.

Comments

0

if you need different shapes with multiple dimensions here it is the code:

import random

def random_matrix(c,shape):
    for i in range(len(shape)):
        if len(shape)-i>1:
            for j in range(shape[i]):
                return [random_matrix(c,shape[i+1:]) for b in range(shape[i])]
        else:
            return [random.randint(0,c-1) for v in range(shape[i])]

mat = random_matrix(2,[3,3,1])
print(mat)
print(mat[0])

Output:

[[[1], [0], [1]], [[0], [1], [0]], [[0], [1], [0]]]
[[1], [0], [1]]

or just as in your example:

mat = random_matrix(2, [4,2])
print(mat)

output:

[[0, 0], [0, 0], [0, 0], [0, 0]]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.