高尔夫球代码:生成帕斯卡三角形 [英] Code-golf: generate pascal's triangle

查看:133
本文介绍了高尔夫球代码:生成帕斯卡三角形的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

生成列表列表(或打印,我不介意)帕斯卡三角形大小为N的代码行最少!

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!

这就是我的尝试(在 python 2.6中使用118个字符,使用技巧):

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

说明:


  • 列表理解的第一个元素(长度是0)是 [1]

  • 通过以下方式获得下一个元素:

  • 获取上一个列表,并创建两个列表,一个列表的开头以0填充,另一个列表的末尾填充。


    • 例如对于第二步,我们采用 [1] 并分别使 [0,1] [1,0]

    • 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]

      • 例如我们创建一个新列表 [(0,1),(1,0)] 并映射总和。<​​/ li>
      • e.g. we make a new list [(0,1),(1,0)] and map with sum.

      用法(打印精美,实际上超出了代码范围) -golf xD):

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

      输出:

                   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
      


      推荐答案

      J (APL家族的另一种语言),由9个字符组成:

      J, another language in the APL family, 9 characters:

      p=:!/~@i.
      

      这使用了J的内置组合动词。

      This uses J's builtin "combinations" verb.

      输出:

         p 10
      1 1 1 1 1  1  1  1  1   1
      0 1 2 3 4  5  6  7  8   9
      0 0 1 3 6 10 15 21 28  36
      0 0 0 1 4 10 20 35 56  84
      0 0 0 0 1  5 15 35 70 126
      0 0 0 0 0  1  6 21 56 126
      0 0 0 0 0  0  1  7 28  84
      0 0 0 0 0  0  0  1  8  36
      0 0 0 0 0  0  0  0  1   9
      0 0 0 0 0  0  0  0  0   1
      

      这篇关于高尔夫球代码:生成帕斯卡三角形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆