'checking the existence of a string in another string using recursive function

I wanna write a program that checks the existence of a string in another string using recursive function (not allowed to use any method such as in , find etc.

I've written that like this :

def intersection(str1, str2):
        if str2 in str1:
            print('yes')
        else:
            print('no')

        intersection(str1, str2)

intersection('abcd abs', 'abs')

this code runs too much how can i fix this problem .

by the way, i have to write it recursively and not allowed to use any set method or string method that checks the input strings automatically.



Solution 1:[1]

For recursion, you need a base case and recursion part (which usually involves reducing the problem).

def is_substring(str1, str2):
    if len(str1) < len(str2):
        return False
    return str1[:len(str2)] == str2 or is_substring(str1[1:], str2)

print(is_substring('abcd abs', 'abs')) # True

Here, recursion stops as False when str1 shorter than str2 (i.e., base case). Otherwise, the function compares the beginning of str1 to str2. If they are not the same, then because of or, the function calls itself with smaller part of str1.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 j1-lee