-
Notifications
You must be signed in to change notification settings - Fork 50
/
strings.py
56 lines (45 loc) · 2.27 KB
/
strings.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#!python
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)
# TODO: Implement contains here (iteratively and/or recursively)
def find_index(text, pattern):
"""Return the starting index of the first occurrence of pattern in text,
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)
def find_all_indexes(text, pattern):
"""Return a list of starting indexes of all occurrences of pattern in text,
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)
def test_string_algorithms(text, pattern):
found = contains(text, pattern)
print('contains({!r}, {!r}) => {}'.format(text, pattern, found))
# TODO: Uncomment these lines after you implement find_index
index = find_index(text, pattern)
print('find_index({!r}, {!r}) => {}'.format(text, pattern, index))
# TODO: Uncomment these lines after you implement find_all_indexes
indexes = find_all_indexes(text, pattern)
print('find_all_indexes({!r}, {!r}) => {}'.format(text, pattern, indexes))
def main():
"""Read command-line arguments and test string searching algorithms."""
import sys
args = sys.argv[1:] # Ignore script file name
if len(args) == 2:
text = args[0]
pattern = args[1]
test_string_algorithms(text, pattern)
else:
script = sys.argv[0]
print('Usage: {} text pattern'.format(script))
print('Searches for occurrences of pattern in text')
print("\nExample: {} 'abra cadabra' 'abra'".format(script))
print("contains('abra cadabra', 'abra') => True")
print("find_index('abra cadabra', 'abra') => 0")
print("find_all_indexes('abra cadabra', 'abra') => [0, 8]")
if __name__ == '__main__':
main()