Reputation: 100
I would like to print the following pattern using python:
00X
0X0
X00
Additionally, I have to print this using loops ONLY, without using arrays. Well, I have written an initial code, but is not scalable. Here is the initial code:
for i in range (1):
for j in range (1):
print(0, 0, "X")
for i in range (1):
for j in range (1):
print(0, "X", 0)
for i in range (1):
for j in range (1):
print("X", 0, 0)
I am looking for a suitable alternative. Please also feel free to contribute on the [source code on my GitHub: https://github.com/micahondiwa/python/blob/main/0x00-python/31-pattern.py.
Thank you.
I tried using the for a loop. Although I got the output, the result is not scalable. I am expecting to find a solution that uses a function to implement a loop and print the pattern.
Upvotes: 0
Views: 877
Reputation: 179
From what I understood, you want to write a matrix, where there is X in the secondary diagonal and 0 in all other places, and you can't use arrays (which you don't need).
If I am correct, you basically want to do this (if we say the matrix is 10x10):
This shows the next pattern
So we can do it like this:
n = 10
for i in range(n):
print('0' * (n-i-1) + 'X' + '0' * i)
EDIT:
Since @micahondiwa said it needs to be implemented in function, here is the code sample:
def my_func(n):
for i in range(n):
print('0' * (n-i-1) + 'X' + '0' * i)
Upvotes: 1
Reputation: 172
Here n
is the number of rows and columns.
for i in range(n):
for j in range(n):
if(j == n - 1 - i):
print("X", end="")
else:
print("0", end="")
print()
output:
n = 3
>>> 00X
>>> 0X0
>>> X00
Upvotes: 1
Reputation: 12701
You can do it in a single loop:
SQUARE_SIZE = 8
for i in range(SQUARE_SIZE):
print("0"*(SQUARE_SIZE-i-1) + "X" + "0"*i)
Output:
0000000X
000000X0
00000X00
0000X000
000X0000
00X00000
0X000000
X0000000
Upvotes: 1
Reputation: 13533
A nested loop will work. The outer loop goes from n-1
to 0
and the inner loop goes from 0
to n-1
. When the outer and inner loop variables are equal, print an X
.
def f(n):
for row in range(n-1, -1, -1):
for col in range(n):
if row == col:
print('X', end='')
else:
print('0', end='')
print()
Example run:
>>> f(5)
0000X
000X0
00X00
0X000
X0000
Upvotes: 2