I am trying to complete the following problem: Write a function called rabbit_hole. rabbit_hole should have two parameters: a dictionary and a string. The string may be a key to the dictionary. The value associated with that key, in turn, may be another key to the dictionary. Keep looking up the keys until you reach a key that has no associated value. Then, return that key.
I tested the following code, but it does not return properly for any recursive examples. I added two print statements for testing and it seems to flow correctly, but return is not propagating the correct result for example 1 and 2 (returning "None"). I tried moving the 2nd return statement over one block but it then returned the first cycle of the function. I believe can rewrite to use print rather than return, but the problem asks to use return.
Appreciate any help and explanation.
def rabbit_hole(D, Key):
if Key in D:
if D[Key] in D:
if D[D[Key]] == Key:
return False
else:
print("F1 /", D[Key])
rabbit_hole(D, D[Key])
else:
print("F2 /", D[Key])
return D[Key]
else: return Key
d = {"bat": "pig", "pig": "cat", "cat": "dog", "dog": "ant", "cow": "bee", "bee": "elk", "elk": "fly", "ewe": "cod", "cod": "hen", "hog": "fox", "fox": "jay", "jay": "doe", "rat": "ram", "ram": "rat"}
print(rabbit_hole(d, "bat"))
print(rabbit_hole(d, "ewe"))
print(rabbit_hole(d, "jay"))
print(rabbit_hole(d, "yak"))
print(rabbit_hole(d, "rat"))
return rabbit_hole(D, D[Key])