![](/img/trans.png)
[英]python solution in codewars could not pass time limit, needs optimization
[英]Python partitioning function needs optimization
在研究项目欧拉练习(#78)时 ,我了解到,为了对数字进行分区,您可以创建幂级数。 从该系列中,您可以扩展并使用项系数来获取划分特定数字的方法的数量。
从那里,我创建了这个小函数:
## I've included two arguments, 'lim' for the number you wish to partition and 'ways' a list of numbers you can use to partition that number 'lim'. ##
def stack(lim,ways):
## create a list of length of 'lim' filled with 0's. ##
posi = [0] * (lim + 1)
## allow the posi[0] to be 1 ##
posi[0] = 1
## double loop -- with the amount of 'ways'. ##
for i in ways:
for k in range(i, lim + 1):
posi[k] += posi[k - i]
## return the 'lim' numbered from the list which will be the 'lim' coefficient. ##
return posi[lim]
>>> stack(100,[1,5,10,25,50,100])
>>> 293
>>> stack(100,range(1,100))
>>> 190569291
>>> stack(10000,range(1,10000))
>>> 36167251325636293988820471890953695495016030339315650422081868605887952568754066420592310556052906916435143L
这在相对较小的分区上运行良好,但没有进行此练习。 有没有办法通过递归或更快的算法来加快速度? 我读过一些地方,也可以使用五角形数来帮助进行分区。
现在,我不需要返回有关此问题的实际数字,但是,请检查该数字是否可以被1000000整除。
更新:我最终使用了五角数定理 。 我将尝试使用Craig Citro发布的Hardy-Ramanujan渐近公式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.