Pascal's Triangle for Python

后端 未结 11 1561
轮回少年
轮回少年 2020-11-30 06:13

As a learning experience for Python, I am trying to code my own version of Pascal\'s triangle. It took me a few hours (as I am just starting), but I came out with this code:

11条回答
  •  鱼传尺愫
    2020-11-30 06:30

    Without using zip, but using generator:

    def gen(n,r=[]):
        for x in range(n):
            l = len(r)
            r = [1 if i == 0 or i == l else r[i-1]+r[i] for i in range(l+1)]
            yield r
    

    example:

    print(list(gen(15)))
    

    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], [1, 11, 55, 165, 330, 462, 462, 330, 165, 55, 11, 1], [1, 12, 66, 220, 495, 792, 924, 792, 495, 220, 66, 12, 1], [1, 13, 78, 286, 715, 1287, 1716, 1716, 1287, 715, 286, 78, 13, 1], [1, 14, 91, 364, 1001, 2002, 3003, 3432, 3003, 2002, 1001, 364, 91, 14, 1]]
    

    DISPLAY AS TRIANGLE

    To draw it in beautiful triangle(works only for n < 7, beyond that it gets distroted. ref draw_beautiful for n>7)

    for n < 7

    def draw(n):
        for p in gen(n):
            print(' '.join(map(str,p)).center(n*2)+'\n')
    

    eg:

    draw(10)

    output:

          1       
    
         1 1      
    
        1 2 1     
    
       1 3 3 1    
    
      1 4 6 4 1   
    
    1 5 10 10 5 1   
    

    for any size

    since we need to know the max width, we can't make use of generator

    def draw_beautiful(n):
        ps = list(gen(n))
        max = len(' '.join(map(str,ps[-1])))
        for p in ps:
            print(' '.join(map(str,p)).center(max)+'\n')
    

    example (2) : works for any number:

    draw_beautiful(100)
    

提交回复
热议问题