Home > Software engineering >  How do I repeat binary pattern and ratio in matrix effectively in python?
How do I repeat binary pattern and ratio in matrix effectively in python?

Time:04-25

I want to efficiently print a matrix in python that follows a specific pattern in the columns of 5 0s then 3 1s then 5 0s and so on and so forth as shown below for 1000 rows:

0000
0000
0000
0000
0000
1111
1111
1111
0000
0000
0000
0000
0000
1111
1111
1111
...

CodePudding user response:

This didn't use numpy but it does the job. You can later convert it into a numpy matrix using numpy.matrix.

import itertools

cycle = itertools.cycle([5 for i in range(5)]   [3 for i in range(3)])

for i in range(1000):
  item = next(cycle)

  if item == 5:
    print("0" * 5)
  else:
    print("1" * 5)

Output -

00000
00000
00000
00000
00000
11111
11111
11111
00000
00000
00000
00000
00000
11111
11111
11111

CodePudding user response:

Here's how you can do it:

import numpy as np

my_array = np.array([[[0,0,0,0], [0,0,0,0], [0,0,0,0], [0,0,0,0], [0,0,0,0], [1,1,1,1], [1,1,1,1], [1,1,1,1]] for i in range(125)])

You can check the shape. It has 125 rows of 8 rows i.e. 1000:

>>> my_array.shape
(125, 8, 4)

To print it you can use:

count_row = 0
for row in my_array:
    for row2 in row:
        print(row2)
        count_row  = 1

Output:

# count_row is equal to 1000.

[0 0 0 0]
[0 0 0 0]
[0 0 0 0]
[0 0 0 0]
[0 0 0 0]
[1 1 1 1]
[1 1 1 1]
[1 1 1 1]
[0 0 0 0]
[0 0 0 0]
[0 0 0 0]
[0 0 0 0]
[0 0 0 0]
[1 1 1 1]
[1 1 1 1]
[1 1 1 1]
[0 0 0 0]
....
  • Related