2009-04-12 257 views
0

這個函數應該返回36,但它返回0。如果我通過邏輯線通過在交互模式下,我得到36代碼在全局範圍內工作,但不在本地範圍內工作?

代碼

from math import * 

line = ((2, 5), (4, -1)) 
point = (6, 11) 

def cross(line, point): 
    #reference: http://www.topcoder.com/tc?module=Static&d1=tutorials&d2=geometry1 
    ab = ac = [None, None] 
    ab[0] = line[1][0] - line[0][0] 
    ab[1] = line[1][1] - line[0][1] 
    print ab 
    ac[0] = point[0] - line[0][0] 
    ac[1] = point[1] - line[0][1] 
    print ac 
    step1 = ab[0] * ac[1] 
    print step1 
    step2 = ab[1] * ac[0] 
    print step2 
    step3 = step1 - step2 
    print step3 
    return float(value) 

cross(line, point) 

輸出

[2, -6] # ab 
[4, 6] #ac 
24  #step 1 (Should be 12) 
24  #step 2 (Should be -24) 
0  #step 3 (Should be 36) 

根據線運行到交互模式,這應該是步驟1,步驟2和步驟3的結果。

>>> ab = [2, -6] 
>>> ac = [4, 6] 
>>> step1 = ab[0] * ac[1] 
>>> step1 
12 
>>> step2 = ab[1] * ac[0] 
>>> step2 
-24 
>>> step3 = step1 - step2 
>>> step3 
36 

(這將是偉大的,如果有人可以給這個好標題)

+0

什麼是價值的價值? :) – WhatIsHeDoing 2009-04-12 22:00:11

+0

這將是`NameError:全球名稱'值'未定義' – epochwolf 2009-04-12 22:04:43

回答

5

你有ab和ac指向相同的參考。更改此:

ab = ac = [None, None] 

這樣:

ab = [None, None] 
ac = [None, None] 
1

在行ab = ac = [None, None],您分配同一列表的變量AB和AC。當你改變一個,你同時改變另一個。

交互式工作的原因是您不以相同的方式初始化列表。

交換你的函數的第一行與此:

ab = [None, None] 
ac = [None, None] 
相關問題