撰寫一個 Python 程式,列印一個由星號制成的鉆石,其中鉆石的高度(行數)由變數 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")
uj5u.com熱心網友回復:
列印先減少后增加的空格數,然后增加星數,然后減少星數:
height = 7
for i in range(1-height,height,2):
print(abs(i)//2*" " "*"*(height-abs(i)))
*
***
*****
*******
*****
***
*
i from 的進展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)*'*')
uj5u.com熱心網友回復:
您可以宣告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))
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/343081.html
