PYTHON Solution must be recursive. You are not allowed to use loops, or use the
ID: 3792956 • Letter: P
Question
PYTHON
Solution must be recursive. You are not allowed to use loops, or use the python "in" operator.
Write a function which is passed 3 parameters, all of which are strings. The function returns a copy of the string s with all occurrences of old_c replaced by new_c. You are not allowed to use the built-in python replace method. You may assume that old_c and new_c are both strings of length 1.
def replace(s, old_c, new_c):
>>> replace('science', 'c' , 't')
'stiente'
>>> replace('python', 's', 't')
'python'
>>> replace('rocker', 'r', 'd')
'docked'
Explanation / Answer
def replace(s, old_c, new_c):
if s == '':
return ''
if s[0] == old_c:
return new_c + replace(s[1:], old_c, new_c)
return s[0] + replace(s[1:], old_c, new_c)
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.