这个函数应该返回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)
根据交互模式,这应该是step1,step2和step3的结果
>>> 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 :(得分:5)
你有ab和ac指向同一个引用。改变这个:
ab = ac = [None, None]
到此:
ab = [None, None]
ac = [None, None]
答案 1 :(得分:1)
在第ab = ac = [None, None]
行中,您将相同列表分配给变量ab和ac。当你改变一个时,你可以同时改变另一个。
它以交互方式工作的原因是你没有以相同的方式初始化列表。
用你的函数交换函数的第一行:
ab = [None, None]
ac = [None, None]