맞춤형 숫자 시스템의 수를위한 스위스-무아 나이프.
Evgueni Antonov 2023.
이 모듈은 Python 3.10.6, PIP 23.1.2에서 생성 및 테스트되었습니다.
2023 년 5 월에 처음 출판되었습니다.
pip3 install custom-numbers
# or
python3 -m pip install custom-numbers
사용 방법에 대한 자세한 내용은 아래 사용 섹션을 참조하십시오.
from custom_numbers import custom_numbers as cn
my_custom_numeral_system = cn.CustomNumeralSystem("paf")
my_number = cn.CustomNumber(my_custom_numeral_system, "a")
# Now if you type in REPL:
# help(cn)
# You will get the help for the module and the classes.
이 패키지에는 사용자 정의 기호로 만든 사용자 정의 숫자 시스템을 선언하는 데 도움이되는 클래스가 거의없는 하나의 모듈이 포함되어 있습니다. 이것은 이상하게 들릴 수 있으므로 실제로 이것은 모습입니다.
참고 : 서브 시스템은 지원되지 않으며이 기능을 구현할 계획이 없습니다.
참고 :이 모듈은 사용자 지정 정수 번호 만 지원합니다. 맞춤 플로팅 포인트 번호는 지원되지 않으며 결코 그렇지 않습니다.
이미 알고있는 것 - 이진수부터 시작합시다. 이것들은 0으로 만들어졌으며, 따라서베이스는 2입니다.
예 : 1100101
그리고 이것은 실제로 90 년대의 정말 멋진 노래의 제목입니다. 또한 1100101 바이너리, 소수점으로 변환 됩니다 .
이제 - 16 진수 - 이것들은 숫자 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 숫자로 만들어졌으며 문자 A, B, C, D, E, F는 16입니다.
따라서 16 진수는 다음과 같습니다.
F 16 == 15 10 , 10 16 == 16 10 , f0 16 == 240 10
잘 알려진 다른 숫자 시스템은 옥탈 시스템이며, 0에서 7 및 기본 8의 숫자만으로 구성되지만 지금은이 건너 뛰게됩니다.
그리고 마지막으로 어린 시절부터 우리 모두가 알고있는 소수 시스템은 10의 기초를 가지고 있으며 0에서 9의 숫자로 만들어졌습니다.
좋아, 지금까지 당신은 가장 널리 사용되는 숫자 시스템 (이진, 옥탈, 소수점 및 16 진수)에 익숙합니다.
이진 시스템을 다시 정의하는 것으로 시작하겠습니다. 그래서 그것은 2의 밑면을 가지고 있으며 우리는 그것을 바꾸지 않을 것입니다. 그러나 0과 1을 사용하여 p와 a를 사용하는 대신 어떻습니까? 그래서 P는 우리의 새로운 Zero이고 A는 우리의 새로운 0이 될 것입니다. 따라서 우리가 일반적으로 1100101을 쓸 때 이것은 이제 Aappapa 로 작성되었습니다. 혼란 스럽습니까? 그러나 무엇이 - 그것은 여전히 이진 시스템이며, 우리는 단지 기호를 변경했습니다.
그러나 이제는 기호 P, A, F를 숫자로 사용하여 3 인 숫자 시스템 인 Frazier는 어떻습니까? 따라서 F 는 10 진수, P는 10 진수입니다. 그러므로:
AA 3 == 4 10 , AF 3 == 5 10 , FP 3 == 6 10
이제 이것을 실제로 보자 :
from custom_numbers import custom_numbers as cn
sys3 = cn.CustomNumeralSystem("paf")
num3 = cn.CustomNumber(sys3, "aa")
num10 = num3.to_decimal()
print(num10) # Prints "4"
클래스가 예상대로 작동하는지 테스트하는 가장 좋은 방법은 우리 모두가 알고있는 기호로 숫자 시스템을 선언하는 것입니다.
from custom_numbers import custom_numbers as cn
sys2 = cn.CustomNumeralSystem("01")
num2 = cn.CustomNumber(sys2, "1100101")
num10 = num2.to_decimal()
print(num10) # Prints "101"
sys16 = cn.CustomNumeralSystem("0123456789abcdef")
num16 = cn.CustomNumber(sys16, "f0")
num10 = num16.to_decimal()
print(num10) # Prints "240"
지금까지 너무 좋아. 이제 완전히 견과류로 가서 16보다 기본 화자가있는 시스템과 숫자를위한 완전히 이상한 기호 세트를 선언합시다. 그리고 우리는 실제로 그렇게 할 수 있습니다.
sysN = cn.CustomNumeralSystem("kje5nCs21Q9vW0KMqc")
참고 : 사용자 정의 번호는 사례에 민감합니다 !! 그래서 n! = n !!
참고 : 숫자 시스템에서 사용할 수없고 숫자로 사용할 수없는 금지 된 문자가 있습니다. CustomNumeralsystem 클래스의 Forbidden_characters 속성을 사용하여 항상 문자열로 얻을 수 있습니다.
CustomNumeralSystem 클래스에서 기본 검증의 요구에 대한 평등 및 IEMPYINCY PYTHON 연산자가 구현되었으므로 두 객체를 비교할 수 있습니다.
그러나 비교는 표준 Python 객체 (참조) 비교가 아닌 숫자를 나타내는 문자의 목록 (기본적으로 문자열)에 의해 이루어집니다.
sys1 = cn.CustomNumeralSystem("paf")
sys2 = cn.CustomNumeralSystem("paf")
# The two objects are different, despite being initialized with
# the same value
id(sys1) == id(sys2) # False
# However the set of characters (the digits) is the same, the
# base is the same, so I accept they are the same numeral systems
sys1 == sys2 # True
# And you could also test for inequality
sys1 = cn.CustomNumeralSystem("paf")
sys2 = cn.CustomNumeralSystem("paz")
sys1 != sys2 # True
서명 된 사용자 정의 번호도 지원됩니다.
sysN = cn.CustomNumeralSystem("paf")
numN1 = cn.CustomNumber(sysN, "-a") # A negative number
numN2 = cn.CustomNumber(sysN, "a") # A positive number
numN3 = cn.CustomNumber(sysN, "+a") # A positive number
기본 수학 작업은 Trough 표준 파이썬 연산자가 지원됩니다.
sysN = cn.CustomNumeralSystem("paf")
numN1 = cn.CustomNumber(sysN, "-a")
numN2 = cn.CustomNumber(sysN, "a")
numN3 = cn.CustomNumber(sysN, "+a")
# Comparisson
numN1 == numN2
numN1 != numN2
numN1 > numN2
numN1 < numN2
numN1 >= numN2
numN1 <= numN2
# Basic mathematical operations
numN1 + numN2 # Addition
numN1 += numN2 # Augmented addition
numN1 - numN2 # Subtraction
numN1 -= numN2 # Augmented subtraction
numN1 // numN2 # Floor division
numN1 / numN2 # NOTE: This will perform floor division as well!
# as floating point numbers are not supported by this class and will
# never be.
numN1 * numN2 # Multiplication
numN1 ** numN2 # Power
numN1 % numN2 # Modulo division
abs(numN) # Absolute value
반복자 사용 :
sysN = cn.CustomNumeralSystem("paf")
it = cn.GearIterator(sysN, 0, 2)
next(it) # "p" # "p" assumes to be the analog of the zero
next(it) # "a"
next(it) # "f"
next(it) # "ap"
next(it) # "aa"
# and so on. You get the idea.
# The iterator could also be initialized with an init_value which is
# de-facto a custom number from the chosen CustomNumeralSystem,
# but for convenience I left the number to be a string, as you may
# wish or not to initialize at all:
it = cn.GearIterator(sysN, 0, 2, "af")
참고 : 초기화되면 반복자는 주어진 init_value에서 선행 "제로"(따라서 말하기)를 제거합니다.
사용자 정의 숫자 시스템을 정의하고 선언합니다.
CustomNumeralSystem(digits: str)
Args:
digits: The symbols to be used as digits. The string length defines
the numeral system base.
속성:
forbidden_characters -> str
base -> int
행동 양식:
valid_number(number: str) -> bool
Tests if the given "number" is valid for the current numeral system.
Should not contain forbidden characters.
Should contain only characters defined in the numeral system.
사용자 정의 숫자 시스템에서 숫자를 정의하고 선언합니다.
CustomNumber(numeral_system: CustomNumeralSystem, value: str)
Args:
numeral_system: A previously defined custom numeral system.
value: The value (the number itself).
속성:
init_value -> str
Returns the initial value the class was initialized with.
행동 양식:
digit_to_int(digit: str) -> int
Converts the given digit from the custom numeral system to a
decimal integer.
to_decimal() -> int
Converts the current number value to a decimal integer.
첫 번째 숫자 (제로 해당)에서 시작하거나 주어진 init_value에서 시작하는 사용자 정의 숫자 시스템 eiter의 수를 반복합니다.
오래된 자동차 주행 거리계와 같이 오래된 기어 카운터를 간단히 시뮬레이션합니다.
GearIterator(numeral_system: CustomNumeralSystem, min_length: int = 0, max_length: int = 0, init_value: str = "")
Args:
numeral_system: Custom numeral system. Mind the order of symbols!
min_length: Minimum length, default is zero.
max_length: Maximum length, default is zero - means no limit.
init_value: Value to initialize with.
속성:
combinations -> int
Returns the number of possible combinations (iterations).
이 클래스는 Python 컨텍스트 관리 프로토콜을 구현합니다.