tags:

views:

134

answers:

2

This function should be returning 36 but it returns 0. If I run through the logic line by line in interactive mode I get 36.

Code

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)

Output

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

According to the interactive mode this should be the result of step1, step2, and 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

(It would be great if someone can give this a good title)

+5  A: 

You have ab and ac pointing to the same reference. Change this:

ab = ac = [None, None]

to this:

ab = [None, None]
ac = [None, None]
Eric Palakovich Carr
wow... I've been trying to figure this out for an hour! Silly me. I blame too much C++ lately.
epochwolf
+1  A: 

In the line ab = ac = [None, None], you assign the same list to the variables ab and ac. When you change one, you change the other at the same time.

The reason it works interactively, is that you don't init the lists in the same way.

Swap the first line in your function with this:

ab = [None, None]
ac = [None, None]
Epcylon