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

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

10239 次点击
所在节点    Python
45 条回复
yuankui
2015-06-18 14:56:56 +08:00
好多列表的concat
wizardoz
2015-06-18 14:57:30 +08:00
@xuyl
for i,l in zip(range(10),triangles()):
....print(l)
forrestchang
2015-06-18 15:16:59 +08:00
刚学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
2015-06-18 23:20:02 +08:00
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
2015-06-26 17:12:38 +08:00
lazy val tri: Stream[List[Int]] = List(1) #:: tri map {s => (0 :: (s :+ 0)).sliding(2).toList.map(_.sum)}
@lds56

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

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

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

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

© 2021 V2EX