def subStringMatchExact(target, key):
if (target.find(key) == -1):
return []
else:
foundStringAt = [target.find(key)]
target = target[foundStringAt[0] + len(key):]
return foundStringAt + subStringMatchExact(target, key)
string = subStringMatchExact("your code works with wrongly correlated coefficients which incorporates more costs", "co")
print(string)
Current incorrect output:
[5, 22, 9, 19, 14]
I am having trouble summing the length of the substring on the previous recursion step. Like the second element of the list should be 29 instead of 22 as in len(previousSubstring) + len(key) - 1 + len(currentSubstring).
Any ideas to improve my code and/or fix my error too?
The fast way
You don’t have to implement your own solution, its already done! Use the
finditerfunction from theremodule:Your own way
If you want to make your own implementation (using recursion) you could take advantage of the extra arguments of the
str.findfunction. Lets see whathelp(str.find)says about it:There is an extra argument called
startthat tellsstr.findwhere to start searching the substring. That’s just what we need!So, modifying your implementation, we can get a simple, fast and beautiful solution:
What is the recursion doing here?
[].[pos]plus all the positions where the substring will appear in the string starting at positionpos + len(key).Using our brand new function