Problem
The maximum common string of the two strings
The workaround
First get the maximum number of characters to match the two strings
Then get the comparison of the two strings of the side and the main string respectively what is
Character matching is compared to the characters in it
Character matching is compared to the characters in it
Code implementation
- Encapsulate Error
class NoneError(Exception):
def __str__(self):
return f"The parameters participating in the operation cannot be empty, please check the parameter values"
Function: String parameters that participate in the operation cannot be empty
The function code
class get_Same_String:
def __init__(self, str1=None, str2=None):
self.__str1__ = str1
self.__str2__ = str2
self._get_max_len = 0
self._get_example = None
self._get_other = None
@property
def __Str1__(self):
return self.__str1__
@__Str1__.setter
def __Str1__(self, Set_Str1):
self.__str1__ = Set_Str1
@property
def __Str2__(self):
return self.__str2__
@__Str2__.setter
def __Str2__(self, Set_Str2):
self.__str2__ = Set_Str2
@property
def getLCString(self):
return self.__get_LCString__()
def __str_Nome_Error__(self):
"""
:return String parameters that participate in the operation cannot be empty 进行参与运算的字符串参数不能为空
"""
if not all([self.__str1__, self.__str2__]):
raise NoneError
def __max_len__(self):
"""
:return The maximum lookup range 最大查找范围
"""
return len(self.__str1__) if len(self.__str1__) < len(self.__str2__) else len(self.__str2__)
def __example__(self):
"""
:return:The main string for comparison 进行比较的主字符串
"""
return self.__str1__ if len(self.__str1__) < len(self.__str2__) else self.__str2__
def __other__(self):
"""
:return The substring for comparison 进行比较的副字符串
"""
return self.__str2__ if self.__str1__ == self._get_example else self.__str1__
def __get_LCString__(self):
self.__str_Nome_Error__()
self._get_max_len = self.__max_len__()
self._get_example = self.__example__()
self._get_other = self.__other__()
for _i in range(self._get_max_len):
for _j in range(self._get_max_len, 0, -1):
if self._get_other.find(self._get_example[_i: _j]) != -1:
return self._get_example[_i: _j]
- Code testing
if __name__ == '__main__': new_getLCString = get_Same_String('abcdef', "bcdef") print(new_getLCString.getLCString) new_getLCString = get_Same_String(None, "bcdef") print(new_getLCString.getLCString)
The result of the operation
bcdef __main__.NoneError: The parameters participating in the operation cannot be empty, please check the parameter values