0

I have two functions and an array which contains X and Y coordinates. One of the function calculates slope and another function is intended to determine collinearity. There is some weird behavior going on. I apologize if I am missing something clearly obvious.

def slope(list, a, b):

    slope = 0
    #vertical line
    if(list[a][0] == list[b][0]):
        slope = float("inf")
        if(list[a][1] == list[b][1]):
            slope = float("-inf")
    else:
        slope = (list[b][1] - list[a][1])/(list[b][0] - list[a][0])

    return slope

def FastCollinearPoint(list):

    slope_array = list
    #print(slope_array[0][1])

    for i in range(len(list)):
        ss = slope(list, 0 ,i)
        print(ss)
        #slope_array[i][0] = ss

current output -

-inf
2.0
0.5
4.5
2.0
1.0
1.2142857142857142
2.5
:
:

If I uncomment the line slope_array[i][0] = ss, the output becomes -

-inf
-0.0
-0.0
-0.0
-0.0
-0.0
-0.0
-0.0
-0.0
-0.0
0.0
-0.0
-0.0
-0.0
0.0
:
:

I don't understand how the value of the previously calculated variable is changing when I assign it to a new variable. Here is the complete code - https://pastebin.com/SxYjs0jY

Here is the input file mentioned in the link - https://pastebin.com/EMHBWxqT

P.S. - I sincerely apologize in advance if this is a dumb question or something stupid has been done by me.

HARSHIT BAJPAI
  • 361
  • 2
  • 17
  • 2
    It's a really bad idea to use `list` as a variable name in Python, since it will mask the important builtin function of the same name. – Tom Karzes Jun 09 '19 at 16:49
  • 1
    Even though you're passing `list` into the `slope` function, `slope_array[i][0] = ...` still modifies your `list` variable since only a shallow copy is made. And when `i = 0`, your first data point will go all the way up/down at ∞. – TrebledJ Jun 09 '19 at 16:50
  • I'am not much aware of `python` but your `cord` is an `array` and you are using `append` - `cord.append(line)` – random Jun 09 '19 at 16:50
  • @TrebledJ thanks for the help. I got your point . – HARSHIT BAJPAI Jun 09 '19 at 17:07

1 Answers1

0

from comment of @TrebledJ Even though you're passing list into the slope function, slope_array[i][0] = ... still modifies your list variable since only a shallow copy is made. And when i = 0, your first data point will go all the way up/down at ∞

Read python shallow list concepts of python.

HARSHIT BAJPAI
  • 361
  • 2
  • 17