首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >代数金字塔蟒蛇挑战赛-更有效的方式?

代数金字塔蟒蛇挑战赛-更有效的方式?
EN

Stack Overflow用户
提问于 2021-01-14 05:45:44
回答 2查看 250关注 0票数 1

我正在做一个python挑战,你必须根据列表创建一个倒置的代数金字塔。每一层(向下)都需要是它上面的数字的总和。

我创建了4个层的代码来做这件事。

第二部分的挑战是为任何长度的列表做这件事,所以我添加了len(列表)代码来适应。你可以在下面看到我的代码。

我只是想知道是否有更有效的方法来处理长列表,或者我只需要为剩余的层键入更多的代码。

另外,我想知道return语句是如何适应它的(下面的代码中给出了更新return语句的提示)。

代码语言:javascript
复制
 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)
EN

回答 2

Stack Overflow用户

发布于 2021-01-14 06:04:07

这里这个函数将使用列表计算你的金字塔:

代码语言:javascript
复制
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

此函数将以字符串形式获取金字塔:

代码语言:javascript
复制
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)

现在你可以输入任何你想要的基数,它会工作的

代码语言:javascript
复制
print_pyramid(calcul_pyramid([30,12,10,22])))
票数 1
EN

Stack Overflow用户

发布于 2021-01-14 11:33:50

您可以使用zip将值相加,然后这只是一个格式问题:

代码语言:javascript
复制
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)

输出:

代码语言:javascript
复制
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
           568
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65710243

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档