need to know the mistake in this code
def contains(big_string, little_string):
for character in big_string:
if character == little_string:
and when i look at the solution i don’t understand the answer of the first Q
This will return on the first True, meaning iteration will not be complete. Be sure to completely compare little_string.
Think in terms of slices. We can measure the length of little_string and then iterate over big_string and compare equal length slices when the first letter of little_string is encountered.
What’s more, the above is comparing a character to a string, not a character.
While this is not the recommended solution, since it is not an algorithm (the preferred solution at this level)…
return little_string in big_string
The above uses membership testing with the
in operator. Our algorithm will want to emulate this, but in a loop construct.
def contains(haystack, needle): n = len(needle) f = needle for i, x in enumerate(haystack): if x == f: if haystack[i:n + i] == needle: return True return False print (contains('superimposed', 'impose')) # True
Now if we assume that the
enumerate function is as yet unknown to you, then we can revert to
range to obtain the index, and the current character.
for i in range(len(big_string)): if big_string[i] == f: if big_string[i:n + i] == little_string:
Of course, the above solutions both assume that you are familiar with slicing. If not, then we need to get more creative using only the concepts currently in your tool belt.
We’re now eight hours later, and have this to consider that uses none of the above, only the
range, as suggested.
# without slicing or enumerate def has_in(haystack, needle): k = range(len(needle)) h = range(len(haystack)) f = needle r = False for i in h: if haystack[i] == f: for j in k: if haystack[i + j] == needle[j]: r = True continue else: r = False break if r: return r return r print (has_in('superimposed self-imposed', 'impose')) # True print (has_in('superimposed self-imposed', 'imposter')) # False
Above we could technically return the index, as well, but it would be to the first match, not subsequent matches. That will take more logic.
def has_at(haystack, needle): k = range(len(needle)) h = range(len(haystack) - k[-1]) f = needle r = False s =  for i in h: if haystack[i] == f: for j in k: if haystack[i + j] == needle[j]: r = True continue else: r = False break if r: s.append(i) return s or r print (has_at('superimposed self-imposed impose', 'impose')) # [5, 18, 26] print (has_at('superimposed self-imposed impose', 'imposter')) # False