I’m new to Python and trying to generate an alternative pattern starting with two sets of values: (0, 0) and (10, 10). My expected output is as follows:
0 0
10 10
10 -10
20 0
20 20
20 -20
30 10
30 -10
30 30
30 -30
40 0
40 20
40 -20
40 40
40 -40
I attempted to achieve this with the following Python code, but it generated a different output:
N = 4
for i in range(N):
x = i * 10
y_values = [10, -10, 0]
for y in y_values:
print(f"{x}, {y}")
Any assistance would be appreciated.
Thank you!
>Solution :
I’ve written a Python script to generate an alternating pattern using nested loops. The pattern follows an odd and even indices, and I’ve included a condition to avoid negative values when the column index is zero.
n = 5
for i in range(n):
for j in range(i+1):
if i % 2 == 0 and j % 2 == 0: # Check if both row and column indices are even for alternating sets
print(f"{i*10} {j*10}")
if j != 0: # avoid negative in 0.
print(f"{i*10} -{j*10}")
if i % 2 != 0 and j % 2 != 0: # Check if both row and column indices are odd for alternating sets.
print(f"{i*10} {j*10}")
print(f"{i*10} -{j*10}")
it will generate your desire pattern
0 0
10 10
10 -10
20 0
20 20
20 -20
30 10
30 -10
30 30
30 -30
40 0
40 20
40 -20
40 40
40 -40
Another or alternative solution using bitwise AND (&) and adjust conditions for generating an alternating pattern.
n = 5
for i in range(n):
if i % 2 != 0:
for j in range(1, i + 1):
if i != j & i % 2 != 0:
print(i * 10, j * 10)
print(i * 10, -j * 10)
elif i % 2 == 0:
for j in range(i + 1):
if j * 20 <= i * 10:
print(i * 10, j * 20)
if j != 0:
print(i * 10, -j * 20)