用Python輸出一個楊輝三角的例子

來源:互聯網
上載者:User
關於楊輝三角是什麼東西,右轉維基百科:楊輝三角

稍微看一下直觀一點的圖:
複製代碼 代碼如下:


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

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.