格式化Pascal的三角形

时间:2010-11-10 03:12:52

标签: python output-formatting pascals-triangle

我目前正在做一项家庭作业,以在Python中生成所谓的Pascal's triangle

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

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开始),并在达到用户指定的行数后停止。

但是,我不确定如何格式化我的三角形。它目前打印为:

[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.

(由于括号/逗号,它有点过时,但我现在只想尝试一般格式。)

感谢您提供任何帮助!

6 个答案:

答案 0 :(得分:1)

以下是一些提示。尝试:

' ' * someNumber

表示间距。如果您不想使用列表括号,则可以遍历该行:

for el in i:
  # Write el as you want

或使用join

您可能还会发现enumerate有助于获取索引(例如间距)。

答案 1 :(得分:1)

获得行后,最后一行可能是最长的行。

由于您只是将它们打印出来,然后您可以使用l = len(str(rows[-1])),然后将其与每行str(rows[i]).center(l)合并。

编辑:我们不知道我们应该给家庭作业的所有答案......如果是这样的话:

def mytri(myrange):
    rows = list()
    lr = None # Last row

    for i in xrange(myrange+1):
        try:
            lr = [1] + [lr[i] + lr[i+1] for i in range(len(lr) - 1)] + [1]
        except TypeError:
            lr = [1]
        #rows.append(str(lr))
        rows.append(' '.join(str(v) for v in lr))
    return rows

rows = mytri(10)
l = len(rows[-1])
print '\n'.join(v.center(l) for v in rows)

输出

                 1                 
                1 1                
               1 2 1               
              1 3 3 1              
             1 4 6 4 1             
           1 5 10 10 5 1           
          1 6 15 20 15 6 1         
        1 7 21 35 35 21 7 1        
       1 8 28 56 70 56 28 8 1      
    1 9 36 84 126 126 84 36 9 1    
1 10 45 120 210 252 210 120 45 10 1

答案 2 :(得分:1)

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

所以在这里你为每个级别的金字塔打印2个空格。第一行缩进两倍高度的空格数。当你下降一个级别时,你将缩进减少2。

答案 3 :(得分:0)

不是在每次迭代时重新生成前一行,而是在生成它时生成每一行:

def mytri(height):
  start = [1]
  for _ in xrange(height):  # "_" for an unused variable
    yield start  # loop written "backwards" for simplicity,
    # though this does generate one unused row
    next_row = [1]
    for a, b in zip(start, start[1:]):  # slicing creates a new list, not a
      next_row.append(a + b)            # concern for this problem, but in
    next_row.append(1)                  # others you could use itertools.islice
    start = next_row                    # to avoid that

现在向后列举每一行的高度:

height = int(raw_input("Height: "))
for n, row in zip(xrange(height - 1, -1, -1), mytri(height)):
  print "   " * n, " ".join("%5d" % x for x in row)

这很快就不会排成很多行,但它应该让你朝着正确的方向前进。

答案 4 :(得分:0)

您需要填充所有数字,使它们的宽度相同 您还需要在左侧添加一些填充

def mymenu():
    res = mytri(int(raw_input("Please enter the height of the triangle: ")))
    width = len(str(res[-1][len(res[-1])/2]))
    for i, row in enumerate(res):
        print " "*(width*(len(res)-i)/2)+" ".join(str(x).rjust(width) for x in row)
    print '\n'
    choicevar = raw_input("Would you like to create another triangle? (y/n): ")
    if choicevar == "y":
        mymenu()
    else:
        print "Goodbye."

输出:

Please enter the height of the triangle: 10
                1 
              1   1 
             1   2   1 
           1   3   3   1 
          1   4   6   4   1 
        1   5   10  10  5   1 
       1   6   15  20  15  6   1 
     1   7   21  35  35  21  7   1 
    1   8   28  56  70  56  28  8   1 
  1   9   36  84 126 126  84  36  9   1 

答案 5 :(得分:0)

n=input('enter n:')
z=0
d=' '
while z<n:
        d=d+'   '
        z=z+1
print d,1
l1=[1]
l2=[1,1]
def space(n,a):
        s=''
        while a<n:
        s=s+' '
        a=a+1
        return s
def digit(n):
        r=1
        k=0
        while r!=0:
            r=n/10**k
            k=k+1
        return k-1
def print_l(l1,b):
        d=''
        d='\n'+space(b-1,0)*3
        i=0
        while i<len(l1):
            d=d+' '*(6-digit(l1[i]))+str(l1[i])
            i=i+1
        print d
b=n-1
k=1
while k<n:
        l2=l1
        l1=[1]
        i=1
        while len(l1)<len(l2):
            if i>len(l2)/2:
                l1.append(l1[len(l2)-i])
            else:
                l1.append(l2[i-1]+l2[i])
            i=i+1   
        k=k+1
        l1.append(1)
        print_l(l1,b)
        b=b-1