【问题标题】:Convert Python partition generator to Java将 Python 分区生成器转换为 Java
【发布时间】:2014-03-29 17:03:04
【问题描述】:

我正在尝试将以下分区生成器从 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

这是不正确的。

【问题讨论】:

  • 对于初学者来说,a[:k + 2] 的意思是“从 a[0] 到 a[k+2] 的所有项目”,但等效的 System.out.print 位于从 a [2] 到 a[k+2]。
  • @Kevin 谢谢你,解决了问题;我已经更新了问题
  • 您应该回答自己的问题,然后将其勾选为已回答,因为它仍然处于打开状态。

标签: java python combinatorics code-conversion


【解决方案1】:

Kevin 的评论引出了答案:

替换

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] );

【讨论】:

    猜你喜欢
    • 2017-06-26
    • 1970-01-01
    • 2023-03-24
    • 1970-01-01
    • 2020-07-09
    • 2011-11-08
    • 2017-05-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多