【Python】【双语文献】 Number Interval Realization(数学区间实现方案)

嗟!来食!/Get it!

"""
Author: 灰尘疾客
Blog:   https://www.gkcoll.xyz
"""
import math
from decimal import Decimal

class NumInterval:
    """实现数学的数字区间,用于判断是否包含指定数字等"""

    def __init__(self, open_left: bool = False, left: int | float | Decimal = -math.inf, right: int | float | Decimal = math.inf, open_right: bool = False) -> None:
        self.open_left = open_left
        self.left = left
        self.right = right
        self.open_right = open_right

    def include(self, num):
        if not self.open_left and not self.open_right:return self.left <= num <= self.right
        if not self.open_left and self.open_right:return self.left <= num < self.right
        if self.open_left and self.open_right:return self.left < num < self.right
        if self.open_left and not self.open_right:return self.left < num <= self.right

    def __contains__(self, num):
        return self.include(num)

上述代码基本了 Python 内数字区间需求。

This block of code realized some simple functions of the Number Interval in Python.

至于交集并集补集等内容,可以自写或参考其他人的代码。

If you have need in Intersection/union/complementary set or more, try write it by yourself or refer to other codes.

什么?你需要包括汉字在内的可用列举法直接表示的集合?别扯了!我猜你要的是列表吧!

What? You need the set can list by enumeration method? DO YOU HAVE BRAIN? I think you just need a Python list!

Method

这个类需要传递用于初始化的参数有:区间左端开闭情况、区间头、区间尾、区间右端开闭情况。它们分别需要传入的类型为布尔,数字,数字,布尔。

区间两端的开闭情况指的就是开区间或闭区间。

使用只需要将一个数字区间复制给变量就可以使用:x = NumInterval(True, -8, 5, True)

x.include()

此方法用于返回传入的数字是否在区间内。

This method used for return if the incoming number be included in the Interval or not.

举个栗子,

For example,

x = NumInterval(True, -8, 5, False)  # (-8, 5]
print(x.include(-8))  # False
print(x.include(5))   # True
print(x.include(0))   # True
print(x.include(6))   # False

x.__contains__()

此方法重写(添加)了 NumInterval 对 in 运算符的支持

This method rewrite(add) the in operator for NumInterval.

现在,x 可以用 in 来判断传入的数字是否在区间里了。

Now, x can be use in to judge that if the incoming number in the Interval or not.

print(6 in x)  # False
print(4 in x)  # True

原理:在方法内部调用 include 方法。

Principle: call the include method in it.

版权声明
作者:灰尘疾客
链接:https://www.gkcoll.xyz/451.html
来源:极客藏源
注意:若文章头部无特殊声明,则文章为作者原创,版权归作者所有,未经允许请勿转载(默认允许)。
转载须知:若无特殊说明,本站所有文章均遵循 CC BY-NC-SA 4.0 协议发布,转载、二次创作请遵守该协议内容,并参考以下文案添加转载声明:本文转载自网站 极客藏源 的用户 @灰尘疾客 的文章 《【Python】【双语文献】 Number Interval Realization(数学区间实现方案)》。本转载文发布遵循与原文相同的 CC BY-NC-SA 4.0 协议
THE END
分享
二维码
海报
【Python】【双语文献】 Number Interval Realization(数学区间实现方案)
嗟!来食!/Get it! """ Author: 灰尘疾客 Blog: https://www.gkcoll.xyz """ import math from decimal import Decimal cl……
<<上一篇
下一篇>>