2. (10 points.) Write a Python function called replace that takes two arguments,
ID: 3588142 • Letter: 2
Question
2. (10 points.) Write a Python function called replace that takes two arguments, a dio- tionary D and a tuple T. The function replace must return a tuple like T, but in which each element that is a key in D is replaced by its corresponding value from D. For example, suppose that the dictionary Y is defined like this. Y 'dog' 'cat', 'fido' 'felix') Then here is how replace must work, where the arrow "" means "returns. replace (Y, ()) ('hot', 'dog')) () ('hot','cat') replace (Y, ('fido', replace(Y, 'is', ("nothing', 'a' , 'to', 'dog')) ('felix', 'do')) ('nothing', 'ia', 'a', 'cat') replace (Y, 'to', 'do') Your function replace must work correctly for any dictionary D and any tuple T, not just the ones shown in this example! Also, if there is a predefined Python function that acts like replace, then you are not allowed to use it. Hint: the expression K in D tests if K is a key in the dictionary D.Explanation / Answer
Solution:
def replace(D, T):
res = []
for i in T:
if i in D:
res.append(D[i])
else:
res.append(i)
return tuple(res)
Y = { 'dog': 'cat', 'fido': 'felix'}
print(replace(Y,()))
print(replace(Y, ('hot', 'dog')))
print(replace (Y, ('fido', 'is', 'a', 'dog')))
print(replace (Y, ('nothing', 'to', 'do')))
I hope this helps if you find any problem. Please comment below. Don't forget to give a thumbs up if you liked it. :)
Related Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.