Python分区功能需要优化

时间:2012-07-30 00:42:45

标签: python optimization data-partitioning

在研究project euler exercise (#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整除。

更新:我最终使用了pentagonal number theorem。我将尝试使用Craig Citro发布的Hardy-Ramanujan渐近公式。

1 个答案:

答案 0 :(得分:1)

我最近没有亲自检查过这个事实,但是“最快的分区算法”的标题可能仍然由Sage的实施保留。您可以在the docs中看到它,或者更好,只需跳到the source code即可。如果您正在寻找有关计算此数字的方法的讨论,那么导致此实现的original thread肯定会很有趣。 source file for the implementation itself首先提供了一些有关代码的有用评论。