格式化帕斯卡的三角形 [英] Formatting Pascal's triangle

查看:101
本文介绍了格式化帕斯卡的三角形的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在从事一项作业,以生成Python中称为帕斯卡三角形的

I am currently working on a homework assignment to generate what is known as Pascal's triangle in Python.

到目前为止,这就是我所拥有的:

So far, this is what I have:

def mytri(myrange):
    trianglevar = [[1]]
    for i in range(1, myrange):
        tempvar = [1]
        for n in range(0, i-1):
            tempvar.append(trianglevar[i-1][n]+trianglevar[i-1][n+1])
        tempvar.append(1)
        trianglevar.append(tempvar)
    return trianglevar

def mymenu():
    for i in mytri(int(raw_input("Please enter the height of the triangle: "))):
        print i
    print '\n'
    choicevar = raw_input("Would you like to create another triangle? (y/n): ")
    if choicevar == "y":
        mymenu()
    else:
        print "Goodbye."

mymenu()

到目前为止,程序所做的就是对三角形进行计算.它计算每行中的数字(从1开始),并在达到用户指定的行数后停止.

What the program does up to this point is perform the calculation for the triangle. It calculates the numbers in each row (starting with 1), and stops after reaching the number of rows specified by the user.

但是,我不确定如何格式化三角形.当前打印为:

However, I'm not sure how to format my triangle. It currently prints as:

[1]
[1, 1]
[1, 2, 1]
[1, 3, 3, 1]
[1, 4, 6, 4, 1]
...etc.

我想要的输出是:

        [1]
      [1, 1]
    [1, 2, 1]
  [1, 3, 3, 1]
[1, 4, 6, 4, 1]
...etc.

(由于括弧/逗号,这有点偏离,但是我现在正试图将通用格式记下来.)

(It's a bit off due to the brackets/commas, but I'm just trying to get the general format down right now.)

感谢您提供的任何帮助!

Thank you for any help you can offer!

推荐答案

h = int(raw_input("Please enter the height of the triangle: "))
for i in mytri(h):
    print " " * (h * 2), i
    h -= 1

因此,您在此处为每个金字塔等级打印2个空格.第一行缩进两倍的空格高度数.下降一个级别时,缩进量减少2.

So here you print 2 spaces for each level of pyramid. First line gets indented by twice the height number of spaces. As you descent one level, you decrease indentation by 2.

这篇关于格式化帕斯卡的三角形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆