Skip to content

Instantly share code, notes, and snippets.

@Codercise
Created June 1, 2012 00:36
Show Gist options
  • Save Codercise/2847590 to your computer and use it in GitHub Desktop.
Save Codercise/2847590 to your computer and use it in GitHub Desktop.
# 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 create_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):
match = converter[0]
replacement = converter[1]
madeReplacement = True
while madeReplacement:
madeReplacement = False
#pos = 0
for pos in range(0, len(string) - len(replacement)):
print "hello world1"
if match == True:
print "hello world2"
currentString = currentString.split(0, position)
+ replacement
+ currentString.split(position+len(toMatch)-1, len(currentString)-1)
madeReplacement = True
print currentString
# 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).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment