Code-golf: generate pascal's triangle

2019-01-16 14:17发布

Generate a list of lists (or print, I don't mind) a Pascal's Triangle of size N with the least lines of code possible!

Here goes my attempt (118 characters in python 2.6 using a trick):

c,z,k=locals,[0],'_[1]'
p=lambda n:[len(c()[k])and map(sum,zip(z+c()[k][-1],c()[k][-1]+z))or[1]for _ in range(n)]

Explanation:

  • the first element of the list comprehension (when the length is 0) is [1]
  • the next elements are obtained the following way:
  • take the previous list and make two lists, one padded with a 0 at the beginning and the other at the end.
    • e.g. for the 2nd step, we take [1] and make [0,1] and [1,0]
  • sum the two new lists element by element
    • e.g. we make a new list [(0,1),(1,0)] and map with sum.
  • repeat n times and that's all.

usage (with pretty printing, actually out of the code-golf xD):

result = p(10)
lines = [" ".join(map(str, x)) for x in result]
for i in lines:
    print i.center(max(map(len, lines)))

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

23条回答
\"骚年 ilove
2楼-- · 2019-01-16 14:52

VBA/VB6 (392 chars w/ formatting)

Public Function PascalsTriangle(ByVal pRows As Integer)

Dim iRow As Integer
Dim iCol As Integer
Dim lValue As Long
Dim sLine As String

  For iRow = 1 To pRows
    sLine = ""
    For iCol = 1 To iRow
      If iCol = 1 Then
        lValue = 1
      Else
        lValue = lValue * (iRow - iCol + 1) / (iCol - 1)
      End If
      sLine = sLine & " " & lValue
    Next
    Debug.Print sLine
  Next

End Function
查看更多
乱世女痞
3楼-- · 2019-01-16 14:53

69C in C:

f(int*t){int*l=t+*t,*p=t,r=*t,j=0;for(*t=1;l<t+r*r;j=*p++)*l++=j+*p;}

Use it like so:

int main()
{
#define N 10
    int i, j;
    int t[N*N] = {N};

    f(t);

    for (i = 0; i < N; i++)
    {
        for (j = 0; j <= i; j++)
            printf("%d ", t[i*N + j]);
        putchar('\n');
    }
    return 0;
}
查看更多
戒情不戒烟
4楼-- · 2019-01-16 14:53

Scheme — compressed version of 100 characters

(define(P h)(define(l i r)(if(> i h)'()(cons r(l(1+ i)(map +(cons 0 r)(append r '(0))))))(l 1 '(1)))

This is it in a more readable form (269 characters):

(define (pascal height)
  (define (next-row row)
    (map +
         (cons 0 row)
         (append row '(0))))

  (define (iter i row)
    (if (> i height)
        '()
        (cons row
              (iter (1+ i)
                    (next-row row)))))

  (iter 1 '(1)))
查看更多
Lonely孤独者°
5楼-- · 2019-01-16 14:53

PHP 100 characters

$v[]=1;while($a<34){echo join(" ",$v)."\n";$a++;for($k=0;$k<=$a;$k++)$t[$k]=$v[$k-1]+$v[$k];$v=$t;}
查看更多
Summer. ? 凉城
6楼-- · 2019-01-16 14:54

Haskell, 58 characters:

r 0=[1]
r(n+1)=zipWith(+)(0:r n)$r n++[0]
p n=map r[0..n]

Output:

*Main> p 5
[[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1],[1,5,10,10,5,1]]

More readable:

-- # row 0 is just [1]
row 0     = [1]
-- # row (n+1) is calculated from the previous row
row (n+1) = zipWith (+) ([0] ++ row n) (row n ++ [0])
-- # use that for a list of the first n+1 rows
pascal n  = map row [0..n]
查看更多
Ridiculous、
7楼-- · 2019-01-16 14:54

Old thread, but I wrote this in response to a challenge on another forum today:

def pascals_triangle(n):
    x=[[1]]
    for i in range(n-1):
        x.append([sum(i) for i in zip([0]+x[-1],x[-1]+[0])])
    return x

for x in pascals_triangle(5):
    print('{0:^16}'.format(x))

      [1]       
     [1, 1]     
   [1, 2, 1]    
  [1, 3, 3, 1]  
[1, 4, 6, 4, 1]
查看更多
登录 后发表回答