2014-02-26 25 views
3

我想下面的分區發生器在Python轉換成Java和沒有得到預期的結果:轉換Python的分區生成到Java

的Python:

def accelAsc(n): 
    a = [0 for i in range(n + 1)] 
    k = 1 
    a[0] = 0 
    y = n - 1 
    while k != 0: 
     x = a[k - 1] + 1 
     k -= 1 
     while 2*x <= y: 
      a[k] = x 
      y -= x 
      k += 1 
     l = k + 1 
     while x <= y: 
      a[k] = x 
      a[l] = y 
      yield a[:k + 2] 
      x += 1 
      y -= 1 
     a[k] = x + y 
     y = x + y - 1 
     yield a[:k + 1] 

我的Java:

public static void partition(int n){ 
    int[] a = new int[ n + 1 ]; 
    int k = 1; 
    int y = n - 1; 
    while(k != 0){ 
     int x = a[k - 1] + 1; 
     k -= 1; 
     while(2*x <= y){ 
      a[k] = x; 
      y -= x; 
      k += 1; 
     } 
     int l = k + 1; 
     while(x <= y){ 
      a[k] = x; 
      a[l] = y; 
      for(int xValue = 0; xValue <= k; xValue++) System.out.print(a[xValue + 2]); 
      System.out.println(); 
      x += 1; 
      y -= 1; 
     } 
     a[k] = x + y; 
     y = x + y - 1; 
     for(int xValue = 0; xValue <= k; xValue++) System.out.print(a[xValue + 1]); 
     System.out.println(); 
    } 
} 

使用參數5調用此參數會導致以下打印輸出:

1110 
1121 
132 
22 
42 
2 
3 

這是不正確的。

+5

對於初學者來說,一個'[:K + 2]'裝置,但你是System.out.print等效爲 「從[0]到A [K + 2]的所有項目」在從[2]到[k + 2]的for循環中。 – Kevin

+0

@凱文謝謝你,解決了這個問題;我已更新問題 –

+5

你應該回答你自己的問題,然後檢查它的答案,因爲它仍然是開放的。 – GenericJam

回答

0

凱文的評論導致了答案:

更換

for(int xValue = 0; xValue <= k; xValue++) System.out.print(a[xValue + 2]); 

for(int xValue = 0; xValue < k + 2; xValue++) System.out.print(a[xValue]); 

更換

for(int xValue = 0; xValue <= k; xValue++) System.out.print(a[xValue + 1]); 

for(int xValue = 0; xValue < k + 1; xValue++) System.out.print(a[xValue]);