怎么样:
side = int(input("Please input side length of diamond: "))
for x in list(range(side)) + list(reversed(range(side-1))):
print('{: <{w1}}{:*<{w2}}'.format('', '', w1=side-x-1, w2=x*2+1))
Giving:
*
***
*****
*******
*********
***********
*********
*******
*****
***
*
那么它是怎样工作的?
首先我们需要一个计数器来计数side
然后再次下降。没有什么可以阻止您将两个范围列表附加在一起,因此:
list(range(3)) + list(reversed(range(3-1))
这给你一个清单[0, 1, 2, 1, 0]
从这里我们需要计算出每行所需的正确空格和星号数量:
* needs 2 spaces 1 asterix
*** needs 1 space 3 asterisks
***** needs 0 spaces 5 asterisks
因此需要两个公式,例如为了side=3
:
x 3-x-1 x*2+1
0 2 1
1 1 3
2 0 5
使用 Python 的字符串格式,可以指定填充字符和填充宽度。这避免了必须使用字符串连接。
如果您使用的是 Python 3.6 或更高版本,您可以使用f
字符串表示法:
for x in list(range(side)) + list(reversed(range(side-1))):
print(f"{'': <{side - x - 1}} {'':*<{x * 2 + 1}}")