Question

In: Computer Science

Just to be clear, I only want the answer to the third part The typedset question...

Just to be clear, I only want the answer to the third part

The typedset question pls.

Implement a class Box that represents a 3-dimensional box. Follow these guidelines:


constructor/repr

A Box object is created by specifying calling the constructor and supplying 3 numeric values
for the dimensions (width, height and length) of the box.
These measurements are given in inches.
Each of the three dimensions should default to 12 inches.
The code below mostly uses integers for readability but floats are also allowed.
You do not need to do any data validation.
See below usage for the behaviour of repr.
There are no set methods other than the constructor.


>>> b = Box(11,12,5.5)
>>> b
Box(11,12,5.5)
>>> b2 = Box()
>>> b2
Box(12,12,12)

calculations
Given a Box , you can request its volume and cost.
volume - return volume in cubic inches
cost - returns the cost of a box in dollars. A box is constructed out of cardboard that costs
30 cents per square foot. The area is the total area of the six sides (don't worry about
flaps/overlap) times the unit cost for the cardboard.
If you look up formulas, cite the source in a comment in your code.

>>> b.volume()
726.0
>>> b.volume() == 726
True
>>> b.cost()
1.0770833333333334
>>> b2.volume()
1728
>>> b2.cost()
1.8
>>> b2.cost() == 1.8
True

comparisons

Implement the == and <= operators for boxes.
== - two boxes are equal if all three dimensions are equal (after possibly re-orienting).
<= - one box is <= than another box, if it fits inside (or is the same) as the other (after
possibly re-orienting). This requires that the boxes can be oriented so that the first box has
all three dimensions at most as large as those of the second box.

The above calculations must allow the boxes to be re-oriented. For example
Box(2,3,1)==Box(1,2,3) is True . How many ways can they be oriented? What is a good
strategy to handle this?
You may need to look up the names of the magic/dunder methods. If so, cite the source.
warning: I will run more thorough complete tests, so make sure you are careful!

>>> Box(1,2,3)==Box(1,2,3)
True
>>> (Box(1,2,3)==Box(1,2,3)) == True
True
>>> Box(2,3,1)==Box(1,2,3)
True
>>> Box(4,3,1)==Box(1,2,6)
False
>>> Box(1,2,3) <= Box(1,2.5,3)
True
>>> Box(1,3,3) <= Box(1,2.5,3)
False
>>> Box(3,1,2) <= Box(1,2.5,3)
True
>>> Box(1,2,3)<=Box(1,2,3)
True
>>>

boxThatFits

Write a standalone function boxThatFits that is a client of (uses) the Box class.
This function will accept two arguments, 1) a target Box and, 2) a file that contains an
inventory of available boxes.
The function returns the cheapest box from the inventory that is at least as big as the target
box.
If no box is large enough, None is returned.
If there is more than one that fits available at the same price, the one that occurs first in the
file should be returned.

>>> boxThatFits(Box(10,10,10),"boxes1.txt")
Box(10,10,10)
>>> b = boxThatFits(Box(10,10,10),"boxes1.txt")
>>> b.cost()
1.25
>>> boxThatFits(Box(12,10,9),"boxes2.txt")
Box(10,10,13)
>>> boxThatFits(Box(14,10,9),"boxes2.txt")
Box(11,15,10)
>>> boxThatFits(Box(12,10,13),"boxes2.txt")
Box(12,14,10)
>>> boxThatFits(Box(16,15,19),"boxes1.txt")
>>>

TypedSet

Write a class TypedSet according to these specifications:
TypedSet must inherit from set . Remember that this means you may get some of the
required functionality for free.
TypedSet acts like a set (with limited functionality) except that once the first item is added,
its contents are restricted to items of the type of that first item. This could be str or int or
some other immutable type.

# this is helpful, not something you need to write any code for
>>> type("a")
<class 'str'>
>>> x = type(3)
>>> x
<class 'int'>
>>> x==str
False
>>> x==int
True

constructor/repr
Do not write __init__ or __repr__ . When you inherit from set you will get suitable
versions.
Assume that the constructor will always be used to create an empty TypedSet (no arguments
will be passed)

add/getType
add functions like set.add , except that
the first object added to a TypedSet determines the type of all items that will be
subsequently added to the set
after the first object is added, any attempt to add an item of any other type raises a
WrongTypeError
getType returns the type of the TypedSet or None if no item has ever been added
Note: the sorted function is used for the below examples (and doctest) to make sure that
the results always appear in the same order.
Hint: you will need to make use of Python's type function. It returns the type of an object.
Of course, the value it returns can also be assigned to a variable/attribute and/or compared
to other types like this:

>>> ts = TypedSet()
>>> ts.add("a")
>>> ts.add("b")
>>> ts.add("a")
>>> ts.add(3) #doctest: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
...
WrongTypeError: 3 does not have type <class 'str'>
>>> sorted(ts)
['a', 'b']
>>> ts = TypedSet()
>>> ts.getType()
>>> ts.add(2)
>>> ts.add("a") #doctest: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
...
WrongTypeError: a does not have type <class 'int'>
>>> ts.getType()
<class 'int'>
>>> ts.getType()==int
True
>>>

remove
remove functions as it would with a set

>>> ts = TypedSet()
>>> ts.add(4.3)
>>> ts.add(2.1)
>>> ts.add(4.3)
>>> ts.remove(4.3)
>>> ts.remove(9.2) #doctest: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
...
KeyError: 9.2
>>> ts
TypedSet({2.1})

update
update functions like set.update , given a sequence of items, it adds each of the them
but, this update will raise a WrongTypeError if something is added whose type does not
match the first item

keep in mind that the TypedSet may not yet have been given an item when update is called

>>> ts = TypedSet()
>>> ts.add(3)
>>> ts.update( [3,4,5,3,4,4])
>>> sorted( ts )
[3, 4, 5]
>>> ts.update(["a","b"]) #doctest: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
...
WrongTypeError: a does not have type <class 'int'>
>>>
>>>
>>> ts = TypedSet()
>>> ts.update( ["a","b",3]) #doctest: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
...
WrongTypeError: 3 does not have type <class 'str'>
>>>

The | operator is the "or" operator, given two sets it returns their union, those elements
that are in one set or the other. (It is already defined for the set class.)
accepts two arguments, each a TypedSet , neither is changed by |
returns a new TypedSet whose contents are the mathematical union of the supplied
arguments
as usual, raises a WrongTypeError if the two TypedSet 's do not have the same type
remember to cite anything you need to look up

>>> s1 = TypedSet()
>>> s1.update([1,5,3,1,3])
>>> s2 = TypedSet()
>>> s2.update([5,3,8,4])
>>> sorted( s1|s2 )
[1, 3, 4, 5, 8]
>>> type( s1|s2 ) == TypedSet
True
>>> sorted(s1),sorted(s2)
([1, 3, 5], [3, 4, 5, 8])
>>>
>>> s1 = TypedSet()
>>> s1.update([1,5,3,1,3])
>>> s2 = TypedSet()
>>> s2.update( ["a","b","c"] )
>>> s1|s2 #doctest: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
...
WrongTypeError: b does not have type <class 'int'>

>>> sorted(s1),sorted(s2)
([1, 3, 5], ['a', 'b', 'c'])

Just to be clear, I only want the answer to the third part

The typedset question pls.

Solutions

Expert Solution

Raw_Code:

# custom exception class for TypedSet
class WrongTypeError(Exception):
# overloading __init__ method
def __init__(self, args):
self.args = args
# overloading __str__ method
def __str__(self):
return str(self.args[0]) + " does not have type " + str(self.args[1])

# TypedSet class inheriting set class
class TypedSet(set):
# data variable for storing type of elements of TypedSet
typedset_type = None

# getType method return type of elements of TypedSet object
def getType(self):
return self.typedset_type

# overriding the add method of super class (set)
def add(self, value):
# if the adding element is the first element
# then deciding the type of TypedSet object
if len(self) == 0:
# calling add method super class (set)
super().add(value)
# storing the type of first element in data variable typedset_type
self.typedset_type = type(value)
# if not, first element
else:
#checking whether the type of adding element is typedset_type or not
if type(value) != self.typedset_type:
# if both type aren't same, rasing WrongTypeError
# with value and typedset_type as arguments
raise WrongTypeError((value, self.typedset_type))
else:
# if value is of typedset_type, calling add method of super class
super().add(value)

# over loading update of super class
def update(self, values):
# iterating over values and calling add method with value as argument
for value in values:
self.add(value)

# overloading __instancecheck__ method
def __instancecheck__(self, obj):
# comparing the class of self and obj parameters by accessing __class__ attribute
if self.__class__ == obj.__class__:
# comparing the typedset_type attribute of obj with self object
if self.typedset_type == obj.typedset_type:
# if typeset_type are equal, returns true otherwise false
return True
return False

# overloading __or__ operator
def __or__(self, set2):
# calling union method
return self.union(set2)

# overridding union method of super class(set)
def union(self, set2):
# checking whether both objects are of same type or not
if isinstance(self, set2):
# creating new object of self object type
new = self.__class__()
# calling super class union method and iterating over the returned set
for element in super().union(self, set2):
# calling add method of new object with element as argument
new.add(element)
# retuning new object
return new
# if the set2 is not self object type, raising WrongTypeError
else:
raise WrongTypeError(("b", self.typedset_type))

# overloading __and__ operator   
def __and__(self, set2):
# calling intersection method
return self.intersection(set2)

# overridding intersection method of super class (self)
def intersection(self, set2):
if isinstance(self, set2):
new = self.__class__()
for element in super().intersection(self, set2):
new.add(element)
return new
else:
raise WrongTypeError(("b", self.typedset_type))

# overloading __or__ operator
def __xor__(self, set2):
return self.symmetric_difference(set2)

# overriding symmetric_difference method of super class(set)
def symmetric_difference(self, set2):
if isinstance(self, set2):
new = self.__class__()
for element in super().symmetric_difference(set2):
new.add(element)
return new
else:
raise WrongTypeError(("b", self.typedset_type))

  
  

s1 = TypedSet()
s1.update([1, 5, 3, 1, 3])
s2 = TypedSet()
s2.update([5, 3, 8, 4])
print("sorted of s1 | s2 : ", sorted(s1|s2))
print("sorted of s1 & s2 : ", sorted(s1&s2))
print("sorted of s1 ^ s2 : ", sorted(s1^s2))
print(type(s1|s2) == TypedSet)
print(sorted(s1), sorted(s2))
print()

s1 = TypedSet()
s1.update([1, 5, 3, 1, 3])
s2 = TypedSet()
s2.update(["a", "b", "c"])
print(sorted(s1), sorted(s2))
print(s1&s2)

output:

these are the output pic when some code is runned though script mode:


Related Solutions

(i just need an answer for question 4) (i just need an answer for just question...
(i just need an answer for question 4) (i just need an answer for just question 4) you have two facilities, one in Malaysia and one in Indonesia. The variable cost curve in the Malaysian plant is described as follows: VCM = q­ + .0005*q2 , where q is quantity produced in that plant per month. The variable cost curve in the Indonesian plant is described by VCI = .5q + .00075q2, where q is the quantity produced in that...
Want clear answer for part a and b plz; Assume that an individual is risk-averse and...
Want clear answer for part a and b plz; Assume that an individual is risk-averse and has a utility function regarding income that can is described mathematically as U =√Y. The benefits of increased income are positive, but declining marginal utility. A person with that benefit function knows that there is a ten (10) percent risk of being ill. He is in average sick every ten days. The person receives 1,000 dollar per day when he works, which means that...
PLEASE THIS IS THE THIRD TIME I AM POSTING THIS QUESTION I WANT A COMPLET WORK...
PLEASE THIS IS THE THIRD TIME I AM POSTING THIS QUESTION I WANT A COMPLET WORK SO I CAN GET GOOD GRADES analyze at least three different marketing examples that will help inform marketing plan. 1 What product or service is being marketed 2 What media each uses for marketing the service? 3 How effective the marketing is for you the potential consumer (support why with specifics)? 4 Why is each company marketing and why did they choose the style...
I don't want explanation , I just want a correct answer, Very quickly. 12- If the...
I don't want explanation , I just want a correct answer, Very quickly. 12- If the slope of the consumption function is equal to one, then Select one: a. The multiplier is undefined b. The multiplier is smaller than one c. The multiplier is just one d. The multiplier is larger than one e. None of the above 11- If the nominal interest rate 8% and expected inflation 5%, the expected real interest rate in year t is approximately Select...
Please, I need a correct answer and clear explanation. Thank you, Part I – Explanation Q1...
Please, I need a correct answer and clear explanation. Thank you, Part I – Explanation Q1 Below are pairs of changes that affect elements of the accounting equation. Give an example of a transaction or economic event that reflects each: a. Asset increases, asset decreases b. Asset increases, liability increases c. Asset increases, shareholders’ equity increases d. Asset increases, revenue increases e. Liability decreases, asset decreases f. Asset decreases, expense increases g. Liability decreases, revenue increases h. Asset decreases, shareholders’...
ONLY FILL OUT THE TABLE AND ANSWER THE QUESTION BELOW THE TABLE Third workout design –...
ONLY FILL OUT THE TABLE AND ANSWER THE QUESTION BELOW THE TABLE Third workout design – Low Back Pain (5 points) Your client is a 52 year-old woman that injured her lower back at work 5 years ago, and has been managing low back pain on and off ever since. She now takes anti-inflammatory medication regularly, but not every day. She has tightness and pain in her back with prolonged sitting or standing. She is moderately overweight, has not exercised...
please I want you to answer this question and most importantly, the answer is not already...
please I want you to answer this question and most importantly, the answer is not already available on this site or other site Course Learning Outcome: Apply Organizational behavior knowledge and skills to manage diversified culture in the organizational settings (Lo 2.2). Essay: Differences in Culture and Diversity at workplace Essay Write an essay about the differences in Culture and Diversity at workplace. Use examples, peer-reviewed journals to support your answer. This essay must be at least 1000-word in length....
Note: Plesae I want a clear and justified answer Trentware plc is a medium-sized pottery manufacturer...
Note: Plesae I want a clear and justified answer Trentware plc is a medium-sized pottery manufacturer which is based in the English Potteries. The company has fared badly over the last 10 years, mainly as a result of Japanese competition, and recently this has led to major changes at the senior management level. The new managing director is determined to increase the company’s market share, and you are a member of the ambitious new management team which intends to extend...
I just want this answer to be in simple and easy words without missing the key...
I just want this answer to be in simple and easy words without missing the key words, to be easy for memorizing and understanding for my test.. please help We, as engineers, do not injure directly or indirectly the prospect of another engineer. In the same time, we shall be faithful and honest with our client and employer. In discharging our duty and carrying our works, we shall bear in mind that fair and honest dealing with all parties is...
In the following problems answer is given in bracket, I just want the steps how to...
In the following problems answer is given in bracket, I just want the steps how to get them: (a). Calculate the % of each DRY product when coal is burned stoichiometrically in air. The mass analysis of the coal is: 80% C; 10% H2; 5% S; and 5% ash.(76.7%N, 22.5%CO2; 0.8% SO2) (b). Find the air fuel ratio for stoichiometric combustion of Butane by volume. Calculate the percentage of carbon dioxide present in the DRY flue gas if 30% excess...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT