我试图为一个数字生成整数分区,但偶然发现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代码时遇到麻烦,到目前为止,我对其进行转换的尝试均失败了。感谢我对解决方法的帮助。
答案 0 :(得分:1)
Tupelo库具有Python [INFO] Installing C:\Program Files (x86)\Jenkins\workspace\helloworld-rest-app-build\pom.xml to C:\Windows\system32\config\systemprofile\.m2\repository\com\example\helloworld-rest-app\0.0.1-SNAPSHOT\helloworld-rest-app-0.0.1-SNAPSHOT.pom
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 3.991 s
[INFO] Finished at: 2019-01-25T00:11:10-05:00
[INFO] ------------------------------------------------------------------------
[Pipeline] bat
C:\Program Files (x86)\Jenkins\workspace\helloworld-rest-app-build>scp -i C:\Users\Nital\.ssh\LightsailDefaultKey-us-east-1.pem target\hellworld-rest-app.jar ec2-user@35.175.125.176:/home/ec2-user/app-deploys
'scp' is not recognized as an internal or external command,
operable program or batch file.
[Pipeline] }
[Pipeline] // script
[Pipeline] }
[Pipeline] // withEnv
[Pipeline] }
[Pipeline] // stage
[Pipeline] }
[Pipeline] // withEnv
[Pipeline] }
[Pipeline] // withEnv
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
ERROR: script returned exit code 1
Finished: FAILURE
函数的实现。这是翻译:
yield
答案 1 :(得分:1)
由于分区的活动端位于最前面,因此它最好是列表而不是向量。这简化了代码的末端。
否则,坚持使用您的结构,在Clojure中,我们会得到类似...
(defn partitions [n]
(if (zero? n)
'(())
(apply concat
(for [p (partitions (dec n))]
(let [res [(cons 1 p)]]
(if (and (not (empty? p))
(or (< (count p) 2) (> (second p) (first p))))
(conj res (cons (inc (first p)) (rest p)))
res))))))
有效:
=> (partitions 4)
((1 1 1 1) (1 1 2) (2 2) (1 3) (4))
您哪里出错了?您无法正确解开yield
。
for
返回一个由一个或两个分区组成的向量序列。您
必须将它们串联成一个序列。有一些小的改进要进行,但是我放弃了它们,而是更贴近您的代码。