Question

In: Computer Science

use the python language and fix the error code #Write a function called rabbit_hole. rabbit_hole should...

use the python language and fix the error code

#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.
#
#For example, imagine if you had the following dictionary.
#This one is sorted to make this example easier to follow:
#
# 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"}
#
#If we called rabbit_hole(d, "bat"), then our code should...
#
# - Look up "bat", and find "pig"
# - Look up "pig", and find "cat"
# - Look up "cat", and find "dog"
# - Look up "dog", and find "ant"
# - Look up "ant", and find no associated value, and so it would
# return "ant".
#
#Other possible results are:
#
# rabbit_hole(d, "bat") -> "fly"
# rabbit_hole(d, "ewe") -> "hen"
# rabbit_hole(d, "jay") -> "doe"
# rabbit_hole(d, "yak") -> "yak"
#
#Notice that if the initial string passed in is not a key in
#the dictionary, that string should be returned as the result as
#well.
#
#Note, however, that it is possible to get into a loop. In the
#dictionary above, rabbit_hole(d, "rat") would infinitely go
#around between "rat" and "ram". You should prevent this: if a
#key is ever accessed more than once (meaning a loop has been
#reached), return the boolean False.
#
#Hint: If you try to access a value from a dictionary that does
#not exist, a KeyError will be raised.

#Write your function here!
def rabbit_hole(d,word):
for key in d.keys():
if word == key:
new_key = d[word]
word = new_key
continue
elif word != key:
pass
return d[word]
  

#Below are some lines of code that will test your function.
#You can change the value of the variable(s) to test your
#function with different inputs.
#
#If your function works correctly, this will originally
#print: ant, hen, doe, yak, False, each on their own line.
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"))

Solutions

Expert Solution

Below is a screen shot of the python program to check indentation. Comments are given on every line explaining the code.

Below is the output of the program:

Below is the code to copy:

#CODE STARTS HERE----------------
def rabbit_hole(d,word): #function rabbit_hole
   traversed = [] #Used to store all the words that were searched
   try: #Try , except block to catch key value errors
      while True: #infinite loop is used to travrl across the word chain
         if word not in traversed: #Checking if word was not searched before
            traversed.append(word) #Add word to traversed list
            word = d[word] #Change word for next iteration
         else: #If word repeats, then its a closed chain
            return False #return false
   except KeyError: #This catches key errors
      return word #This is the end of chain

def main():
   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"))

main()
#CODE ENDS HERE-----------------

Related Solutions

This is python: #Write a function called count_positive_evens. This function #should take as input a list...
This is python: #Write a function called count_positive_evens. This function #should take as input a list of integers, and return as #output a single integer. The number the function returns #should be the count of numbers from the list that were both #positive and even. # #For example: # # count_positive_evens([5, 7, 9, 8, -1, -2, -3]) -> 1 # count_positive_evens([2, 4, 6, 8, 10, 12, 15]) -> 6 # count_positive_evens([-2, -4, -6, -8, -10, 1]) -> 0 # #0...
In python please write the following code the problem. Write a function called play_round that simulates...
In python please write the following code the problem. Write a function called play_round that simulates two people drawing cards and comparing their values. High card wins. In the case of a tie, draw more cards. Repeat until someone wins the round. The function has two parameters: the name of player 1 and the name of player 2. It returns a string with format '<winning player name> wins!'. For instance, if the winning player is named Rocket, return 'Rocket wins!'.
Write a function in Python 3 (v. 6175+) called multiplicity00794. The function should receive alimit number...
Write a function in Python 3 (v. 6175+) called multiplicity00794. The function should receive alimit number and return: • how many multiples of 3 or 5 or 7 there are that are less than or equal to the specified limit. • the sum of the multiples of 3 or 5 or 7 that are less than or equal to the specified limit. • the product of the multiples of 3 or 5 or 7 that are less than or equal...
use python to solve Write a function called word_chain that repeatedly asks the user for a...
use python to solve Write a function called word_chain that repeatedly asks the user for a word until either (1) the user has entered ten words, or (2) the user types nothing and presses enter. Each time the user enters an actual word, your program should print all the words entered so far, in one long chain. For example, if the user just typed "orange", and the user has already entered "apple" and "banana", your program should print "applebananaorange" before...
Using python as the coding language please write the code for the following problem. Write a...
Using python as the coding language please write the code for the following problem. Write a function called provenance that takes two string arguments and returns another string depending on the values of the arguments according to the table below. This function is based on the geologic practice of determining the distance of a sedimentary rock from the source of its component grains by grain size and smoothness. First Argument Value Second Argument Value Return Value "coarse" "rounded" "intermediate" "coarse"...
using python 1. #Write a function called multiply_file_by_index. This function #should take two parameters, both strings....
using python 1. #Write a function called multiply_file_by_index. This function #should take two parameters, both strings. The first string is #the filename of a file to which to write (output_file), and #the second string is the filename of a file from which to read #(input_file). # #In the input file, there will be an integer on every line. #To the output file, you should write the integer from the #original file multiplied by the line number on which it #appeared....
Python 3 Fix code everytime i hit submit all the fields in the fomr should be...
Python 3 Fix code everytime i hit submit all the fields in the fomr should be cleaned # required library import tkinter as tk from tkcalendar import DateEntry import xlsxwriter # frame window = tk.Tk() window.title("daily logs") #window.resizable(0,0) # labels tk.Label(window, text="Bar code").grid(row=0, sticky="W", pady=20, padx=20) tk.Label(window, text="Products failed").grid(row=1, sticky="W", pady=20, padx=20) tk.Label(window, text="Money Lost").grid(row=2, sticky="W", pady=20, padx=20) tk.Label(window, text="Failed date").grid(row=3, sticky="W", pady=20, padx=20) # entries barcode = tk.Entry(window) product = tk.Entry(window) money = tk.Entry(window) # arraging barcode.grid(row=0, column=1) product.grid(row=1,...
Python 3 Fix the code. It is not saving the data into the xls file Code:...
Python 3 Fix the code. It is not saving the data into the xls file Code: import tkinter as tk from tkcalendar import DateEntry from openpyxl import load_workbook from tkinter import messagebox from datetime import datetime window = tk.Tk() window.title("daily logs") window.grid_columnconfigure(1,weight=1) window.grid_rowconfigure(1,weight=1) # labels tk.Label(window, text="Bar code").grid(row=0, sticky="W", pady=20, padx=20) tk.Label(window, text="Products failed").grid(row=1, sticky="W", pady=20, padx=20) tk.Label(window, text="Money Lost").grid(row=2, sticky="W", pady=20, padx=20) tk.Label(window, text="sold by").grid(row=3, sticky="W", pady=20, padx=20) tk.Label(window, text="Working product").grid(row=4, sticky="W", pady=20, padx=20) #Working product label tk.Label(window, text="Failed...
Use python write a function that translates the input string into Pig Latin. The translation should...
Use python write a function that translates the input string into Pig Latin. The translation should be done word by word, where all words will be separated by only one space. You may assume that each word must have at least one vowel (a,e,i,o,u and uppercased counterparts), and there will be no punctuation or other special characters in the input string. The Pig Latin rules are as follows: For words that begin with consonants, all letters before the initial vowel...
Write a code to find the following in a text file (Letter). language: Python (a) Find...
Write a code to find the following in a text file (Letter). language: Python (a) Find the 20 most common words (b) How many unique words are used? (c) How many words are used at least 5 times? (d) Write the 200 most common words, and their counts, to a file. text file: Look in thy glass and tell the face thou viewest, Now is the time that face should form another, Whose fresh repair if now thou not renewest,...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT