class Line:
'''Fields: slope(anyof Int Float "undefined"), intercept (anyof Int Float)
'''
def __init__(self,slope,intercept):
self.slope = slope
self.intercept = intercept
def __repr__(self):
s1 = "Y = {0:.2f}X + {1:.2f}"
s2 = "X = {0:.2f}"
s3 = "Y = {0:.2f}"
if self.slope=="undefined":
return s2.format(self.intercept)
elif self.slope==0:
return s3.format(self.intercept)
else:
return s1.format(self.slope, self.intercept)
def __eq__(self, other):
return type(other) == type(self) and self.slope == other.slope and \
self.intercept == other.intercept
def intersect(self, other):
'''
intersect(self,other) return a list that contains two points that
represent the intersection of the two lines. False is returned if the
line are parallel or equal.
intersect: Line((anyof Int Str Float),(anyof Float Int)
Line((anyof Int Str Float),(anyof Float Int)
-> (anyof Bool (listof (anyof Int Float) (anyof Int Float)))
Examples:
L1 = Line(1,3)
L2 = Line(-1,3)
L1.intersect(L2) => [0,3]
L1 = Line(1,3)
L2 = Line(1,3)
L1.intersect(L2) => False
'''
if self.slope == other.slope:
return False
if self.slope == 0:
if other.slope == 'undefined':
return [other.intersect,self.intersect]
if other.slope == 0:
if self.slope == 'undefined':
return [self.intersect,other.intersect]
if self.slope == 'undefined':
x = self.intersect
y = (other.slope * x) + other.intersect
return [x,y]
if other.slope == 'undefined':
x = other.intersect
y = (self.slope * x) + self.intersect
return [x,y]
if self.slope != other.slope:
x = (other.intersect - self.intersect)/(self.slope - other.slope)
y = (self.slope * x) + self.intersect
return[x,y]
L5 = Line(1,10)
L6 = Line(0,5)
L5.intersect(L6)
我一直遇到此错误:
builtins.TypeError: unsupported operand type(s) for -: 'method' and 'method'
请帮助
答案 0 :(得分:2)
我认为您想做的是:
最后一次,如果不是相交(实际上是一种方法),您将减去截距,这是一个值。
否?
if self.slope != other.slope:
x = (other.intercept - self.intercept)/(self.slope - other.slope)
y = (self.slope * x) + self.intercept
return[x,y]