Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Only using recursion! Do not use loop(for)!!! Note: You are not allowed to use a

ID: 3600837 • Letter: O

Question

Only using recursion! Do not use loop(for)!!!

Note: You are not allowed to use any of the string methods for this question (remember: slicing, in, and len are not string methods, thus they are allowed). Write a Python function replace_str that consumes 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 returns a new string in which the target string is replaced by the rep string in the base string, but returns 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, replacestr ("This is a book", "a", "the")=> ' This is the book' replacestr ("This is my book", "a", "the"->'This is my book' replace_str ("my brother reads books and sometimes he reads magazines", "reads", "likes") => 'my brother ikes books and sometimes he likes magazines replace_str ("Apple is a fruit", "f" , "t")-> Apple is a truit' replacestr ("aaaaa", "aa", "X")=> 'xxa' - - -

Explanation / Answer

main.py

import check


def replace_str(base, target,rep):
word = len(target)
if word == 0:
return base
if len(base) < word:
return base
elif target in base:
start = base.find(target)
new_base = base[start+word:]
new = base[:start] + rep + replace_str(new_base,target,rep)
return new
else:
return base
  
# Tests
## base case
check.expect("q1t1", replace_str('','a','b'), '')
check.expect("q1t2", replace_str('','','a'), '')
check.expect("q1t3", replace_str('','a',''), '')
## single replacement
check.expect("q1t4", replace_str('fruit','f','t'), 'truit')
check.expect("q1t5", replace_str('This is my book','my','the'),
'This is the book')
## multiple replacement
check.expect("q1t6", replace_str('aaaaa','aa','x'), 'xxa')
check.expect("q1t7", replace_str('My brother reads books and sometimes he reads magazines', 'reads', 'likes'),
'My brother likes books and sometimes he likes magazines')
check.expect("q1t8", replace_str('I like this book','I','I'), 'I like this book')
## no replacement
check.expect("q1t9", replace_str('this is my book','a','the'), 'this is my book')