How can I create a binary table of this alternating pattern efficiently in python? The 1s repeat for 4 elements then 0s for another 4 elements and so on and so forth as shown below:
101010
101010
101010
101010
010101
010101
010101
010101
101010
101010
...
CodePudding user response:
Consider using numpy.tile
import numpy as np
one_zero = np.tile([1, 0], 12).reshape(4, 6)
"""
array([[1, 0, 1, 0, 1, 0],
[1, 0, 1, 0, 1, 0],
[1, 0, 1, 0, 1, 0],
[1, 0, 1, 0, 1, 0]])
"""
zero_one = np.tile([0, 1], 12).reshape(4, 6)
"""
array([[0, 1, 0, 1, 0, 1],
[0, 1, 0, 1, 0, 1],
[0, 1, 0, 1, 0, 1],
[0, 1, 0, 1, 0, 1]])
"""
ar = np.tile([[1, 0], [0, 1]], 12).reshape(8, 6)
"""
array([[1, 0, 1, 0, 1, 0],
[1, 0, 1, 0, 1, 0],
[1, 0, 1, 0, 1, 0],
[1, 0, 1, 0, 1, 0],
[0, 1, 0, 1, 0, 1],
[0, 1, 0, 1, 0, 1],
[0, 1, 0, 1, 0, 1],
[0, 1, 0, 1, 0, 1]])
"""
CodePudding user response:
Using list comprehension:
table = [('101010', '010101')[x//4%2 == 1] for x in range(100)]
You may prefer use 0b101010 and 0b010101 instead of string, but the result printed will be 42 and 21.