-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfind_and_replace.py
48 lines (37 loc) · 1.34 KB
/
find_and_replace.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
# Question 7: Find and Replace
# For this question you need to define two procedures:
# make_converter(match, replacement)
# Takes as input two strings and returns a converter. It doesn't have
# to make a specific type of thing. Itcan
# return anything you would find useful in apply_converter.
# apply_converter(converter, string)
# Takes as input a converter (produced by make_converter), and
# a string, and returns the result of applying the converter to the
# input string. This replaces all occurrences of the match used to
# build the converter, with the replacement. It keeps doing
# replacements until there are no more opportunities for replacements.
def make_converter(match, replacement):
return match,replacement
def apply_converter(converter, string):
s=[]
s.append(string)
begin=0
while True:
record=""
begin=s[-1].find(converter[0],0)
if begin==-1:
break
end=begin+len(converter[0])
record=s[-1][:begin]+converter[1]+s[-1][end:]
s.append(record)
return s[-1]
# For example,
c1 = make_converter('aa', 'a')
print apply_converter(c1, 'aaaa')
#>>> a
c = make_converter('aba', 'b')
print apply_converter(c, 'aaaaaabaaaaa')
#>>> ab
# Note that this process is not guaranteed to terminate for all inputs
# (for example, apply_converter(make_converter('a', 'aa'), 'a') would
# run forever).