1

I'm trying to manually code the python string in function for an assignment. Using this code, where s is the string and t is the substring I am trying to find:

def test(s, t):
    stidx = 0
    while stidx < len(s):
        idx = 0
        for i in s[stidx:]:
            if idx < len(t):
                if t[idx] == i:
                    idx += 1
                    continue
                else:
                    break
            if idx == len(t):
                return True
        stidx += 1
    return False

The above code works, except when I am checking a substring at the very end of the word (e.g. s = 'happy' and t = 'py'). If I add an arbitrary character to the end of s, it works. Why is this?

Adrian Shum
  • 38,812
  • 10
  • 83
  • 131
madeleine
  • 11
  • 5

1 Answers1

0

maybe?

def test(s, t):
    """
    :param s:   exp: happy
    :param t:   exp: py
    :return:
    """
    tmp = result = 0
    t_len = len(t)
    while tmp <= len(s)-t_len:
        if s[tmp: tmp+t_len] == t:
            result = 1
            break
        else:
            tmp += 1
            continue

    return bool(result)
oaixnah
  • 44
  • 2