Name: Anonymous 2013-03-19 15:39
/prog/ How do I do this using recursion? I finished this using a loop but it turns out that I cannot do this question using any sort of iteration. Heres my code:
Heres the assignment:
The Microsoft Word Find and Replace function finds the target in the whole document and replaces it with the given replacement text. Write a function replace_str to implement this functionality. Your function will consume 3 non-empty strings, base, target and rep. The first string, base, represents a base string that you want to update. The second string target represents the target string that you want to replace and the third string rep represents a string that will replace the target in the updated string. The function produces a new string in which the target string is replaced by the rep string in the base string, but produces the same base string if either of the following conditions hold true.
• If the target string is not found in the base string or,
• If the target and rep are the same strings.
For example,
Note:
• You are not allowed to use the string methods replace and find for this question.
def replace_str(base, target, rep):
for i in range(len(base)):
if target == base[i:i + len(target)]:
base = base[:i] + rep + base[i + len(target):]
print baseHeres the assignment:
The Microsoft Word Find and Replace function finds the target in the whole document and replaces it with the given replacement text. Write a function replace_str to implement this functionality. Your function will consume 3 non-empty strings, base, target and rep. The first string, base, represents a base string that you want to update. The second string target represents the target string that you want to replace and the third string rep represents a string that will replace the target in the updated string. The function produces a new string in which the target string is replaced by the rep string in the base string, but produces the same base string if either of the following conditions hold true.
• If the target string is not found in the base string or,
• If the target and rep are the same strings.
For example,
replace_str("This is a book","a","the")=>'This is the book'
replace_str("This is my book","a","the")=>'This is my book'
replace_str("I like this book","I","I")=> 'I like this book'
replace_str ("my brother reads books and sometimes he reads magazines", "reads", "likes") =>'my brother likes books and sometimes he likes magazines'
replace_str("Apple is a fruit", "f" , "t" )=>'Apple is a truit'
replace_str("aaaaa","aa","x")=>'xxa'Note:
• You are not allowed to use the string methods replace and find for this question.