2012-04-06 54 views
-5
def partitions(n): 
    # base case of recursion: zero is the sum of the empty list 
    if n == 0: 
     yield [] 
     return 

    # modify partitions of n-1 to form partitions of n 
    for p in partitions(n-1): 
     yield [1] + p 
     if p and (len(p) < 2 or p[1] > p[0]): 
      yield [p[0] + 1] + p[1:] 

说明: 如果您有n个的分区,你可以把它从一个减去减少到n-1的一个典型方式分区分区中最小的项目。例如。 1 + 2 + 3 => 2 + 3,2 + 4 => 1 + 4。这个算法逆过程:对于n-1的每个分区p,它找出n的分区,这个分区将通过这个过程减少到p。因此,在考虑减少n-1的分区的步骤中,n的每个分区只输出一次。算法翻译从蟒蛇PHP或伪代码整数分区

这是在Python中获取数字的所有可能分区的代码。我不擅长Python。如果有人能够将其转化为伪代码(或详细描述)或PHP,我将非常感激。上面的解释在我的脑海里产生了一个疑问:“从分区中的最小项目中减去一个”。我还可以从第二小或其他元素中减去一个。那么,为什么只有最小的?如果有人能够向我解释整个想法,那将是非常感激的。 谢谢。

+2

我不认为你可以只是让人们在这里为你编码。你必须先自己付出一些努力。 – jamylak 2012-04-06 08:50:57

+0

@jamylak我不是要求进入PHP的代码。我也写过伪代码。只是想获得代码。而已!那么你评价它为-1是什么?如果我的名声较低,这并不意味着我所要求或做的无用或愚蠢。 – Sushant 2012-04-06 08:56:14

+0

'partitions(n)'不会返回/为'0'以外的值产生任何值...... – knittl 2012-04-06 09:02:15

回答

2
def partitions(n): 
    # base case of recursion: zero is the sum of the empty list 
    if n == 0: 
     yield [] # yield empty array 
     return # exit function 

    # modify partitions of n-1 to form partitions of n 
    for p in partitions(n-1): # recursive call, get n-1 partitions 
     yield [1] + p # yield array [1, p...] 
     if p and (len(p) < 2 or p[1] > p[0]): # p not empty, and length < 2 or p[1] > p[0] 
      yield [p[0] + 1] + p[1:] # increment first item of p and yield p 

这里是我的尝试(据我所知PHP没有yield,所以它可能表现更差):

function partitions($n) { 
    # base case of recursion: zero is the sum of the empty list 
    if(!$n) return array(array()); # return/"yield" empty array 

    # modify partitions of n-1 to form partitions of n 
    $a = array(); # will hold "yielded" values 
    foreach(partitions($n-1) as $p) { # recursive call 
    $a[] = array_merge(array(1), $p); # "yield" array [1, p...] 
    if($p && (count($p) < 2 || $p[1] > $p[0])) { # p not empty, and length < 2 or p[1] > p[0] 
     ++$p[0]; # increment first item of p 
     $a[] = $p; # "yield" p 
    } 
    } 
    return $a; # return all "yielded" values at once 
} 

(我不能保证任何东西)

+0

该代码实际上不起作用。但我非常感谢你这样做。 – Sushant 2012-04-06 11:02:35

+0

必须完成的编辑是----> if($ n == 1)return array(array(1)); // base case – Sushant 2012-04-06 11:41:04

+0

你说得很对,yield返回数组中的元素,所以'yield []'从数组中返回一个空数组。 'if(!$ n)return array(array())'应该也适用,并且应该适用于所有'n> = 0'的情况。我编辑了我的答案来反映这一点。 – knittl 2012-04-06 12:34:16