Files
python-bootcamp/max submission/6_7_HW.py
T
2023-06-07 17:58:22 -05:00

132 lines
3.4 KiB
Python

# question 1: Read this: https://docs.python.org/3/reference/datamodel.html?highlight=__int__#object.__int__
# question 2:
class BoundedInt():
def __init__(self, i, min, max):
"""
Create a bounded integer.
Args:
i (int): The initial value of the integer.
min (int): The minimum value of the integer.
max (int): The maximum value of the integer.
"""
self.i = i
self.min = min
self.max = max
def __int__(self):
return self.i
# question 3:Read this, and the paragraph below it: https://docs.python.org/3/reference/datamodel.html?highlight=__int__#object.__add__
# question 4: Without checking the debugger's local window, I would guess that x and y are integer values. Actually,
# they can be objects of any type.
# question 6:
class BoundedInt:
def __init__(self, i, min=None, max=None):
self.i = i
self.min = min
self.max = max
def __int__(self):
return self.i
def __add__(self, other):
result = self.i + other
if result > self.max:
raise ValueError("Value exceeds maximum bound.")
return BoundedInt(result, self.min, self.max)
def __radd__(self, other):
return self.__add__(other)
def __repr__(self):
return str(self.i)
# question 7:
class BoundedInt:
def __init__(self, i, min=None, max=None):
self.i = i
self.min = min
self.max = max
def __int__(self):
return self.i
def __sub__(self, other):
result = self.i - other
if result < self.min:
raise ValueError("Value exceeds minimum bound.")
return BoundedInt(result, self.min, self.max)
def __rsub__(self, other):
return self.__sub__(other)
def __repr__(self):
return str(self.i)
# question 8:
class BoundedInt():
def __init__(self, i, min, max):
self.i = i
self.min = min
self.max = max
def __int__(self):
return self.i
def __add__(self, other):
if isinstance(other, BoundedInt):
result = self.i + other.i
else:
result = self.i + other
if result > self.max:
raise ValueError("Result exceeds max value")
return BoundedInt(result, self.min, self.max)
# question 9:
class BoundedInt():
def __init__(self, i, min, max):
self.i = i
self.min = min
self.max = max
def __int__(self):
return self.i
def __sub__(self, other):
if isinstance(other, BoundedInt):
result = self.i - other.i
else:
result = self.i - other
if result < self.min:
raise ValueError("Result exceeds min value")
return BoundedInt(result, self.min, self.max)
# question 10:
class BoundedInt():
def __init__(self, i, min_val, max_val):
self.i = i
self.min = min
self.max = max
def __int__(self):
return self.i
def __add__(self, other):
if isinstance(other, BoundedInt):
result = self.i + other.i
elif isinstance(other, int):
result = self.i + other
elif isinstance(other, emoji):
raise ValueError("Cannot add a BoundedInt to an emoji.")
else:
raise TypeError("Unsupported operand type.")
if result > self.max:
raise ValueError("Sum exceeds maximum value.")