好的,所以我终于开始使用python中的数学,这是(到目前为止)令人惊讶的不像我想象的那么难(我不知道任何微积分,或三角学,只知道基本代数) 。 我试图从头开始创建一个影响二次方程的程序。这是我到目前为止(对不起,如果写得不好):
def factor(arg):
o = arg
n = o
x = 2
factors = [o]
while abs(o) >= x:
if (o) % x == 0:
n = o / x
factors.append(n)
x += 1
else:
x += 1
return factors
A = int(raw_input("What is A in your quadratic equation? A = "))
B = int(raw_input("What is B in your quadratic equation? B = "))
C = int(raw_input("What is C in your quadratic equation? C = "))
Br = abs(B) + abs(A) # Range of B
Bpf = range (-Br, Br + 1) # Possible factors of B
ACpf = factor(A * C) # Possible factors of (A * C)
for i in ABpf:
ACpf.append(-i)
cf = [] # Common factors
for i in Bpf:
for j in ACpf:
if i == j:
cf.append(i)
print cf
我通过终端运行这个脚本,它问我A B和C是什么,然后它冻结了大约30秒。在我打字之后解冻它之后说'杀死'。 有谁知道是什么造成的?我感谢任何答案或建议。
答案 0 :(得分:1)
修改你的代码有点像这样:
def factor(arg):
o = arg
n = o
x = 2
factors = [o]
while abs(o) >= x:
if (o) % x == 0:
n = o / x
factors.append(n)
x += 1
else:
x += 1
return factors
A = int(raw_input("What is A in your quadratic equation? A = "))
B = int(raw_input("What is B in your quadratic equation? B = "))
C = int(raw_input("What is C in your quadratic equation? C = "))
Br = abs(B) + abs(A) # Range of B
Bpf = range (-Br, Br + 1) # Possible factors of B
ABpf = factor(A * C) # Possible factors of (A * C)
ACpf = []
for i in ABpf:
ACpf.append(i)
ACpf.append(-1*i)
cf = [] # Common factors
for i in Bpf:
for j in ACpf:
if i == j:
cf.append(i)
print cf
现在尝试运行它。你应该得到一个结果。
答案 1 :(得分:1)
看起来问题出在以下几行:
ACpf = factor(A * C) # Possible factors of (A * C)
for i in ABpf:
ACpf.append(-i)
请改为尝试:
ACpf = factor(A * C) # Possible factors of (A * C)
for i in ACpf[:]: # Loop over a copy of ACpf
ACpf.append(-i)
[:]表示法用于复制列表。这样可以确保您在循环时不会改变列表(增长它)。
此处还有一点清理factor()的代码:
def factor(arg):
o = arg
factors = [o]
for x in range(2, o+1):
if o % x == 0:
n = o // x
factors.append(n)
return factors