'Newbie to python-- problem on Object Oriented Programming
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])
Solution 1:[1]
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)
Solution 2:[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.)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | JeffUK |
| Solution 2 | chepner |
