区间类-Python
作为类间隔的一部分,我需要将两个间隔的减法定义为 [甲,乙]−[c,d]=[a−d、 b−c] 如果我们只有一个区间和一个数字(整数或浮点),那么减法定义为 1-区间(4,5)=[-3,-4]和区间(4,5)-1=[3,4] 这是我的代码:区间类-Python,python,class,intervals,Python,Class,Intervals,作为类间隔的一部分,我需要将两个间隔的减法定义为 [甲,乙]−[c,d]=[a−d、 b−c] 如果我们只有一个区间和一个数字(整数或浮点),那么减法定义为 1-区间(4,5)=[-3,-4]和区间(4,5)-1=[3,4] 这是我的代码: def __sub__ (self, other): if isinstance (other, Interval): return Interval (self.left_point - other.right_p
def __sub__ (self, other):
if isinstance (other, Interval):
return Interval (self.left_point - other.right_point, self.right_point - other.left_point)
elif isinstance (other, (int, float)):
return Interval (self.left_point - other, self.right_point - other)
else:
raise TypeError ('Wrong type!')
def __rsub__ (self, other):
return Interval(other - self.left_point, other - self.right_point)
代码工作得很好,但问题是当我有例如1-Interval(4,5)=[-3,-4]时,我希望它返回[-4,-3],这只是困扰我的顺序
你能给我一个提示吗?
谢谢你抽出时间 您始终可以对端点进行排序:
def __init__(self, start, end):
self.left, self.right = sorted([start, end])
如果更改\uuuu sub\uuuu
方法以删除特定检查,则可以使端点完全类型化
def __sub__ (self, other):
if isinstance (other, Interval):
return Interval (self.left_point - other.right_point, self.right_point - other.left_point)
else:
return Interval (self.left_point - other, self.right_point - other)
始终可以对端点进行排序:
def __init__(self, start, end):
self.left, self.right = sorted([start, end])
如果更改\uuuu sub\uuuu
方法以删除特定检查,则可以使端点完全类型化
def __sub__ (self, other):
if isinstance (other, Interval):
return Interval (self.left_point - other.right_point, self.right_point - other.left_point)
else:
return Interval (self.left_point - other, self.right_point - other)
使用参数翻转将rsub定义为sub或定义一个否定运算符如果两个端点的顺序不正确,您可能希望让您的
\uuu init\uuu()
交换它们-这将捕获此情况以及任何其他类似情况(以及用户只是以错误的顺序给出参数)。使用翻转的参数将rsub定义为sub或定义一个求反运算符。如果两个端点的顺序不正确,您可能希望让您的\uuu init\uuu()
交换它们-这将捕获此情况以及任何其他类似情况(以及用户只是以错误的顺序给出参数)。@Haus。请在问题中加上这个。在一张纸上几乎看不清comment@Haus. 请使用此信息编辑您的问题。不要试图在注释中发布多行代码。问题下方有一个编辑链接。当你高兴的时候打我done@Haus. 别忘了包括对确切错误的描述。我已经将它添加到我的init方法中,现在它似乎工作得很好``self.left\u point,self.right\u point=sorted([left\u point,args[0]])```。多谢各位@豪斯。我不确定通信在哪里失败。请停止在评论中发布代码。用这个question@Haus. 请在问题中加上这个。在一张纸上几乎看不清comment@Haus. 请使用此信息编辑您的问题。不要试图在注释中发布多行代码。问题下方有一个编辑链接。当你高兴的时候打我done@Haus. 别忘了包括对确切错误的描述。我已经将它添加到我的init方法中,现在它似乎工作得很好``self.left\u point,self.right\u point=sorted([left\u point,args[0]])```。多谢各位@豪斯。我不确定通信在哪里失败。请停止在评论中发布代码。用这个来回答问题