Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

IN PYTHON Complete the class Misspellings, which should be able to correct the misspelling of attribute names: both for getting the value of an attribute

IN PYTHON Complete the class Misspellings, which should be able to correct the misspelling of attribute names: both for getting the value of an attribute and setting the value of an attribute. See the exact specifications below. Memoize class and a min_dist function. Leave these definitions exactly as they are.

The distance between strings increases by 1 for every addition, deletion, or substitution it takes to convert one string into the other. For example min_dist("able", "camel") is 4: to transform "able"into "camel" we can add a c at the front, substitute an m for ab, add an e between the m and l, and delete the e at the end Going the other way, we can delete the c at the front, substitute a b for anm, add an l between the m and e, and delete the lat the end. There are other ways to convert in 4 changes, but no ways to do it in 3: so 4 is the minimum distance. The __init__ method in Misspelling has a parameter (whose default value is False) that is used to set the fix_when_setting attribute (see below for how this attribute is used). It calls initialize_attributesto initialize the attribute names that may be misspelled in tests. For testing purposes, this is easier to do outside of __init__. You can change the inside of either method, but __init__ must call initialize_attributes as its last statement.

1)Write method named closest_matches; its parameters are self(an object from the class Misspelling) and name (a str); it returns a list of all the attribute names in that Misspelling object that have the same minimum distance from name, so long at that minimum distance is half of the length of name (so, not too distant from name). The returnedlistmay be empty (no attributes names are close), or contain one or more values (multiple attribute names all having the same minimum distance).

2)Write the __getattr__ method; its parameters are self(an object from the class Misspelling) and name(a str that is not the correct spelling of any attribute in the object); it returns the value of the attribute name in selfthat is closest to name(use the listof attribute names returned by closest_matches). only if there is exactly one attribute name that is the minimum distance from name: if there are none or more than one, this method should raise a NameErrorexception with an appropriate message. Remember that __getattr__is called by Python only if nameis not an actual attribute in an object

3)Write the __setattr__ method; its parameters are self (an object from the class Misspelling), name (a strthat may or may not be the name of an attribute), and value (the new value to be bound to the attributename). This method should allow (a) the binding of any attribute names in __init__and initialize_attributes; (b) the rebinding of any attribute name that is already stored in the object. Otherwise (c) if name is not an attribute name and the fix_when_setting attribute is True, then value should be bound to the unique name that most closely matches name (use the listof attribute names returned by closest_matches). if none or more than one attribute names match with the minimum distance (or fix_when_settingis False) then this method should raise a NameErrorexception with an appropriate message. Hint: Use code like the Historyclass example in the notes to ensure all the attribute names in __init__and initialize_attributes get bound correctly. Read the comment beforeinitialize_attributes, which guarantees the last attribute name bound in that method is last

Here is an example of a run of the code in misspelling.py (allowingfixing spelling in __setattr__).

{'fix_when_setting': False, 'amoral': 1, 'more': 2, 'babel': 3, 'last': 4}

Enter test: o.babel

3

{'fix_when_setting': False, 'amoral': 1, 'more': 2, 'babel': 3, 'last': 4}

Enter test: o.babe

3

{'fix_when_setting': False, 'amoral': 1, 'more': 2, 'babel': 3, 'last': 4}

Enter test: o.least

4

{'fix_when_setting': False, 'amoral': 1, 'more': 2, 'babel': 3, 'last': 4}

Enter test: o.colorado

('Misspelling.__getattr__: name(colorado) not found; matches =', [])

import prompt class Memoize: def __init__(self,f): self.f = f self.cache = {} def __call__(self,*args): if args in self.cache: return self.cache[args] else: answer = self.f(*args) self.cache[args] = answer return answer # Computes minimum distance between two words recursively # Use memoization for dynamic programming speedup (explained later in the quarter) @Memoize def min_dist(a : str, b : str) -> int: # Levenshtein distance:: 1 for every addition, deletion, substitution if a == '': return len(b) elif b == '': return len(a) elif a[0] == b[0]: return min_dist(a[1:],b[1:]) else: return 1 + min( min_dist(a[1:],b), min_dist(a,b[1:]), min_dist(a[1:],b[1:]) ) class Misspelling: # __init__ must call this method so I can test Misspelling more easily. # This method should consist of only new bindings to attribute names. # It should (and will when I grade it) always have a list binding # self.last = some value # You may put your own bindings here using any names to test your code; # when I grade your work, I will replace the contents of this method # but the last binding will always be to the attribute last def initialize_attributes(self): self.amoral = 1 self.more = 2 self.babel = 3 self.last = 4 def __init__(self, fix_when_setting=False): self.fix_when_setting = fix_when_setting self.initialize_attributes() def closest_matches(self,name): pass def __getattr__(self,name): pass # Uncomment when ready to solve this part; otherwise o.a = v does nothing # def __setattr__(self,name,value): # pass # You should try to understand the specifications and test your code # to ensure it works correctly, according to the specification. # You are all allowed to ask "what should my code do..." questions online # both before and after I post my batch self_check file. # The driver below will allow you to easily test your code. if __name__ == '__main__': o = Misspelling(prompt.for_bool("Allow fixing mispelling in __setattr__",True)) # Put code here to test object o the same way each time the code is run # Use the while loop below to type in code one on-the-fly when prompted while True: try: print(" " + str(o.__dict__)) test = prompt.for_string("Enter test") if test == "quit": break; if '=' not in test: print(eval(test)) else: exec(test) except Exception as exc: print(exc)

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

More Books

Students also viewed these Databases questions

Question

1.what is the significance of Taxonomy ?

Answered: 1 week ago

Question

What are the advantages and disadvantages of leasing ?

Answered: 1 week ago

Question

Name is needed for identifying organisms ?

Answered: 1 week ago