The Python Oracle

Recursive function that identifies whether string 1 is contained within string 2? (Python 3.4)

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Music Box Puzzles

--

Chapters
00:00 Recursive Function That Identifies Whether String 1 Is Contained Within String 2? (Python 3.4)
00:53 Answer 1 Score 0
01:11 Accepted Answer Score 3
01:36 Answer 3 Score 1
01:55 Answer 4 Score 1
02:12 Thank you

--

Full question
https://stackoverflow.com/questions/3722...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #string #recursion

#avk47



ACCEPTED ANSWER

Score 3


At the line:

 return contains_recursive(s1[0], s2[1:])

you are shortening s1 to one character but then at the next call you may hit:

 return contains_recursive(s1[1:], s2[1:])

with s1 a string of len 1.

You need to use:

return contains_recursive(s1, s2[1:])

and add a check on the length of s1




ANSWER 2

Score 1


I take it that being recursive is a requirement. In that case:

def contains(s1, s2):
    if not s1:
        return True
    i = s2.find(s1[0])
    if i == -1:
        return False
    else:
        return contains(s1[1:], s2[i+1:])

This produces:

>>> contains("lit", "litter")
True
>>> contains("thot", "thurtle")
False
>>> contains("ratchet", "ramtbunchiousest")
True
>>> contains("shade", "hadsazie")
False



ANSWER 3

Score 1


The error you are getting could be because s2 is an empty string. Add a check for it's length as well. If you reach this point it would mean you haven't found all the letters you are searching for and therefore the end result should be false.

if s2 == '':
    return False



ANSWER 4

Score 0


Avoid using rescurive functions for efficiency.

def test(s1, s2):
    idx2 = 0
    for c in s1:
        if c in s2[idx2:]:
            idx2 = s2.index(c) + 1
        else:
            return False

    return True

# Test
lists = [   ("lit", "litter"), 
            ("thot", "thurtle"), 
            ("ratchet", "ramtbunchiousest"), 
            ("shade", "hadsazie")]

result = [test(*t) for t in lists]
print(result)
# Output
[True, False, True, False]