如何输出n个重叠的菱形,每个菱形的高度为2n-1。以下是n = 3的输出要求:
* * *
* * * * * *
* * * * * * *
* * * * * *
* * *
n = 4
* * * *
* * * * * * * *
* * * * * * * * * * * *
* * * * * * * * * * * * *
* * * * * * * * * * * *
* * * * * * * *
* * * *
n = 5
* * * * *
* * * * * * * * * *
* * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * *
* * * * * * * * * *
* * * * *
我尝试使用循环编写代码,成功输出了与输入n相对应的每个形状。然而,我无法将钻石形状显示在“单行”上,只能像这样显示在多行中:
n = 3
*
* *
* * *
* *
*
*
* *
* * *
* *
*
*
* *
* * *
* *
*
这是我使用的代码:
n = int(input()) #for number of diamonds per row
height = 2*n - 1
for j in range(1, n + 1): #for printing h no. of diamonds
#from row 1 to middle row
for row in range(1, (height + 1)//2 + 1):
for spaces in range((height + 1)//2 - row): #print spaces per row
print(" ", end = "")
for stars in range((2*row) - 1): #print stars per row
if stars % 2 == 0:
print("*", end = "")
else:
print(" ", end = "")
print()
#from middle row to last row
for row in range((height + 1)//2 + 1, height + 1):
for spaces in range(row - (height + 1)//2):
print(" ", end = "")
for stars in range((height + 1 - row)*2 - 1):
if stars % 2 == 0:
print("*", end = "")
else:
print(" ", end = "")
print()