1

I have a string of 1s and 0s that I need to insert into a [4] by [4] matrix, that I can then use for other things.

This is my attempt at it:

b = '0110000101101000'

m = [[], [], [], []]
for i in range(4):
    for j in range(4):
        m[i].append(b[i * j])

But where I expected to get

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

I got [['0', '0', '0', '0'], ['0', '1', '1', '0'], ['0', '1', '0', '0'], ['0', '0', '0', '1']].

Could someone point me in the right direction here?

4 Answers 4

2

Get paper and a pencil and write a table of what you have now vs what you want:

i j i*j desired
0 0  0  0
0 1  0  1
0 2  0  2
0 3  0  3
1 0  0  4
1 1  1  5
... up to i=3, j=3

Now you can see that i * j is not the correct index in b. Can you see what the desired index formula is?

Sign up to request clarification or add additional context in comments.

Comments

0

I'd agree with @John Zwinck that you can easily figure it out but if you hate math simply do

counter = 0
for i in range(4):
    for j in range(4):
        m[i].append(b[counter])
        counter += 1 # keep track of the overall iterations

otherwise you have to find the starting row you are in (i * columns) and add the current column index

m[i].append(b[i * 4 + j]) # i * 4 gives the overall index of the 0th element of the current row

Comments

0

Here is a hint: range(4) starts from 0 and ends at 3. See the python documentation: https://docs.python.org/3.9/library/stdtypes.html#typesseq

Comments

0

First of all, the rule to convert coordinates to index is index = row * NRO_COLS + col. You should use i * 4 + j.

Second, you can use list comprehension:

m = [[b[i * 4 + j] for j in range(4)] for i in range(4)]

then, it can be rewritten as:

m = [[b[i + j] for j in range(4)] for i in range(0, len(b), 4)]

or

m = [list(b[i:i+4]) for i in range(0, len(b), 4)]

another alternative is to use numpy, which is a great library, specially to handle multidimensional arrays

import numpy as np

m = np.array(list(b)).reshape(4,4)

or:

print(np.array(list(b)).reshape(4, -1))
print(np.array(list(b)).reshape(-1, 4))

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.