找到具有n个不同部分的整数分区的数量
一个具有
n
不同部分的整数分区是一个降低的积极整数列表,该列表汇总到n
中,其中没有数字超过一次。例如,有3个整数分区为5:
[5],[4,1],[3,2]
。编写一个函数,该函数返回具有
n
不同部分的整数分区的数量,其中1< = n< = 600
。
来源:
”
import itertools
list_poss = [list(i) for j in range(1, n+1) for i in itertools.combinations(range(n+1), j) if sum(list(i)) == n and 0 not in list(i)]
但是它太慢了,并且会产生以下错误:执行时间(12000 ms)
。
如何进一步优化此代码?
An integer partition with distinct parts of
n
is a decreasing list of positive integers which sum ton
, in which no number occurs more than once.For example, there are 3 integer partitions of 5:
[5], [4,1], [3,2]
.Write a function which returns the number of integer partitions with distinct parts of
n
where1 <= n <= 600
.
Source: https://www.codewars.com/kata/6267a007e67fba0058725ad2
I wrote this code:
import itertools
list_poss = [list(i) for j in range(1, n+1) for i in itertools.combinations(range(n+1), j) if sum(list(i)) == n and 0 not in list(i)]
but it is too slow and gives the following error : Execution Timed Out (12000 ms)
.
How can I optimise this code further?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这看起来像是递归的工作。
n
的分区始终具有[n]。然后,对于每个数字k从n-1降低到N的一半(独家),可以用k和n(即NK)的其余部分形成分区:输出:
要查看分区是什么,您可以使用递归生成器编写递归生成器相同的逻辑:
This looks like a job for recursion.
Partitions for
n
will always have [n] on its own. Then for every number k from n-1 down to half of n (exclusively), partitions can be formed with k and the remainder of n (i.e. n-k):output:
To see what the partitions are, you can write a recursive generator using the same logic: