1

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?

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks for the swift reply. Why shouldn't I use a while loop in recursion? And what do you mean when you talk about name collision? I can't see where I've assigned 'position' to two different things.
@user3106040, position = find(target, key) <-- int, position = substringmatchrecursive(target[position+1: ], key) <-- tuple or string.
@user3106040, You can use while loop. But it will involves unnecessary duplicated operations.
user3106040: Don't [just] thank @falsetru, accept his answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.