python - 区间类 - Python

标签 python class intervals

作为 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/

相关文章:

sql - 用于从时间戳中减去时间的 Oracle SQL 查询

python - Python 中的密码测试

python - 从 Bigquery 中读取几行作为辅助输入,得到 None

C++模板化接口(interface)

datetime - f# 中自定义时钟的更好解决方案

algorithm - 不超过覆盖范围限制的最大间隔子集?

python - Flask 测试客户端使用 GET 请求而不是 POST

python - 使用 join() 的方法的空间复杂度

javascript - 如何在同一个 Polymer 元素中扩展多个 mixin?

c++ - 将类转换为结构