推荐学习书目
› Learn Python the Hard Way
Python Sites
› PyPI - Python Package Index
› http://diveintopython.org/toc/index.html
› Pocoo
值得关注的项目
› PyPy
› Celery
› Jinja2
› Read the Docs
› gevent
› pyenv
› virtualenv
› Stackless Python
› Beautiful Soup
› 结巴中文分词
› Green Unicorn
› Sentry
› Shovel
› Pyflakes
› pytest
Python 编程
› pep8 Checker
Styles
› PEP 8
› Google Python Style Guide
› Code Style from The Hitchhiker's Guide
Tiande
V2EX  ›  Python

这段 杨辉三角 的算法,真漂亮...

  •  
  •   Tiande · Jun 17, 2015 · 11786 views
    This topic created in 4159 days ago, the information mentioned may be changed or developed.

    来源 (代码在评论中)

    代码:

    def triangles():
    ....a = [1];
    ....while True:
    ........yield a
    ........a = [sum(i) for i in zip([0] + a, a + [0])]

    部分结果:

    $ python python/pytest.py
    [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]
    

    真是爆za了 ;)

    45 replies  •  2015-06-26 17:12:38 +08:00
    ColorfulNight
    ColorfulNight
    Jun 17, 2015
    1
    我用C的队列写过,但是不知道为什么当行数一大就会出错
    sinux
    sinux
    PRO
    Jun 17, 2015
    2
    nice job
    elvis_w
    elvis_w
    Jun 17, 2015
    3
    Python的生成器函数,不错
    zerh925
    zerh925
    Jun 17, 2015❤️1
    4
    之前看到使用yield生成fab数,从最简单的方法,到使用list存储,再到定义一个类的next()方法,最后再来一记yield,真是惊艳到了。
    66beta
    66beta
    Jun 17, 2015❤️1
    5
    哼,格式不对,没对齐
    est
    est
    Jun 17, 2015❤️1
    6
    pascal = map ([1,1]^) [0..]
    take 5 pascal -- [[1], [1,1], [1,2,1], [1,3,3,1], [1,4,6,4,1]]

    还是有更加高级的语言的描述能力能秒杀python的。
    est
    est
    Jun 17, 2015❤️2
    7
    定义一个函数 fib 用来输入任意位的Fibonacci 数列

    fib 0 = 0
    fib 1 = 1
    fib n = fib (n-1) + fib (n-2)
    TimLang
    TimLang
    Jun 17, 2015
    8
    看了下python的yield和ruby的yield完全不是一个意思啊。下面是Ruby代码,ruby不需要生成器。

    ```ruby
    def pascal(n)
    ar = [1]
    while n > 1
    ar.unshift(0).push(0) # tack a zero on both ends
    yield ar = ar.each_cons(2).map{|a, b| a + b }
    n=n-1
    end
    end
    puts pascal(5){|row| p row}
    ···
    codercai
    codercai
    Jun 17, 2015
    9
    graceful job!
    Vlux
    Vlux
    Jun 17, 2015
    10
    人生苦短。pythonic
    some0ne
    some0ne
    Jun 17, 2015❤️1
    11
    ```ruby

    triangles = Enumerator.new do |yielder|
    a = [1]
    loop do
    yielder << a
    a = ([0] + a).zip(a + [0]).map {|i| i.reduce(:+) }
    end
    end

    triangles.take(10).each {|row| p row }

    ```

    相同功能的ruby版
    Tiande
    Tiande
    OP
    Jun 17, 2015
    12
    @some0ne 连函数名都一样 hhh
    Tiande
    Tiande
    OP
    Jun 17, 2015
    13
    @est 这是啥语言
    (已匍匐在石榴裙下)
    some0ne
    some0ne
    Jun 17, 2015❤️1
    14
    @dtdnqsb 变量名随便起,一样只不过是为了跟LZ的代码对应。你要是不喜欢,我改成 `杨辉三角.take(10)` 怎么样?
    jsyangwenjie
    jsyangwenjie
    Jun 17, 2015❤️1
    15
    这。。
    你随便学一门函数式语言就写得出来的。。
    est
    est
    Jun 17, 2015❤️1
    16
    @dtdnqsb 当然是我大Haskell 。
    luciankaltz
    luciankaltz
    Jun 17, 2015
    17
    Python弱鸡被惊艳到了。。。
    Tiande
    Tiande
    OP
    Jun 17, 2015
    18
    @some0ne 我是说 zip() 不是变量名 hhh
    Tiande
    Tiande
    OP
    Jun 17, 2015
    19
    @jsyangwenjie 你就随便拿顺手的语言写个如此简洁的,让大家活儿好好乐乐?
    没有嘲讽的意思 -。-
    Tiande
    Tiande
    OP
    Jun 17, 2015
    20
    @est 好好好,立马去跪舔
    pubby
    pubby
    Jun 17, 2015 via Android
    21
    坐等PHP版
    ob
    ob
    Jun 17, 2015
    22
    zip里面是啥?
    zonghua
    zonghua
    Jun 17, 2015 via iPhone
    23
    人生苦短,为了排个杨辉三角,耗费了多少脑力。
    jsyangwenjie
    jsyangwenjie
    Jun 17, 2015❤️1
    24
    @dtdnqsb
    yang::Int -> [Int]
    yang n
    | n == 0 = [1]
    | otherwise = map (\x-> fst x + snd x) $ zip ([0] ++ yang (n-1)) (yang (n-1) ++ [0])
    这是人家玩烂了的。。
    lilydjwg
    lilydjwg
    Jun 17, 2015
    25
    @est ^ 是什么操作?我这里报错了。

    PS: 斐波那契数列不是 fibs = scanl (+) 0 (1:fibs) 么 ;-)
    lilydjwg
    lilydjwg
    Jun 17, 2015❤️1
    26
    @est 好像这个更流行: fibs = 0 : 1 : zipWith (+) fibs (tail fibs)
    xuyl
    xuyl
    Jun 17, 2015
    28
    @dtdnqsb 那么这个函数怎么迭代运行呢?求教。都不带参数来着
    horx
    horx
    Jun 17, 2015
    29
    Fibonacci 数列 Elixir 版:
    def fib(n) when n < 1, do: n
    def fib(n), do: fib(n -1) + fib(n - 2)
    horx
    horx
    Jun 17, 2015❤️1
    30
    上门第一行写错了, 是 def fib(n) when n <= 1, do:n
    zerh925
    zerh925
    Jun 17, 2015
    31
    @staticor 对 就是这篇
    karloku
    karloku
    Jun 17, 2015❤️1
    32
    pascal = lambda do |n|
    | n.times.reduce([[1]]) do |rows|
    | rows << ([0] + rows.last).zip(rows.last + [0]).map {|i| i.reduce(&:+)}
    | end
    end
    Tiande
    Tiande
    OP
    Jun 17, 2015
    33
    @xuyl
    # 函数写好后,实例化
    result = triangles()

    i = 1
    for a in result:
    ....i = i + 1
    ....print(a)
    ....if i > 10: # 限定循环次数
    ........break
    Tiande
    Tiande
    OP
    Jun 17, 2015
    34
    @jsyangwenjie
    谢谢,然而并不懂你说的函数式编程...
    msg7086
    msg7086
    Jun 18, 2015❤️1
    35
    4 kyu Pascal's Triangle
    Ruby:

    def pascalsTriangle(n)
    result = p = [1]
    (n-1).times do
    p = (p+[0]).zip([0]+p).map{|v|v.reduce(&:+)}
    result += p
    end
    result
    end
    4 days ago

    前几天刚写过。
    lds56
    lds56
    Jun 18, 2015❤️1
    36
    Scala 版本

    def tri(row:Int):List[Int] = { row match {
    case 1 => List(1)
    case n:Int => List(1) ::: ((tri(n-1) zip tri(n-1).tail) map {case (a,b) => a+b}) ::: List(1)
    }
    }

    def prettytri(n:Int) = (1 to n) foreach {i=>print(" "*(n-i)); tri(i) map (c=>print(c+" ")); println}
    prettytri(5)

    出自 http://rosettacode.org/wiki/Pascal's_triangle
    lds56
    lds56
    Jun 18, 2015
    37
    感觉 python 的生成器还是不够优雅
    xiaoxianyu
    xiaoxianyu
    Jun 18, 2015❤️1
    38
    很美丽~zip原来有这么赞的用法~~~
    dsdshcym
    dsdshcym
    Jun 18, 2015
    39
    @lds56 服
    yuankui
    yuankui
    Jun 18, 2015
    40
    性能堪忧啊...
    yuankui
    yuankui
    Jun 18, 2015
    41
    好多列表的concat
    wizardoz
    wizardoz
    Jun 18, 2015
    42
    @xuyl
    for i,l in zip(range(10),triangles()):
    ....print(l)
    forrestchang
    forrestchang
    Jun 18, 2015❤️1
    43
    刚学Swift, 用Swift写了一个,基本的方法
    func pascalsTriangle(rows: Int) {
    if rows < 0 {
    return
    }

    var last = [Int]()
    last.append(1)
    println(last)

    for i in 1..<rows {
    var thisRow = [Int]()
    thisRow.append(last.first!)
    for j in 1..<i {
    thisRow.append(last[j - 1] + last[j])
    }
    thisRow.append(last.first!)
    last = thisRow
    println(thisRow)
    }

    }
    shizukoto
    shizukoto
    Jun 18, 2015❤️2
    44
    JavaScript (ES6) 实现:

    ```js
    const {zip, sum, map, head} = require('aureooms-js-itertools');

    function *triangles() {
    let a = [1];
    while (true) {
    yield a;
    a = Array.from(map(sum, zip([[0].concat(a), a.concat([0])])));
    }
    }

    for (let row of head(triangles(), 5)) console.log(row.join(' '));

    ```
    Hchan
    Hchan
    Jun 26, 2015❤️1
    45
    lazy val tri: Stream[List[Int]] = List(1) #:: tri map {s => (0 :: (s :+ 0)).sliding(2).toList.map(_.sum)}
    @lds56
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   4785 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 91ms · UTC 07:31 · PVG 15:31 · LAX 23:31 · JFK 02:31
    ♥ Do have faith in what you're doing.