I spend time working on a simple python function that allows for printing binary square patterns. Below is the code.
def print_binary_square(n):
i = 0
odd = True
while(i<n):
j=0
while(j<n):
if(odd):
if (j % 2 == 0):
print(0, end='')
else:
print(1,end='')
j += 1
else:
j += 1
if (j % 2 == 0):
print(0, end='')
else:
print(1,end='')
odd = not odd
i += 1
print()
As you can see, the function takes one argument. It would print binary numbers in a square pattern. Each row starts with either 0 for odd-numbered or 1 for even-numbered row The above code worked, but I was wondering if there's I can improve for the code since the nested if-else seems redundant for me.
Thanks in advance!
If you look at the output as zero-indexed matrix, you can note that zero occurs at index (i, j)
whenever i + j
is even. Using this observation, you could write the following. It is shorter but not necessarily more legible.
n = 5
result = "\n".join(
"".join("0" if (i + j) % 2 == 0 else "1" for i in range(n))
for j in range(n)
)
Here is a solution using itertools
and a generator. Generators and itertools.cycle
make it easy to repeat things without needing to count. The only trick here is to waste one element at each line in case n is even (as the last number repeats).
from itertools import cycle, islice
c = cycle(['0','1'])
n = 6
print('\n'.join(''.join(islice(c, n+1-n%2))[:n]
for _ in range(n)))
Output:
010101
101010
010101
101010
010101
101010
This makes it very easy to generalize by just changing the input:
from itertools import cycle, islice
def pattern(l, n):
c = cycle(l)
r = 1-n%len(l)
print ('\n'.join(''.join(islice(c, n+r))[:n]
for _ in range(n)))
Example:
>>> pattern(list('012'), 5)
0120
1201
2012
0120
1201
>>> pattern(list('01234'), 7)
012340
123401
234012
340123
401234
012340
123401
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.