我正在做一个python挑战,你必须根据列表创建一个倒置的代数金字塔。每一层(向下)都需要是它上面的数字的总和。
我创建了4个层的代码来做这件事。
第二部分的挑战是为任何长度的列表做这件事,所以我添加了len(列表)代码来适应。你可以在下面看到我的代码。
我只是想知道是否有更有效的方法来处理长列表,或者我只需要为剩余的层键入更多的代码。
另外,我想知道return语句是如何适应它的(下面的代码中给出了更新return语句的提示)。
def drawPyramid(list):
layer = ""
layer2 = " "
layer3 = " "
layer4 = " "
for i in range(len(list)):
layer = layer + " " + str(list[i])
for i in range(len(list)-1):
layer2 = layer2 + " " + str(list[i]+list[i+1])
for i in range(len(list)-2):
layer3 = layer3 + " " + str(list[i]+(list[i+1]*2)+list[i+2])
for i in range(len(list)-3):
layer4 = layer4 + " " + str(list[i]+(list[i+1]*3)+(list[i+2]*3)+list[i+3])
print(layer)
print(layer2)
print(layer3)
print(layer4)
#Update this code to generate all 4 layers of the pyramid
#Update this return statement to return the value of the single brick on the last layer of the pyramid
return 0
#Main code starts here
list = [30,12,10,22]
drawPyramid(list)发布于 2021-01-14 06:04:07
这里这个函数将使用列表计算你的金字塔:
def calcul_pyramid(base):
pyramid = [base]
for i in range(len(base) - 1):
actual_layer = []
last_layer = pyramid[i]
for j in range(len(last_layer) - 1):
actual_layer.append(last_layer[j] + last_layer[j + 1])
pyramid.append(actual_layer)
return pyramid此函数将以字符串形式获取金字塔:
def print_pyramid(pyramid):
lines = []
for layer in pyramid:
line = ""
for brick in layer:
line += str(brick)
line += " "
lines.append(line)
pyramid_len = max([len(layer) for layer in lines])
txt = ""
for line in lines:
diff = (pyramid_len - len(line)) / 2
txt += " " * int(diff + 0.5)
txt += line
txt += " " * int(diff - 0.5)
txt += "\n"
print(txt)现在你可以输入任何你想要的基数,它会工作的
print_pyramid(calcul_pyramid([30,12,10,22])))发布于 2021-01-14 11:33:50
您可以使用zip将值相加,然后这只是一个格式问题:
def pyramid(A):
indent = ""
width = len(str(sum(A)))
while A:
print(indent,*(f"{a:{width}}" for a in A))
A = [a+b for a,b in zip(A,A[1:])]
indent += " "*max(1,width-1)输出:
L = [30,12,10,22]
pyramid(L)
30 12 10 22
42 22 32
64 54
118
L = [30,12,10,22,23,43]
pyramid(L)
30 12 10 22 23 43
42 22 32 45 66
64 54 77 111
118 131 188
249 319
568https://stackoverflow.com/questions/65710243
复制相似问题