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

2015-06-17 14:42:56 +08:00
 Tiande

来源 (代码在评论中)

代码:

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

10223 次点击
所在节点    Python
45 条回复
pubby
2015-06-17 18:26:49 +08:00
坐等PHP版
ob
2015-06-17 18:41:07 +08:00
zip里面是啥?
zonghua
2015-06-17 18:41:49 +08:00
人生苦短,为了排个杨辉三角,耗费了多少脑力。
jsyangwenjie
2015-06-17 19:08:54 +08:00
@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
2015-06-17 19:14:59 +08:00
@est ^ 是什么操作?我这里报错了。

PS: 斐波那契数列不是 fibs = scanl (+) 0 (1:fibs) 么 ;-)
lilydjwg
2015-06-17 19:15:25 +08:00
@est 好像这个更流行: fibs = 0 : 1 : zipWith (+) fibs (tail fibs)
staticor
2015-06-17 20:53:54 +08:00
xuyl
2015-06-17 21:10:36 +08:00
@dtdnqsb 那么这个函数怎么迭代运行呢?求教。都不带参数来着
horx
2015-06-17 21:11:00 +08:00
Fibonacci 数列 Elixir 版:
def fib(n) when n < 1, do: n
def fib(n), do: fib(n -1) + fib(n - 2)
horx
2015-06-17 21:12:39 +08:00
上门第一行写错了, 是 def fib(n) when n <= 1, do:n
zerh925
2015-06-17 22:21:47 +08:00
@staticor 对 就是这篇
karloku
2015-06-17 23:04:31 +08:00
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
2015-06-17 23:12:55 +08:00
@xuyl
# 函数写好后,实例化
result = triangles()

i = 1
for a in result:
....i = i + 1
....print(a)
....if i > 10: # 限定循环次数
........break
Tiande
2015-06-17 23:21:59 +08:00
@jsyangwenjie
谢谢,然而并不懂你说的函数式编程...
msg7086
2015-06-18 07:32:12 +08:00
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
2015-06-18 10:26:30 +08:00
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
2015-06-18 10:29:00 +08:00
感觉 python 的生成器还是不够优雅
xiaoxianyu
2015-06-18 11:26:35 +08:00
很美丽~zip原来有这么赞的用法~~~
dsdshcym
2015-06-18 14:38:39 +08:00
@lds56
yuankui
2015-06-18 14:56:32 +08:00
性能堪忧啊...

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/199252

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX