之前为了应对数学建模 ,就学了一些数学模型,就比如马尔科夫链。
以下就是我写的简单的马尔科夫链:
python
from typing import Any ,NoReturn
from pprint import pprint
class MarkovChain(object):
CACHE: dict[str : int] = {}
#实现简单的缓存
@classmethod
def cache(cls ,target: Any) -> int|None:
return cls.CACHE[target] if target in list(cls.CACHE) else None
def __init__(self ,string: str) -> NoReturn:
if not isinstance(string ,str) or not string:
return
self.__main_string: str = string
#返回组合
@property
def permutations(self) -> iter:
data_set: set = set(self.__main_string)
return {(e1 ,e2) for e1 in data_set for e2 in data_set}
#计算子字符串的个数
def count_substring(self ,sub_string: str ,count:int = 0b0) -> int:
if sub_string not in self.__main_string:
return 0b0
for index ,each in enumerate(range(len(self.__main_string)) ,start=0):
if self.__main_string[index:index+0b10] == sub_string:
count += 0b1
else:
return count
#返回计算结果
@property
def data(self ,*args: tuple ,**kwargs: dict) -> dict:
data: dict[str : int] = {}
for index ,each in enumerate(self.permutations ,start=0):
sub_name: str = ''.join(each)
data[sub_name]: dict[str : int] = self.count_substring(sub_name)
else:
return data
#计算分母
def denominator(self ,substring: str) -> int:
if (SUM := MarkovChain.cache(substring[0])) is not None:
return SUM
SUM: int = sum([item for index ,(key ,item) in enumerate(self.data.items()) if substring[0]==key[0]])
MarkovChain.CACHE[substring[0]]: dict[str:int] = SUM
return SUM
#返回计算的比例
@property
def percentage(self) -> dict:
return {key:each/self.denominator(key) for index ,(key ,each) in enumerate(self.data.items() ,start=0)}
def main(*args: tuple ,**kwargs: dict) -> NoReturn:
for index ,each in enumerate(args ,start=1):
print(f"{index}:")
chain: MarkovChain = MarkovChain(string_data)
pprint(chain.data)
print()
pprint(chain.percentage)
else:
print("OK!")