简体   繁体   English

Python中的递归整数分区计算器的未知问题

[英]Unknown issue with recursive integer partition calculator in Python

I'm having some trouble with my recursive program to calculate the number of integer partitions of an integer. 我的递归程序在计算整数的整数分区数时遇到了一些麻烦。

Here's what I have written: 这是我写的:

def p(k, n):
    if k > n:
        return 0
    if k == 1:
        return 1
    else:
        return (p(k+1, n) + p(k, n-k))

def partitions(n):
    ans = 1
    for k in range(1, n/2):
        ans += p(k, n-k)
    return ans

This algorithm is implemented from Wikipedia's article Partition (number theory) . 该算法是从Wikipedia的文章分区(数论)中实现的 Here's what my program outputs for the first few integers: 这是我的程序输出的前几个整数的内容:

partitions(0) = 1
partitions(1) = 1
partitions(2) = 1
partitions(3) = 1
partitions(4) = 2
partitions(5) = 2
partitions(6) = 2
partitions(7) = 2

I'm not sure why my program doesn't operate properly, since I thought I correctly implemented both recursion and the algorithm from Wikipedia. 我不确定为什么我的程序不能正常运行,因为我以为我正确地实现了Wikipedia的递归和算法。 Could somebody help me understand what it's doing? 有人可以帮助我了解它在做什么吗?

You have one of the base cases wrong: 您有一种错误的基本情况:

if k == 1:
    return 1

should be 应该

if k == n:
    return 1

Additionally: 另外:

for k in range(1, n / 2):

should be 应该

for k in range(1, n / 2 + 1):

This is because the sum in the formula is inclusive of the upper bound, but in Python, the range does not include the upper bound. 这是因为公式中的总和包含上限,但在Python中, range不包含上限。 Then: 然后:

print [partitions(i) for i in range(1, 8)]

gives

[1, 2, 3, 5, 7, 11, 15]

matching the values given in the Wikipedia article . 匹配Wikipedia文章中给出的值。

I see two problems: 我看到两个问题:

This: 这个:

if k == 1:

should be if k == n: , and this loop: 应该是if k == n:并且此循环:

for k in range(1, n/2):

should be range(1, n/2+1) -- or better, range(1, n//2+1) to be explicit about the fact we want integer division -- because range in Python doesn't include the upper bound. 应该是range(1, n/2+1) -或更佳的是range(1, n//2+1)可以明确表明我们想要整数除法的事实-因为Python中的range不包括上位界。 After fixing those, I get: 修复这些问题后,我得到:

>>> [partitions(i) for i in range(1,10)]
[1, 2, 3, 5, 7, 11, 15, 22, 30]

(which, you'll notice, only has 9 values. :^) (您会注意到,它只有9个值。:^)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM