傅能杰
傅能杰

Reputation: 153

How to initialize an empty array that can accept any size?

def __init__(self):
        self.b = []
        for i in range(2):
            board_num = input("Type something to test this out: ")
            n = int(input("enter n: "))
            if board_num == 2:
                self.b = ['R', 'B', 'R', 'B']
    #            n==4
            elif board_num == 3:
                self.b = ['R', 'B', 'R', 'B', 'R', 'B', 'R', 'B', 'B']
    #            n==6
            elif board_num == 4:
                self.b = ['R', 'B', 'R', 'B', 'R', 'B', 'R', 'B', 'B', 'R', 
                            'B', 'R', 'R', 'B', 'R', 'B']
        numpy.arange(n*n).reshape((n,n))
        self.b=numpy.array(self.b)
        numpy.random.shuffle(self.b)
        self.b=self.b.reshape(n,n)

  line 30, in __init__
    self.b=self.b.reshape(n,n)

ValueError: cannot reshape array of size 0 into shape (2,2)

Upvotes: 0

Views: 73

Answers (1)

Jay
Jay

Reputation: 2902

I'm guessing a bit at what you're trying to accomplish, but here is how I might implement it:

$ python
Python 3.7.2 (default, Dec 27 2018, 07:35:06) 
[Clang 10.0.0 (clang-1000.11.45.5)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import numpy
>>> n = 4
>>> board = numpy.array(['R', 'B'])
>>> board = numpy.resize(board, (n, n))
>>> board
array([['R', 'B', 'R', 'B'],
       ['R', 'B', 'R', 'B'],
       ['R', 'B', 'R', 'B'],
       ['R', 'B', 'R', 'B']], dtype='<U1')

Or with the shuffle step:

>>> n = 4
>>> board = numpy.array(['R', 'B'])
>>> board = numpy.resize(board, n*n)
>>> board
array(['R', 'B', 'R', 'B', 'R', 'B', 'R', 'B', 'R', 'B', 'R', 'B', 'R',
       'B', 'R', 'B'], dtype='<U1')
>>> numpy.random.shuffle(board)
>>> board
array(['R', 'B', 'R', 'R', 'B', 'R', 'R', 'B', 'R', 'R', 'B', 'B', 'B',
       'B', 'R', 'B'], dtype='<U1')
>>> board = numpy.resize(board, (n, n))
>>> board
array([['R', 'B', 'R', 'R'],
       ['B', 'R', 'R', 'B'],
       ['R', 'R', 'B', 'B'],
       ['B', 'B', 'R', 'B']], dtype='<U1')

Upvotes: 2

Related Questions