我已经编写了一个Python脚本来使用嵌套循环生成交替模式。该模式遵循奇数和偶数索引,并且我包含了一个条件,以避免列索引为零时出现负值。
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}")
它会产生你的欲望模式
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
使用逐位AND(&)并调整生成交替模式的条件的另一个或替代解决方案。
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)