2009-04-12 259 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] 
相关问题