Recursion: Suggested Solution is not good

The suggested solution is incorrect.


def search(strings, term, index=0):
    if strings[0] == term:
        return index
    if len(strings) <= 1:
        return -1
    return search(strings[1:], term, index=index+1)

It can easily be broken with the following example:

search_list = ['apple', 'orange', 'pear', 'fig', 'passionfruit']
apple_index = search(search_list, 'apple', index=100)

It will happily return 100, which is incorrect.

I’d suggest this solution:

def search(s, term, index=0):
    index = max(index, 0)
    if len(s) <= index :
        return -1
    if s[index] == term:
        return index
    index += 1
    return search(s, term, index)
1 Like

Hi @irina.gruzinov: please provide a question link as per these guidelines . In addition, use the in-built tags or create a new one here instead of putting it in the heading.

I have also recategorized your topic.

I tried many times, the tag didn’t stick in the tag window. I use Chrome in Ubuntu.