Question

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()

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.

The output I want is:

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

Was it helpful?

Solution

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

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.

OTHER TIPS

Here are a couple hints. Try:

' ' * someNumber

for the spacing. If you don't want the list brackets, you can loop over the row:

for el in i:
  # Write el as you want

or use join.

You may also find enumerate helpful to get indices (e.g. for spacing).

Once you have your rows, you would probably have the last row as the longest.

Since you just print them out, you can then take the l = len(str(rows[-1])) and then, combine that with a str(rows[i]).center(l) for each row.

EDIT: Was not aware that we should give all the answers to homework... If so:

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)

Would output

                 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

Instead of regenerating the previous rows on each iteration, you can yield each row as you generate it:

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

Now enumerate the height backwards along with each row:

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)

This will quickly not line up with very many rows, but it should get you headed in the right direction.

You need to pad all the numbers so they are the same width
You also need to add some padding to the left side

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

output:

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 
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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top