Search code examples
python-2.7pascals-triangle

Creating a non-right Pascal's triangle (centered) in python


I need to write a code that inputs a non-right Pascal's triangle given the nth level as an input where the first row is the 0th level. Apart from that, at the end of each row the level must be indicated. Here's what I've made so far:

level = input('Please input nth level: ')
x = -1
y = 1

while x < level:
    x = x+1
    d = str(11**x)
    while y < level:
        y = y+1
        print " ",
    for m,n in enumerate(d):
        print str(n) + " ",
    while y < level:
        y = y+1
        print " ",
    print x

When I input 3, it outputs:

    1  0
1  1  1
1  2  1  2
1  3  3  1  3

My desired output is:

   1      0
    1 1     1
   1 2 1    2
  1 3 3 1   3

Solution

  • You could use str.format to center the string for you:

    level = int(raw_input('Please input nth level: '))
    
    N = level*2 + 5
    for x in range(level+1):
        d = ' '.join(str(11**x))
        print('{d:^{N}} {x:>}'.format(N=N, d=d, x=x))
    

    Please input nth level: 4
           1        0
          1 1       1
         1 2 1      2
        1 3 3 1     3
       1 4 6 4 1    4
    

    Note that if d = '1331', then you can add a space between each digit using ' '.join(d):

    In [29]: d = '1331'
    
    In [30]: ' '.join(d)
    Out[30]: '1 3 3 1'
    

    Note that using d = str(11**x) is a problematic way of computing the numbers in Pascal's triangle since it does not give you the correct digits for x >= 5. For example,

    Please input nth level: 5
           1        0
          1 1       1
         1 2 1      2
        1 3 3 1     3
       1 4 6 4 1    4
      1 6 1 0 5 1   5   <-- Should be 1 5 10 10 5 1 !
    

    You'll probably want to compute the digits in Pascal's triangle a different way.