Home  >  Article  >  Backend Development  >  用Python输出一个杨辉三角的例子

用Python输出一个杨辉三角的例子

WBOY
WBOYOriginal
2016-06-16 08:43:462454browse

关于杨辉三角是什么东西,右转维基百科:杨辉三角

稍微看一下直观一点的图:

复制代码 代码如下:

        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


杨辉三角有以下几个特点:

每一项的值等于他左上角的数和右上角的数的和,如果左上角或者右上角没有数字,就按0计算。
第N层项数总比N-1层多1个

计算第N层的杨辉三角,必须知道N-1层的数字,然后将相邻2项的数字相加,就能得到下一层除了最边上2个1的所有数字。 听起来有点像递归的思想,我们不妨假设我们已经知道N-1层的数字,来计算一下N层的数字吧。

复制代码 代码如下:

def _yanghui_trangle(n, result):
    if n == 1:
        return [1]
    else:
        return [sum(i) for i in zip([0] + result, result + [0])]

上面代码中,result表示N-1层杨辉三角的数字。实习上,我们在列表2端各补了一个0,然后计算相邻项的和,就可以直接得到结果。

稍微完善一下代码:

复制代码 代码如下:

def yanghui_trangle(n):
    def _yanghui_trangle(n, result):
        if n == 1:
            return [1]
        else:
            return [sum(i) for i in zip([0] + result, result + [0])]
    pre_result = []
    for i in xrange(n):
        pre_result = _yanghui_trangle(i + 1, pre_result)
        yield pre_result

if __name__ == "__main__":
    for line in yanghui_trangle1(5):
        print line


_yanghui_trangle可以用lambda的方式简写,但是可读性感觉会变差,所以还是保持现状好了。

tips: 上面的程序并没有考虑数据格式化的问题,也就是说输出不是完美的三角形。

鉴于最近在学习erlang,补上一个erlang版本的,性能上没有测试过,不过还是要惊叹于函数式语言的表达能力:

复制代码 代码如下:

-module(yanghui).
-author(lfyzjck).
-export([triangle/1]).

triangle_next(P) ->
    lists:zipwith(fun(X, Y) -> X+Y end, [0|P], P ++ [0]).

triangle(1) ->
    [[1]];
triangle(N) ->
    L = triangle(N - 1),
    [H|_] = L,
    [triangle_next(H)|L].

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn