def calculateScore(text, prefixString, suffixString):
result = {}
lenText = len(text)
while lenText > 0:
for i in range(len(text) + 1 - lenText):
substring = text[i:i + lenText]
# calc the pre_text_pattern_score
pre_text_pattern_score = min(len(prefixString), len(substring))
while pre_text_pattern_score > 0 and substring[:pre_text_pattern_score] != prefixString[-pre_text_pattern_score:]:
pre_text_pattern_score -= 1
# calc the post_text_pattern_score
post_text_pattern_score = min(len(suffixString), len(substring))
while post_text_pattern_score > 0 and substring[-post_text_pattern_score:] != suffixString[:post_text_pattern_score]:
post_text_pattern_score-= 1
# calculate the pattern_score
pattern_score = pre_text_pattern_score + post_text_pattern_score
if not pattern_score in result:
# resets the dictionary key
result[pattern_score] = []
result[pattern_score].append(substring)
lenText -= 1 # reduce lenText by 1
# store the highest key, so we can sort the right item to return
maximum_pattern_score = max(result.keys())
# make sure to sort the lexicographically lowest string of the highest key
result[maximum_pattern_score].sort()
# return the lexicographically highest key
return result[maximum_pattern_score][0]