我是一名新手程式員,我們最近的任務是列印一個完整的星號金字塔,行數基于輸入,然后列印這些金字塔的金字塔。
基本上,當用戶輸入時我期望的輸出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
輸出:
*
***
*****
*******
我認為它可以與頂部的另一個回圈一起使用,但我想不出增加兩個三角形之間空間的可行方法。還有其他選擇嗎?
uj5u.com熱心網友回復:
您可以使用嵌套串列理解來構建要列印的行串列,但這有點令人費解。
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)
測驗:
for line in pyramid(4): print(line)
*
***
*****
*******
for line in pyramidRow(3,4): print(line)
* * *
*** *** ***
***** ***** *****
*********************
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/343068.html
上一篇:在PHP中使用嵌套回圈的質數
