【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.