2

I worked on using the slope and the distance formula here. But I think indexing is the wrong approach, or is it?

class Line():
 def __init__(self,coord1,coord2):
 self.coord1 = coord1
 self.coord2 = coord2
 def distance(self):
 return ((coord2[0]-coord1[0])**2 + (coord2[1]-coord1[1])**2)**0.5
 def slope(self):
 return (coord2[1] - coord1[1])/(coord2[0]-coord1[0])
mkrieger1
24.2k7 gold badges68 silver badges84 bronze badges
asked Dec 6, 2021 at 15:13
0

3 Answers 3

5

To access the class specific variables you need to use self.#varibale name So your functions should look like this:

 def distance(self):
 return ((self.coord2[0]-self.coord1[0])**2 + (self.coord2[1]-self.coord1[1])**2)**0.5
 def slope(self):
 return (self.coord2[1] - self.coord1[1])/(self.coord2[0]-self.coord1[0])
answered Dec 6, 2021 at 15:16
Sign up to request clarification or add additional context in comments.

Comments

3

Assuming coord is a tuple I prefer to unpack them first for readability:

def slope(self):
 x1,y1 = self.coord1
 x2,y2 = self.coord2
 return (y2 - y1)/(x2-x1)
answered Dec 6, 2021 at 15:18

Comments

2

There's nothing wrong with indexing. You might find it more readable if you provide more descriptive names for the components. For example,

def distance(self):
 c1x = self.coord1[0]
 c1y = self.coord1[1]
 c2x = self.coord2[0]
 c2y = self.coord2[1]
 return ((c2x - c1x)**2 + (c2y - c1y)**2)**0.5

which you can make less verbose with tuple unpacking:

def distance(self):
 c1x, c1y = self.coord1
 c2x, c2y = self.coord2
 return ((c2x - c1x)**2 + (c2y - c1y)**2)**0.5

and even less verbose by working on the complex plane:

def distance(self):
 return abs(complex(**self.coord2) - complex(**self.coord1))

(For slope, the complex-number trick involves converting the difference between the two to polar coordinates with cmath.polar.)

answered Dec 6, 2021 at 15:19

3 Comments

what is the use of "complex"?
It creates a complex number from the coordinate pair, e.g (3, 0) becomes 3+0j. Since complex numbers can be views as points in the complex plane, the distance between two complex numbers is just the magnitude of the vector defined by two points, which is just the absolute value of the difference of two complex numbers. You basically get the squaring and square root for free.
For example, abs(complex(3,0) - complex(0,4)) == abs(3 - 4j) == 5.0.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.