[英]How to print a pyramid of full pyramids?
我是一名新手程序員,我們最近的任務是打印一個完整的星號金字塔,行數基於輸入,然后打印這些金字塔的金字塔。
基本上,當用戶輸入Number of Rows: 4
時,我期望的輸出是:
*
***
*****
*******
* * *
*** *** ***
***** ***** *****
*******************
* * * * *
*** *** *** *** ***
***** ***** ***** ***** *****
*******************************
* * * * * * *
*** *** *** *** *** *** ***
***** ***** ***** ***** ***** ***** *****
*******************************************
這是我可以使用循環的最佳方法。
rowInput = int(input("Number of Rows: "))
rowCount = 0
min = rowInput
max = rowInput
while (rowCount < rowInput):
digit = 1
while (digit < min):
print(end=" ")
digit += 1
while (digit >= min and digit <= max):
print(end="*")
digit += 1
print()
min -= 1
max += 1
rowCount += 1
輸入:
Number of Rows: 4
輸出:
*
***
*****
*******
我認為它可以與頂部的另一個循環一起使用,但我想不出增加兩個三角形之間空間的可行方法。 還有其他選擇嗎?
您可以使用嵌套列表理解來構建要打印的行列表,但這有點令人費解。
rows = 4
lines = [" "*(rows-r//2-1)*(2*rows-1) + f"{'*'*i:^{2*rows-1}}"*r
for r in range(1,2*rows+1,2)
for i in range(1,2*rows+1,2)]
print(*lines,sep='\n')
*
***
*****
*******
* * *
*** *** ***
***** ***** *****
*********************
* * * * *
*** *** *** *** ***
***** ***** ***** ***** *****
***********************************
* * * * * * *
*** *** *** *** *** *** ***
***** ***** ***** ***** ***** ***** *****
*************************************************
為了更容易理解代碼,for 循環可能更好:
rows = 4
width = 2*rows-1 # width of one pyramid
for r in range(1,rows+1): # row with r pyramids
indent = " "*(rows-r)*width # indent pyramids
for p in range(rows): # pyramid lines
fill = "*"*(2*p+1) # filled width/stars for line
print(indent+(2*r-1)*f"{fill:^{width}}") # repeated pyramid stars
解決此問題的另一個好方法是將問題分解為您在單個函數中實現的較小部分。 組合執行小任務的功能可以更輕松地實施和測試您的解決方案:
# produce lines for one pyramid
def pyramid(n):
return [f"{'*'*r:^{2*n-1}}" for r in range(1,2*n+1,2)]
# combine pyramids horizontally
def pyramidRow(count,n):
return [count*line for line in pyramid(n)]
width = 2*rows-1 # width of one pyramid
for r in range(1,rows+1): # row of r pyramids
indent = " "*width*(rows-r) # indent pyramids
for line in pyramidRow(2*r-1,rows): # print repeated pyramids
print(indent+line)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.