gpt4 book ai didi

java - 从 Java 代码转换而来的 Python 错误

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:26:34 24 4
gpt4 key购买 nike

我正在尝试学习 python。因此,我有以下 Java 代码来打印输入数字的因数列表。我正在尝试在 python 中实现相同的逻辑。但是得到一些错误。 java代码如下:

public final class PrintFactors {

private PrintFactors() {}

public static void printFactors(int number) {
if (number <= 0) throw new IllegalArgumentException("The number should be greater than 0.");
printFactorsList(number, number + "*" + 1 + "\n", number);
}

private static void printFactorsList(int dividend, String factorString, int prevDivisor) {

for (int divisor = dividend - 1; divisor >= 2; divisor--) {

if (dividend % divisor != 0)
continue;

if (divisor > prevDivisor)
continue;

int quotient = dividend / divisor;


if (quotient <= divisor) {
if (quotient <= prevDivisor) {
System.out.println(factorString + divisor + "*" + quotient);
}
}
printFactorsList(quotient, factorString + divisor + "*", divisor);
}
}

public static void main(String[] args) {
printFactors(12);
System.out.println();
printFactors(32);
}

以上代码输出结果如下:

 $ java -cp . PrintFactors 32

32 * 1

16 * 2

8 * 4

8 * 2 * 2

4 * 4 * 2

4 * 2 * 2 * 2

2 * 2 * 2 * 2 * 2

我的python代码如下:

def print_factors_list(dividend, factorstring, predivisor):

divisor = dividend - 1
for i in range(int(divisor), 2, -1 ):
if dividend % i != 0:
continue

if divisor > predivisor:
continue

quotient = dividend / divisor


if quotient <= divisor:
if quotient <= predivisor:
print factorstring + str(divisor) + "*" + str(quotient)


print_factors_list(quotient, str(factorstring) + str(divisor) + "*", divisor)


def print_factors(x):
if (x < 0):
print "Enter a positive interger"
else:
print_factors_list(x, str(x) + "*" + str(1) + "\n", x )

num = int(input("Enter a number: "))
print_factors(num)

我收到以下错误:

undefined: Error: local variable 'quotient' referenced before assignment

请有人帮我解决这个我哪里出错了。我将这些步骤实现为 Java 代码是否存在逻辑错误?谢谢。

最佳答案

Python 对缩进敏感。您在最外层的缩进级别进行了 print_factors_list 递归调用,因此它在 for 循环之外。这是与您的 Java 代码不同的行为。

关于java - 从 Java 代码转换而来的 Python 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24644383/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com