python中的欧拉五边形数函数


max = 200
max=max+2 ### due to the later code, it got offset by 2
P = [0]*max ### make a list of zeros, length max
P[0] = 1
P[1] = 1
print 0,":", P[0] ### print value for n = 0,1
print 1,":", P[1]
Psign = [0]*max ### make a list the same length as P, to store the signs
### apply Euler's pentagonal numbers formula
k = 1
index= k*(3*k-1)/2
while index <=max:
    Psign[index] = (-1)**k
    index = k*(3*k+1)/2
    if index<=max:
        Psign[index] = (-1)**k
    k=k+1
    index = k*(3*k-1)/2

for n in range(1,max+1):
    n=n+1
    P[n] = 0
    for i in range(0,n+1):
        i=i+1
        P[n] = P[n] - P[n-i]*Psign[i]
    print n,":",P[n]

所以我有这段代码,它可以回答 n 的分区数(目前最多 200 个(。但是,由于我从这里改编了用 Mathematica 编写的代码。我不太确定后面的部分。不知何故,这部分搞砸了我的极限。因此,如果我想生成 25 个分区数,则必须将 max 变量设置为 27。

真的希望有人能帮助我纠正这个问题

干杯

亚历克斯

Python 的列表索引是从 0 开始的,因此,例如,长度n列表可以通过 0 到 n-1(含(中的整数进行索引。 它不能n 编制索引。 所以从这里开始:

P = [0]*max ### make a list of zeros, length max

您想稍后引用P[max],但列表太短(按 1(。 所以改为:

P = [0] * (max + 1)

您还需要类似地进行更改:

Psign = [0]*max ### make a list the same length as P, to store the signs

自:

Psign = [0] * (max + 1)

接下来看看:

for n in range(1,max+1):
    n=n+1

这很奇怪 - 直接迭代您想要的值。 就像将这些行替换为:

for n in range(2, max + 1):

接下来又重复了同样的奇怪事情:

    for i in range(0,n+1):
        i=i+1

同样,将其替换为直接迭代所需的i值:

    for i in range(n+1):

最后,摆脱:

max=max+2 ### due to the later code, it got offset by 2

在顶部。 这只是隐藏了一些(不是全部(使列表太小而无法开始的后果。

完成所有这些更改后,程序对我来说运行良好,以最终输出正常结束:

200 : 3972999029388

所以你把所有困难的部分都做对了! 你只是搞砸了简单的部分 - 大声笑;-( 干得好。

另一个功能

只是为了感兴趣,我将包括我为此使用的函数。 虽然它看起来完全不同,但它实际上是相同的方法,以各种方式"优化"。 享受 :-(

def p4(n, _p=[1]):
    "Number of partitions of n."
    from math import sqrt
    def inner(n, _p=_p):
        k = int((sqrt(24*n+1)-1.) / 6.) + 1
        negative = not (k & 1)
        i = n - (k*(3*k+1) >> 1)
        assert i < 0
        s = 0
        if i + k >= 0:
            s = _p[i+k]
            if negative:
                s = -s
        assert i + 3*k - 1 >= 0
        for k in xrange(k-1, 0, -1):
            i += 3*k + 2
            negative = not negative
            t = _p[i] + _p[i + k]
            if negative:
                t = -t
            s += t
        assert i+k == n-1
        _p[n] = s
    if n < 0:
        raise ValueError("argument must be >= 0")
    oldlen = len(_p)
    if n >= oldlen:
        _p.extend([None] * (n - oldlen + 1))
        for nn in xrange(oldlen, n+1):
            inner(nn)
    return _p[n]

然后,例如,

>>> p4(200)
3972999029388L

最新更新