Chris
Chris

Reputation: 3688

How to create a tuple of tuples and pass it to the superclass's constructor

Let's say we need to have a board (as in a chess board) representation with tuples.
We would need the (x,y) coordinates of the square and then some extra info, for example, if there's a character of the game on it.

So I created the tuple of tuples - an empty game board like this:

n = 4
array = ()
j = 0
i = 0
for k in range(n*n):
    array = array + ((i,j, 0),)
    j += 1
    if j%4 == 0:
        j = 0
        i += 1

Is this the right way to do that? Or there is a shorter way?
Then I'll be passing the array to the superclass.

I've also seen this:

super(className, self).__init__(tuple([0 for j in range(n)]), None)

Which creates a tuple of tuples or a tuple of lists? ..and then passes it into the superclass constructor.
Also, could somebody explain the 0 for j in range(n)? (It's the 0 that bugs me. If it's a list, could it be an initialization of the list?)

Upvotes: 0

Views: 517

Answers (2)

Paul Bissex
Paul Bissex

Reputation: 1704

For representing the board, have you considered a list of n lists, each n items long (where n is your board width/height)?

The list comprehension you ask about at the end, passes to __init__ a single tuple of n zeroes.

Upvotes: 0

Lev Levitsky
Lev Levitsky

Reputation: 65791

You can refactor the code like this:

def empty_board(n):
    return tuple(
        (i, j, 0) for i in range(n) for j in range(n))

This is a generator expression (ref)inside the call to tuple, which creates a tuple out of any iterable, including a generator.

Note that using tuples may not be a good idea, because they are immutable. So you can't change the 3rd element of a given tuple to 1:

In [5]: board = empty_board(4)

In [6]: board[5][2] = 1
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-6-506047481a47> in <module>()
----> 1 board[5][2] = 1

TypeError: 'tuple' object does not support item assignment

Also, storing the coordinates of the fields seems a bit redundant. You can use indexes of a nested list instead, like this:

In [7]: def mutable_board(n):
   ...:     return [[0]*n for _ in range(n)]
   ...:

In [8]: mutable_board(3)
Out[8]: [[0, 0, 0], [0, 0, 0], [0, 0, 0]]

In [9]: board = mutable_board(4)

In [10]: board[2][3] = 1

To answer the question about the superclass constructor argument: it's just a tuple:

In [12]: tuple([0 for j in range(n)])
Out[12]: (0, 0, 0, 0)

Upvotes: 2

Related Questions