Reputation:
I'm trying to write a module that searches for a key string in a target string and outputs the starting points of any matches. I can write an iterative module that achieves this, but I'm attempting to do it with recursion (the tutorial I'm using deals with recursion and iteration in this lesson, so I figure I should try both) and running into some trouble.
def substringmatchrecursive(target, key):
"""returns a tuple of the starting points of matches of the key string in the target string using a recursive function"""
from string import find
position = find(target, key) #position of the match
answer=() #will be outputted
if position == -1:
return 'No match'
else:
while position != 1:
answer = answer + (position, )
position = substringmatchrecursive(target[position+1: ], key)
return answer
loading the module and entering
substringmatchrecursive("fjdkakfjdslkfajfksja", "a")
which should give me a tuple of length 3, instead gives me an error
Traceback (most recent call last):
.....
position = substringmatchrecursive(target[position+1: ], key)
TypeError: cannot concatenate 'str' and 'int' objects
I'd assume that find()
would output an integer, so position+1
should work. What is going on here?
Upvotes: 1
Views: 286
Reputation: 369134
According to following code, substringmatchrecursive
returns str
object ('No match'
) if it does not find a key.
if position == -1:
return 'No match'
And that str
object is assigned to position
:
position = substringmatchrecursive(target[position+1: ], key)
Make the function return a tuple consistently. (a predicate used in the while
loop should be adjusted accordingly, or while
should be gone if you want recursion, ...).
And use different name for position
to avoid name collision.
Upvotes: 3