2012-04-06 75 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