[英]Creating triangle pattern in python looping two characters using nested loop
Please help.请帮忙。 I need to create this pattern:
我需要创建这种模式:
* * $ * $ * * $ * $ * $ * $ * * $ * $ * $ * * $ *The best I can do is:
rows = 5 for i in range(0, 1): for j in range(0, i + 1): print("*", end=' ') print("\r") for i in range(0, rows): for j in range(0, i + 1): d = "$" print("*",d, end=' ') print("\r") for i in range(rows, 0, -1): for j in range(0, i - 1): print("*", d, end=' ') print("\r")
But it is not what I need.但这不是我需要的。 I desperately need help.
我迫切需要帮助。
You cna simplify a bit: a loop for the increase from 1 to 4, another for the decrease from 5 to 1, then depend on odd/even values choose the correct symbol你可以简化一点:一个循环从 1 增加到 4,另一个循环从 5 减少到 1,然后根据奇/偶值选择正确的符号
rows = 5
for i in range(1, rows):
for j in range(i):
print('*' if j % 2 == 0 else "$", end=" ")
print()
for i in range(rows, 0, -1):
for j in range(i):
print('*' if j % 2 == 0 else "$", end=" ")
print()
Can be done in one outer loop可以在一个外循环中完成
rows = 3
for i in range(-rows + 1, rows):
for j in range(rows - abs(i)):
print('*' if j % 2 == 0 else "$", end=" ")
print()
Slightly different approach:略有不同的做法:
N = 5
result = []
for i in range(N):
s = [('*', '$')[j % 2] for j in range(i+1)]
result.append(s)
print(*s)
for i in range(N-2, -1, -1):
print(*result[i])
You can use the abs
function to handle the inflection point with one loop:您可以使用
abs
function 通过一个循环来处理拐点:
print(
*(
' '.join(
'*$'[m % 2]
for m in range(rows - abs(rows - n - 1))
)
for n in range(2 * rows - 1)
),
sep='\n'
)
Or the above in one line, if you prefer:或者如果您愿意,可以将上述内容放在一行中:
print(*(' '.join('*$'[m % 2] for m in range(rows - abs(rows - n - 1))) for n in range(2 * rows - 1)), sep='\n')
Demo: https://replit.com/@blhsing/KnowledgeableWellwornProblem演示: https://replit.com/@blhsing/KnowledgeableWellwornProblem
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.