In: Computer Science
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.
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: