Reputation:
How can you use nested for loops to print out the following pattern in python? So you don't have to write 7 print functions to print the pattern.
1
0 1
1 0 1
0 1 0 1
1 0 1 0 1
0 1 0 1 0 1
1 0 1 0 1 0 1
Upvotes: 3
Views: 1071
Reputation: 5355
One more solution not using nested loops, instead using a single loop and binary representations.
solution = 1
for i in range(7):
out_str = f'{solution:b}'
print(' '.join(out_str[::-1]))
solution = solution << 1
if i > 0 and i % 2 == 1:
solution |= 1
Upvotes: 0
Reputation: 72
You can try this :
import os
import re
import sys
def print_pattern(num):
if(num == 1):
print("1",end="\n")
return
elif(num%2 == 1):
print("1",end=" ")
print_pattern(num-1)
else:
print("0",end=" ")
print_pattern(num-1)
number = int(input("Enter the steps"))
for i in range(1,number+1):
print_pattern(i)
Upvotes: 0
Reputation: 31161
Not containing loop but an example of recursive function so that you push further:
>>> def foo(length_max, list_=[1]):
... print(list_)
... if len(list_)==length_max:
... return
... return foo(length_max, [int(not bool(list_[0]))] + list_)
...
>>> foo(7)
[1]
[0, 1]
[1, 0, 1]
[0, 1, 0, 1]
[1, 0, 1, 0, 1]
[0, 1, 0, 1, 0, 1]
[1, 0, 1, 0, 1, 0, 1]
Upvotes: 2
Reputation: 2179
This is the long but simple solution
count = -1 # Count where in the loop we are
switch = 1 # Switch between 0 and 1
start = 1 # Switch which varibale we start the line with
for i in range(8):
print()
count += 1
start = switch
for j in range(8):
if j != count:
if switch == 0:
print("1 ", end='') #end= means dont print a new line character
switch = 1
else:
print("0 ", end='')
switch = 0
if j == count:
if start == 1:
switch = 0
else:
switch = 1
break #Break loop as we have printed as many characters as we want
print() # Print to end the line
Upvotes: 0
Reputation: 51165
This is not an answer in pure python, it makes use of numpy
and scipy
, but I think this is a great question because of the matrix you're trying to describe.
You may not be intending this, but your output matches the lower triangle of a Toeplitz matrix.
Because of the way you alternate, every diagonal will have the same value. Therefore, you could use scipy
to produce your output.
Setup
num = 7
out = [1,0]*((num // 2)+1)
out = out[:num]
from scipy.linalg import toeplitz
res = toeplitz(out)
res[np.triu_indices_from(res, k=1)] = -1
for row in res:
print(' '.join(map(str, row[row!=-1])))
1
0 1
1 0 1
0 1 0 1
1 0 1 0 1
0 1 0 1 0 1
1 0 1 0 1 0 1
Upvotes: 1
Reputation: 10860
As I can see, this is the contest of how many people do not answer the question, which was about using nested loops... Ok, here we go, this is my approach: :-)
import numpy as np
n = 7
for i in range(n):
print(1-np.mod(np.arange(i+1), 2)[::-1])
Upvotes: 1
Reputation: 7970
You could try this:
def run():
data = [1]
iterations = 7
for i in range(iterations):
print_data(data)
data.append(i % 2)
print_data(data)
def print_data(dat):
print(' '.join(d for d in dat[::-1]))
This solution has the added benefit of not using insert
, which is O(n)
and replacing an if-statement with a mathematical expression.
Upvotes: 0
Reputation: 9019
You are on the right track with your comment, here is one option using insert()
:
start = [1]
no_rows = 7
for i in range(no_rows):
print(start)
start.insert(0, 1 if start[0]==0 else 0)
Which gives:
[1]
[0, 1]
[1, 0, 1]
[0, 1, 0, 1]
[1, 0, 1, 0, 1]
[0, 1, 0, 1, 0, 1]
[1, 0, 1, 0, 1, 0, 1]
If you want each line to be formatted as a str
opposed to a list
, then you can change print(start)
to print(' '.join([str(s) for s in start]))
, which gives:
1
0 1
1 0 1
0 1 0 1
1 0 1 0 1
0 1 0 1 0 1
1 0 1 0 1 0 1
As per Patrick Haugh's comment, you could instead simply replace print(start)
with print(*start)
to print the list of integers as a str
.
Upvotes: 2
Reputation: 12990
You could do something like this:
s = ''
for i in range(1, 8):
s = str(i % 2) + s
print(s)
Upvotes: 4