def sortFun(a):
return a[1] * 1000 - len(a[0]) # sorts by value and biases by substring length
def method1(inpstr, substrs):
total = 0
while len(inpstr): # infinite loops if the input string isn't completely covered by the substrings
for substring in substrs:
count = inpstr.count(
substring[0]) # there's no replace method that returns the count of replaced functions i think
total = total + count * substring[1]
inpstr = inpstr.replace(substring[0], "")
return total
# This is an idea for if we can only eat from the front of the string.
def method2(inpstr, substrs):
total = 0
while len(inpstr):
idx = 0
for substring in substrs:
idx = inpstr.find(substring[0])
if idx == 0:
total = total + substring[1]
inpstr = inpstr[idx:-1]
break
if idx != 0: # only invalid characters left
break
return total
inputString = "ABCDEBCDE"
substrings = [
["AB", 2],
["ABC", 6],
["CDE", 1],
["CD", 2],
["A", 9],
["B", 16],
["C", 20],
["D", 30]
]
substrings.sort(key=sortFun)
print("method1 result:" + str(method1(inputString, substrings)))
print("method2 result:" + str(method2(inputString, substrings)))