【发布时间】:2019-01-25 04:46:48
【问题描述】:
我正在尝试为数字生成整数分区,并偶然发现了this,它看起来非常简洁和优雅:
def partitions(n):
# base case of recursion: zero is the sum of the empty list
if n == 0:
yield []
return
# modify partitions of n-1 to form partitions of n
for p in partitions(n-1):
yield [1] + p
if p and (len(p) < 2 or p[1] > p[0]):
yield [p[0] + 1] + p[1:]
因此,我尝试将其转换为 Clojure,但失败了:
(defn- partitions [n]
(if (zero? n) []
(for [p (partitions (dec n))]
(let [res [(concat [1] p)]]
(if (and (not (empty? p))
(or (< (count p) 2) (> (second p) (first p))))
(conj res (into [(inc (first p))] (subvec p 1)))
res)))))
^^ 上面写错了。例如:
eul=> (partitions 4)
()
我应该考虑惰性序列吗?
我在推理 python 代码时遇到了麻烦,到目前为止我尝试转换它的尝试都失败了。感谢任何帮助我弄清楚如何做到这一点。
【问题讨论】:
标签: clojure