Write a Python function called replace that takes two arguments, a dictionary D
ID: 3835746 • Letter: W
Question
Write a Python function called replace that takes two arguments, a dictionary 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."
replce(Y,()) => ()
replace(Y, ('hot', 'dog')) => ('hot', 'cat')
replace (Y, ('fido', 'is', 'a', 'dog'))=> ('felix', 'is', 'a', 'cat')
replace (Y, ('nothing', 'to', 'do')) => ('nothing', 'to', 'do')
Your function replace must work correctly for any dictionary D and tuple T, not just the ones shown in this example! Also, if here is a predefined 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
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')))
# code link: https://paste.ee/p/VXQpK
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.