编写一个Python程序,打印一个星号组成的钻石,钻石的高度(行数)由变量height的值决定你可以(可选地)要求用户输入height的值。
该值只能有奇数行,因此如果用户输入偶数,则应打印一条描述性消息。
这是我所拥有的,但我不明白这个…有人知道更简单的解决方法吗?
import math as m
height = int(input("Enter height - odd number: "))
if ((height > 2) and (height % 2 == 1)):
a = list(range(1, m.floor(height/2) + 1))
a.append(m.ceil(height/2))
a = a + list(reversed(list(range(1, m.floor(height/2) + 1))))
for h in a:
repeat = 2*h-1
ast = "*"*repeat
blank = int((height - repeat) /2)
blk = " "*blank
print(str(blk) + str(ast) + str(blk))
else:
print("The height must be a positve odd value")
先显示空格数递减,再显示星号递减:
height = 7
for i in range(1-height,height,2):
print(abs(i)//2*" " + "*"*(height-abs(i)))
*
***
*****
*******
*****
***
*
i从range(1-height,height,2)
的进阶为:
-6 -4 -2 0 2 4 6
如果取i的绝对值,它先减小后增大abs(i)
:
6 4 2 0 2 4 6
这个范围可以转换为每行的空格数和星号数:
spaces: abs(i)//2 = 3 2 1 0 1 2 3
stars: height-abs(i) = 1 3 5 7 5 3 1
垂直:
spaces stars | result (underlines are spaces)
3 1 | ___*
2 3 | __***
1 5 | _*****
0 7 | *******
1 5 | _*****
2 3 | __***
3 1 | ___*
使用这些数字,您可以将相应的字符相乘,并得到模式所需的重复字符串。
请注意,它也适用于偶数,尽管形状在左右两侧不是尖的
如果需要,可以在一行代码中将循环转换为推导式:
h = 7
print(*(i//2*' '+(h-i)*'*' for i in map(abs,range(1-h,h,2))),sep='n')
或
for i in map(abs,range(1-h,h,2)):print(i//2*' '+(h-i)*'*')
可以声明increasing
和decreasing
迭代器。它们告诉你每行打印多少个星号(中间行除外)。
您可以使用str.center
方法轻松地居中星号。也可以使用格式说明符将其居中,但我发现后者可读性较差。
size = int(input("Enter the size of the diamond: "))
if size%2 == 0:
raise ValueError("The size must be an odd value")
increasing = range(1, size, 2)
decreasing = reversed(increasing)
for i in increasing:
print(("*" * i).center(size))
print("*" * size)
for i in decreasing:
print(("*" * i).center(size))