2011-10-27 221 views
2

好吧,所以我終於開始使用python的數學了,這是(迄今)令人驚訝的沒有我想象的那麼難(我不知道任何微積分或三角函數,只知道基本代數)。 我正在試圖創建一個從頭開始的因子二次方程。以下是我迄今爲止(如果它寫對不起很差):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秒。當它在我輸入的內容之下解凍後,它說'已殺死'。 有誰知道是什麼原因造成的?我感謝任何答案或建議。

+1

你運行這個你自己的電腦上或在一個工作/學校?這聽起來像是你在共享機器上運行了你的CPU配額。 – kindall

+4

你應該學習三角函數的第一件事是如何拼寫它:-) – paxdiablo

+2

快速簡單地分解二次方程是一個解決的問題。 Python甚至支持複雜的根。 –

回答

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 

現在試着運行它。你應該得到一個結果。

+0

感謝您的幫助,我很感激。 – BLUC

+0

'if(o)%x == 0:'最好寫成'如果不是o%x:' –

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) 

的[:]符號用於複製的清單。這可以確保在循環時不會改變列表(增加它)。

而且這裏是代碼的一點點清理的因素():

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