Menu
support@authoritypapers.com
+1(805) 568 7317

python local dictionary program overview in this assignment we 39 ll write a diction 5153705

Python

Local Dictionary program.

Overview: In this assignment, we'll write a dictionary, and provide a way for user to enter a word and see its meaning. Our dictionary is a very simplified version of a real dictionary, in that each word has only a single part of speech (e.g. noun), a single definition, and optionally, a single example of usage.

Technical Overview: Our dictionary is composed of two parts: a LocalDictionary that contains the deserialized word entries from a JSON file, and a cache for these word entries, called DictionaryEntryCache. Each word entry is represented by an instance of DictionaryEntry.

In computer science, cache typically refers to something that's small but fast, and is usually deployed to increase repeated search performance. For (a canned) example, on President's Day Google might receive lots of queries for “george washington”. Performing one such query might take hundreds of milliseconds over hundreds of servers, but to speed up subsequent queries for the same term, Google servers may cache this particular result locally, so that it might take mere milliseconds to return that subsequently.

In this assignment, we pretend that LocalDictionary contains vast amount of word entries. Once we find an entry for a word, we'll store that in DictionaryEntryCache, which has limited capacity but is fast. So every time we search for a word, we look in DictionaryEntryCache first, and return the result if it's found; if it's not found, then we search for it in LocalDictionary. We'll encapsulate this behavior in another class, aptly named Dictionary.

Note we'll implement our cache on top of a linked list. Linked list is probably not the first choice of data structure for a cache, but it allows us to implement the eviction policy relatively easily:when the capacity of the cache is reached, we'll remove the oldest one inserted.

We'll implement a number of classes. This is an overview diagram showing how they are used and related to each other.

assignment 8 diagram.png

Specification

2 provided files:

1) dictionary.json

{
“copyright”: “foothill cs3b”,
“purpose”: “sample dictionary.json for assignment #8”,
“todo”: “add at least 3 more words with part of speech, definition, and optionally example of usage”,
“entries”: [
{
“word”: “ace”,
“partOfSpeech”: “noun”,
“definition”: “a playing card with a single spot on it, ranked as the highest card in its suit in most card games”,
“example”: “life had started dealing him aces again”
},
{
“word”: “python”,
“partOfSpeech”: “noun”,
“definition”: “a large heavy-bodied non-venomous snake occurring throughout the Old World tropics, killing prey by constriction and asphyxiation.”
},
{
“word”: “foothill”,
“partOfSpeech”: “noun”,
“definition”: “a low hill at the base of a mountain or mountain range”,
“example”: “the camp lies in the foothills of the Andes”
},
{
“word”: “fly”,
“partOfSpeech”: “verb”,
“definition”: “(of a bird, bat, or insect) move through the air using wings”,
“example”: “he was sent flying by the tackle”
}
]
}

2) datalist.py

# You should NOT modify this file, other than for debugging.

# Do NOT submit this file for assignment.

class Node:

“””

Node class for a LinkedList – not designed for general clients.

“””

def __init__(self):

# instance attributes

self.next = None

def insert_after(self, new_node):

if not isinstance(new_node, Node):

raise TypeError(“new_node should be a Node”)

new_node.next = self.next

self.next = new_node

def remove_after(self):

temp = self.next

if temp:

self.next = temp.next

temp.next = None

return temp

def __str__(self):

return f”id={id(self):#x}”

class LinkedList:

“””

LinkedList is our base class for a data-filled linked list

“””

def __init__(self):

# an empty list will have one “header” node at the front

self.head = Node()

def add_to_head(self, new_node):

self.head.insert_after(new_node)

def remove_from_head(self):

return self.head.remove_after()

def is_empty(self):

return self.head.next == None

def __str__(self):

SEPARATOR = ” -> “

LEN_SEPARATOR = len(SEPARATOR)

if self.is_empty():

return “n[ empty list ]n”

ret_str = “n[START LIST]: “

temp = self.head

while temp.next:

temp = temp.next # skip passed header

ret_str += (str(temp) + SEPARATOR)

# remove extra “->” and add terminator

ret_str = ret_str[:-LEN_SEPARATOR] + ” [END LIST]n”

return ret_str

def reset_current(self):

self.current = self.head

def iterate(self):

# Protect against the case client keeps calling iterate() even when

reaching the end

if not self.current:

return None

temp = self.current.next

self.current = temp

return temp

class DataNode(Node):

“””

DataNode subclass of Node.

It is the node class for a data list.

Requires data item, data, be vetted by client (DataList)

“””

def __init__(self, data):

super().__init__()

self.data = data

def __str__(self):

return str(self.data)

class DataList(LinkedList):

“””

DataList can store arbitrary data

“””

def add_to_head(self, data):

super().add_to_head(DataNode(data))

def remove_from_head(self):

return super().remove_from_head().data

def insert_sorted(self, data):

temp = self.head

while temp.next:

if data

break

temp = temp.next

temp.insert_after(DataNode(data))

def remove(self, data):

temp = self.head

while temp.next:

if temp.next.data == data:

temp.remove_after()

return True

temp = temp.next

return False

For this assignment, do not worry about setters/getters/@property, so use attributes by accessing them directly. Attributes don't need underscores preceding them either. Setters/getters are still important, and you should continue to use them for future projects. But for this assignment, we'll focus on the new topics.

▶ file dictionary.json

You are provided with a sample dictionary.json. Following the schema already used in the file, add at least 3 more words to it, along with their parts of speeches, definitions, and optionally examples. Do not change the existing content.

▶ class DictionaryEntry

It represents an entry in the dictionary and has 4 attributes (again, access the attributes directly, no need for setters/getters/@property):

  • word
  • part_of_speech
  • definition
  • example

It should define at least the following methods:

def __init__(self, word, part_of_speech, definition, example=None):

The constructor. No need to validate the parameters.

def __str__(self):

Returns a string representation of the entry. It should be something that's user-friendly, e.g.

Word : ace Part of speech: noun Definition : a playing card with a single spot on it, ranked as the highest card in its suit in most card games Example : life had started dealing him aces again

▶ class LocalDictionary

This class loads the content of the dictionary from a JSON file, and provides a method to search through it.

It must define at least the following instance methods:

def __init__(self, dictionary_json_name = “dictionary.json”):

This loads the entire content of dictionary_json_name. It has to deserialize each entry in the JSON file into an instance of DictionaryEntry.

It should store all the DictionaryEntry's in such a way that it's very easy to search for a word, which is what search(word) must do.

def search(self, word):

This finds and returns the DictionaryEntry associated with word. If no entry exists for word, raise KeyError with a descriptive message.

▶ class DictionaryEntryCache

This is the cache for DictionaryEntry's. We'll have DictionaryEntryCache inherit from DataList discussed in the lecture/readings, and add the necessary methods.

You are provided with datalist.pyPreview the document, which contains the definition for DataList. You should not modify the file (although feel free to do so for debugging), and should simply import what you need from the file. You should not submit this file.

This class should implement at least the following instance methods:

def __init__(self, capacity = 10):

The constructor should initialize what's necessary for a DataList, and instantiate its own instance attributes as necessary. It should also verify capacity is at least 1, and raise a ValueError if it's not. Note you have to make sure the cache work with capacity of 1.

def add(self, entry):

This adds entry, which is the type DictionaryEntry (so raise a TypeError if it's not), to a place in the linked list of your choice. If the the number of entries in the cache exceeds its capacity, you should remove the oldest entry (by insertion order). For example, if the capacity is 2, and you add the word “ace” then “be”, then when you try to add the word “cat”, “ace” should be removed.

def search(self, word):

This should look for word in all the entries in the linked list, return the DictionaryEntry if it's found, raise KeyError if not.

class DictionarySource

It's an enum that represents where the definition comes from. For this assignment it's either LOCAL or CACHE.

▶ class Dictionary

This is the class that client code should instantiate. It contains and manages both an instance of LocalDictionary, and an instance of DictionaryEntryCache.

It should have at least the following instance methods:

def __init__(self):

Instantiate a LocalDictionary and a DictionaryEntryCache as instance attributes.

def search(self, word):

It first searches word in its instance of DictionaryEntryCache. If found, it'll return a tuple of the entry and DictionarySource.CACHE.

If word is not found the cache, it'll then search its instance of LocalDictionary. If found, it'll add the entry to its cache, then return a tuple of the entry and DictionarySource.LOCAL; if not found, it raises a KeyError.

▶ main loop

Write a simple client loop that asks user to type in a word to search, and print the dictionary entry (along with the source) if found; if an exception is raised, it prints the exception and continue. It doesn't need to exit.

A sample output of the main loop would look like this (with cache capacity of 1):

Enter a word to lookup: ace Word : ace Part of speech: noun Definition : a playing card with a single spot on it, ranked as the highest card in its suit in most card games Example : life had started dealing him aces again (Found in LOCAL) Enter a word to lookup: ace Word : ace Part of speech: noun Definition : a playing card with a single spot on it, ranked as the highest card in its suit in most card games Example : life had started dealing him aces again (Found in CACHE) Enter a word to lookup: foothill Word : foothill Part of speech: noun Definition : a low hill at the base of a mountain or mountain range Example : the camp lies in the foothills of the Andes (Found in LOCAL) Enter a word to lookup: ace Word : ace Part of speech: noun Definition : a playing card with a single spot on it, ranked as the highest card in its suit in most card games Example : life had started dealing him aces again (Found in LOCAL) Enter a word to lookup: nothing Error when searching: 'nothing' Enter a word to lookup:

Testing

You should, as usual, write unittest as you develop your code. You should also test with the main loop you write above.

We were unable to transcribe this imageWe were unable to transcribe this image

"Order a similar paper and get 15% discount on your first order with us
Use the following coupon
"GET15"

Order Now