作为 Interval 类的一部分,我需要将两个间隔的减法定义为
[a,b]−[c,d]=[a−d,b−c]。
如果我们只有一个区间和一个数字(整数或 float ),则减法定义为
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_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])
如果更改 __sub__
方法以删除特定检查,则可以使端点完全鸭子类型
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)
关于python - 区间类 - Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59324431/