Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

8.18 Implement a class myInt that behaves almost the same as the class int, exce

ID: 667185 • Letter: 8

Question

8.18 Implement a class myInt that behaves almost the same as the class int, except when
trying to add an object of type myInt. Then, this strange behavior occurs:
>>> x = myInt(5)
>>> x * 4
20
>>> x * (4 + 6)
50
>>> x + 6
'Whatever ...'

8.19 Implement your own string class myStr that behaves like the regular str class except
that:
• The addition (+) operator returns the sum of the lengths of the two strings (instead of
the concatenation).
• The multiplication (*) operator returns the product of the lengths of the two strings.
The two operands, for both operators, are assumed to be strings; the behavior of your implementation
can be undefined if the second operand is not a string.
>>> x = myStr('hello')
>>> x + 'universe'
13
>>> x * 'universe'
40

8.20 Develop a class myList that is a subclass of the built-in list class. The only difference
between myList and list is that the sort method is overridden. myList containers
should behave just like regular lists, except as shown next:
>>> x = myList([1, 2, 3])
>>> x
[1, 2, 3]
>>> x.reverse()
>>> x
[3, 2, 1]
>>> x[2]
1
>>> x.sort()
You wish...

8.23 Develop a class BankAccount that supports these methods:
• __init__(): Initializes the bank account balance to the value of the input argument,
or to 0 if no input argument is given
• withdraw(): Takes an amount as input and withdraws it from the balance
• deposit(): Takes an amount as input and adds it to the balance
• balance(): Returns the balance on the account
>>> x = BankAccount(700)
>>> x.balance())
700.00
>>> x.withdraw(70)
>>> x.balance()
630.00
>>> x.deposit(7)
>>> x.balance()
637.00

8.24 Implement a class Polygon that abstracts regular polygons and supports class methods:
• __init__(): A constructor that takes as input the number of sides and the side
length of a regular n-gon (n-sided polygon) object
• perimeter(): Returns the perimeter of n-gon object
• area(): returns the area of the n-gon object
Note: The area of a regular polygon with n sides of length s is

(s^(2)n)/(4tan(pi/n))

>>> p2 = Polygon(6, 1)
>>> p2.perimeter()
6
>>> p2.area()
2.5980762113533165

8.25 Implement class Worker that supports methods:
• __init__(): Constructor that takes as input the worker’s name (as a string) and the
hourly pay rate (as a number)
• changeRate(): Takes the new pay rate as input and changes the worker’s pay rate
to the new hourly rate
• pay(): Takes the number of hours worked as input and prints 'Not Implemented

Next develop classes HourlyWorker and SalariedWorker as subclasses of Worker. Each
overloads the inherited method pay() to compute the weekly pay for the worker. Hourly
workers are paid the hourly rate for the actual hours worked; any overtime hours above
40 are paid double. Salaried workers are paid for 40 hours regardless of the number of
hours worked. Because the number of hours is not relevant, the method pay() for salaried
workers should also be callable without an input argument.
>>> w1 = Worker('Joe', 15)
>>> w1.pay(35)
Not implemented
>>> w2 = SalariedWorker('Sue', 14.50)
>>> w2.pay()
580.0
>>> w2.pay(60)
580.0
>>> w3 = HourlyWorker('Dana', 20)
>>> w3.pay(25)
500
>>> w3.changeRate(35)
>>> w3.pay(25)
875

Explanation / Answer

8.18

class MyInt(int):
    """ Subset of int class with addition changed
    """
    def __add__(self, other):
        """ Returns whatever when the operator + is directly used on self
        """
        return 'Whatever ...'

x = MyInt(5)
print(x * 4)
print(x * (4 + 6))
print(x + 6)

8.19

class MyStr(str):
    """ Subset of str class with addition and multiplication changed
    """
    def __add__(self, other):
        """ Returns the sum of lengths of self and other (strings)
        """
        return len(self) + len(other)

    def __mul__(self, other):
        """ Returns the product of the lengths of the two strings
        """
        return len(self) * len(other)

x = MyStr('hello')
print(x + 'universe')
print(x * 'universe')

8.20

x = MyList([1, 2, 3])
print(x)
print(x.reverse())
print(x[2])
print(x.sort())

class NegativeBalanceError(Exception):
    pass


class OverdraftError(Exception):
    pass


class DepositError(Exception):
    pass


class BankAccount:
    """ creates a bank account
    """
    def __init__(self, bal=0):
        """ Constructor: Initializes bank account with bal as starting balance
        """

        # if bal < 0:
        #     raise ValueError('Illegal Balance')

        if bal < 0:
            raise NegativeBalanceError('Account created with negative balance: {}'.format(bal))
        self.bal = bal

    def __repr__(self):
        """
        """
        return '{0:.2f}'.format(self.bal)

    def withdraw(self, n):
        """ Removes n value from balance
        """

        # if n > self.bal:
        #     raise ValueError('Overdraft')
        # elif n < 0:
        #     raise ValueError('Negative Withdrawal')

        if n > self.bal:
            raise OverdraftError('Operation would result in negative balance: {}'.format(self.bal - n))

        self.bal -= n

    def deposit(self, n):
        """ Adds n value from balance
        """

        # if n < 0:
        #     raise ValueError('Negative Deposit')

        if n < 0:
            raise DepositError('Negative deposit: {}'.format(n))

        self.bal += n

    def balance(self):
        """ Returns the balance on the account
        """
        return eval('{0:.2f}'.format(self.bal))

x = BankAccount(700)
print(x.balance())
x.withdraw(70)
print(x.balance())
x.deposit(7)
print(x.balance())
x.withdraw(6.9801)
print(x.balance())

8.24

class Polygon:
    """ Abstracts regular polygons and supports class methods
    """

    def __init__(self, n=0, s=0):
        """ Constructor: initializes polygon with sides length (len) and number of sides (n)
        """
        self.length = s
        self.sides = n

    def perimeter(self):
        """ Returns the perimeter of the polygon
        """
        return self.length * self.sides

    def area(self):
        """ Returns the area of the polygon
        """
        return (self.length ** 2 * self.sides) / (4 * math.tan(math.pi / self.sides))

p2 = Polygon(6, 1)
print(p2.perimeter())
print(p2.area())

8.25

class Worker:
    """ Creates a basic worker namespace
    """
    def __init__(self, name='Unknown', rate=0.0):
        """ Constructor: takes name and the hourly pay rate of worker
        """
        self.name = name
        self.rate = rate

    def changerate(self, newrate):
        """ Takes the new pay rate as input and changes the worker's pay rate to the new hourly rate
        """
        self.rate = newrate

    def pay(self, hours):
        """ Takes the number of hours worked as input and prints 'Not Implemented'
        """
        return 'Not Implemented'


class HourlyWorker(Worker):
    """ inherits class worker; Overloads pay to compute the pay of the worker per hour
    """
    def pay(self, hours):
        """ Takes number of hours worked as input and returns the wage; any hours above 40 are paid double
        """
        if hours > 40:
            return 40 * self.rate + (hours - 40) * self.rate * 2
        return self.rate * hours


class SalariedWorker(Worker):
    """ Inherits class Worker; Overloads pay to compute the wage of the worker on a firm salary
    """
    def pay(self, hours=40):
        """ Returns the pay for 40 hours, regardless of how many hours were actually worked
        """
        return 40 * self.rate

w1 = Worker('Joe', 15)
print(w1.pay(35))

w2 = SalariedWorker('Sue', 14.50)
print(w2.pay())
print(w2.pay(60))

w3 = HourlyWorker('Dana', 20)
print(w3.pay(25))
w3.changerate(35)
print(w3.pay(25))

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote