Verified Commit ff0cd765 authored by Dacio Romero's avatar Dacio Romero 🔎

Use generator for strings

parent 42d31727
......@@ -4,16 +4,6 @@ def contains(text, pattern):
"""Return a boolean indicating whether pattern occurs in text."""
assert isinstance(text, str), 'text is not a string: {}'.format(text)
assert isinstance(pattern, str), 'pattern is not a string: {}'.format(text)
# return pattern in text
# if pattern == '':
# return True
# for i in range(len(text) - len(pattern) + 1):
# if text[i:i+len(pattern)] == pattern:
# return True
# return False
return find_index(text, pattern) != None
......@@ -24,14 +14,8 @@ def find_index(text, pattern):
or None if not found."""
assert isinstance(text, str), 'text is not a string: {}'.format(text)
assert isinstance(pattern, str), 'pattern is not a string: {}'.format(text)
# TODO: Implement find_index here (iteratively and/or recursively)
if pattern == '':
return 0
for i in range(len(text) - len(pattern) + 1):
if text[i:i+len(pattern)] == pattern:
return i
return None
return next(find_indexes(text, pattern), None)
def find_all_indexes(text, pattern):
......@@ -39,17 +23,17 @@ def find_all_indexes(text, pattern):
or an empty list if not found."""
assert isinstance(text, str), 'text is not a string: {}'.format(text)
assert isinstance(pattern, str), 'pattern is not a string: {}'.format(text)
# TODO: Implement find_all_indexes here (iteratively and/or recursively)
if pattern == '':
return list(range(len(text)))
indices = []
return list(find_indexes(text, pattern))
def find_indexes(text, pattern):
if pattern == '':
yield from range(len(text))
return
for i in range(len(text) - len(pattern) + 1):
if text[i:i+len(pattern)] == pattern:
indices.append(i)
return indices
yield i
def test_string_algorithms(text, pattern):
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment