The __str__ method of the Bank class (in bank.py) returns a string containing the accounts in random order. Design and implement a change that causes the accounts to be placed in the string in ascending order of name. Implement the __str__ method of the bank class so that it sorts the account values before printing them to the console. In order to sort the account values you will need to define the __eq__ and __lt__ methods in the SavingsAccount class (in savingsaccount.py). The __eq__ method should return True if the account names are equal during a comparison, False otherwise. The __lt__ method should return True if the name of one account is less than the name of another, False otherwise. The program should output in the following format: Test for createBank: Name: Jack PIN: 1001 Balance: 653.0 Name: Mark PIN: 1000 Balance: 377.0 ... ... ... Name: Name7 PIN: 1006 Balance: 100.0

Computer Networking: A Top-Down Approach (7th Edition)
7th Edition
ISBN:9780133594140
Author:James Kurose, Keith Ross
Publisher:James Kurose, Keith Ross
Chapter1: Computer Networks And The Internet
Section: Chapter Questions
Problem R1RQ: What is the difference between a host and an end system? List several different types of end...
icon
Related questions
Question

The __str__ method of the Bank class (in bank.py) returns a string containing the accounts in random order. Design and implement a change that causes the accounts to be placed in the string in ascending order of name.

Implement the __str__ method of the bank class so that it sorts the account values before printing them to the console.

In order to sort the account values you will need to define the __eq__ and __lt__ methods in the SavingsAccount class (in savingsaccount.py).

The __eq__ method should return True if the account names are equal during a comparison, False otherwise.

The __lt__ method should return True if the name of one account is less than the name of another, False otherwise.

The program should output in the following format:

Test for createBank: Name: Jack PIN: 1001 Balance: 653.0 Name: Mark PIN: 1000 Balance: 377.0 ... ... ... Name: Name7 PIN: 1006 Balance: 100.0

 

 

bank.py

 

"""
File: bank.py
Project 9.3
The str for Bank returns a string of accounts sorted by name.
"""
import pickle
import random
from savingsaccount import SavingsAccount

class Bank:
    """This class represents a bank as a collection of savings accounts.
    An optional file name is also associated
    with the bank, to allow transfer of accounts to and
    from permanent file storage."""

    """The state of the bank is a dictionary of accounts and a file name.  If the file name is None, a file name for the bank has not yet been established."""

    def __init__(self, fileName = None):
        """Creates a new dictionary to hold the accounts.
        If a file name is provided, loads the accounts from
        a file of pickled accounts."""
        self.accounts = {}
        self.fileName = fileName
        if fileName != None:
            fileObj = open(fileName, 'rb')
            while True:
                try:
                    account = pickle.load(fileObj)
                    self.add(account)
                except Exception:
                    fileObj.close()
                    break

    def __str__(self):
        """Returns the string representation of the bank."""
        nameSort = sorted(self.accounts)
        return "\n".join(map(str, nameSort))

    def makeKey(self, name, pin):
        """Returns a key for the account."""
        return name + "/" + pin

    def add(self, account):
        """Adds the account to the bank."""
        key = self.makeKey(account.getName(), account.getPin())
        self.accounts[key] = account

    def remove(self, name, pin):
        """Removes the account from the bank and
        and returns it, or None if the account does
        not exist."""
        key = self.makeKey(name, pin)
        return self.accounts.pop(key, None)

    def get(self, name, pin):
        """Returns the account from the bank,
        or returns None if the account does
        not exist."""
        key = self.makeKey(name, pin)
        return self.accounts.get(key, None)

    def computeInterest(self):
        """Computes and returns the interest on
        all accounts."""
        total = 0
        for account in self._accounts.values():
            total += account.computeInterest()
        return total

    def getKeys(self):
        """Returns a sorted list of keys."""
        return []

    def save(self, fileName = None):
        """Saves pickled accounts to a file.  The parameter
        allows the user to change file names."""
        if fileName != None:
            self.fileName = fileName
        elif self.fileName == None:
            return
        fileObj = open(self.fileName, 'wb')
        for account in self.accounts.values():
            pickle.dump(account, fileObj)
        fileObj.close()

# Functions for testing
       
def createBank(numAccounts = 1):
    """Returns a new bank with the given number of 
    accounts."""
    names = ("Brandon", "Molly", "Elena", "Mark", "Tricia",
             "Ken", "Jill", "Jack")
    bank = Bank()
    upperPin = numAccounts + 1000
    for pinNumber in range(1000, upperPin):
        name = random.choice(names)
        balance = float(random.randint(100, 1000))
        bank.add(SavingsAccount(name, str(pinNumber), balance))
    return bank

def testAccount():
    """Test function for savings account."""
    account = SavingsAccount("Ken", "1000", 500.00)
    print(account)
    print(account.deposit(100))
    print("Expect 600:", account.getBalance())
    print(account.deposit(-50))
    print("Expect 600:", account.getBalance())
    print(account.withdraw(100))
    print("Expect 500:", account.getBalance())
    print(account.withdraw(-50))
    print("Expect 500:", account.getBalance())
    print(account.withdraw(100000))
    print("Expect 500:", account.getBalance())

def main(number = 10, fileName = None):
    """Creates and prints a bank, either from
    the optional file name argument or from the optional
    number."""

    if fileName:
        bank = Bank(fileName)
    else:
        bank = createBank(number)
    print(bank)

if __name__ == "__main__":
    main()
 
 
I am just about to the character limit on this question so the other file will be in images.
```python
"""
File: savingsaccount.py
This module defines the SavingsAccount class.
"""

class SavingsAccount:
    """This class represents a savings account
    with the owner's name, PIN, and balance."""

    RATE = 0.02  # Single rate for all accounts

    def __init__(self, name, pin, balance = 0.0):
        self.name = name
        self.pin = pin
        self.balance = balance

    def __str__(self):
        """Returns the string rep."""
        result = 'Name:    ' + self.name + '\n'
        result += 'PIN:     ' + self.pin + '\n'
        result += 'Balance: ' + str(self.balance)
        return result

    def getBalance(self):
        """Returns the current balance."""
        return self.balance

    def getName(self):
        """Returns the current name."""
        return self.name

    def getPin(self):
        """Returns the current pin."""
        return self.pin

    def deposit(self, amount):
        """If the amount is valid, adds it
        to the balance and returns None;
        otherwise, returns an error message."""
        self.balance += amount
        return None

    def withdraw(self, amount):
        """If the amount is valid, subtract it
        from the balance and returns None;
        otherwise, returns an error message."""
        if amount < 0:
            return "Amount must be >= 0"
        elif self.balance < amount:
            return "Insufficient funds"
        else:
            self.balance -= amount
            return None

    def computeInterest(self):
        """Computes, deposits, and returns the interest."""
        interest = self.balance * SavingsAccount.RATE
        self.deposit(interest)
        return interest

    def __eq__(self, other):
        """Returns True if names are equal or False otherwise."""
        returnValue = False
        if isinstance(other, savingsaccount):
            if self.name == other.name:
                returnValue = True
        return returnValue

    def __lt__(self, other):
        """Returns True if name of self is less than
        the name of other, or False otherwise."""
        returnValue = False
        if isinstance(other, savingsaccount):
            if self.name < other.name:
                returnValue = True
        return returnValue
```

### Explanation

This Python script defines a class named `
Transcribed Image Text:```python """ File: savingsaccount.py This module defines the SavingsAccount class. """ class SavingsAccount: """This class represents a savings account with the owner's name, PIN, and balance.""" RATE = 0.02 # Single rate for all accounts def __init__(self, name, pin, balance = 0.0): self.name = name self.pin = pin self.balance = balance def __str__(self): """Returns the string rep.""" result = 'Name: ' + self.name + '\n' result += 'PIN: ' + self.pin + '\n' result += 'Balance: ' + str(self.balance) return result def getBalance(self): """Returns the current balance.""" return self.balance def getName(self): """Returns the current name.""" return self.name def getPin(self): """Returns the current pin.""" return self.pin def deposit(self, amount): """If the amount is valid, adds it to the balance and returns None; otherwise, returns an error message.""" self.balance += amount return None def withdraw(self, amount): """If the amount is valid, subtract it from the balance and returns None; otherwise, returns an error message.""" if amount < 0: return "Amount must be >= 0" elif self.balance < amount: return "Insufficient funds" else: self.balance -= amount return None def computeInterest(self): """Computes, deposits, and returns the interest.""" interest = self.balance * SavingsAccount.RATE self.deposit(interest) return interest def __eq__(self, other): """Returns True if names are equal or False otherwise.""" returnValue = False if isinstance(other, savingsaccount): if self.name == other.name: returnValue = True return returnValue def __lt__(self, other): """Returns True if name of self is less than the name of other, or False otherwise.""" returnValue = False if isinstance(other, savingsaccount): if self.name < other.name: returnValue = True return returnValue ``` ### Explanation This Python script defines a class named `
Expert Solution
trending now

Trending now

This is a popular solution!

steps

Step by step

Solved in 4 steps with 7 images

Blurred answer
Recommended textbooks for you
Computer Networking: A Top-Down Approach (7th Edi…
Computer Networking: A Top-Down Approach (7th Edi…
Computer Engineering
ISBN:
9780133594140
Author:
James Kurose, Keith Ross
Publisher:
PEARSON
Computer Organization and Design MIPS Edition, Fi…
Computer Organization and Design MIPS Edition, Fi…
Computer Engineering
ISBN:
9780124077263
Author:
David A. Patterson, John L. Hennessy
Publisher:
Elsevier Science
Network+ Guide to Networks (MindTap Course List)
Network+ Guide to Networks (MindTap Course List)
Computer Engineering
ISBN:
9781337569330
Author:
Jill West, Tamara Dean, Jean Andrews
Publisher:
Cengage Learning
Concepts of Database Management
Concepts of Database Management
Computer Engineering
ISBN:
9781337093422
Author:
Joy L. Starks, Philip J. Pratt, Mary Z. Last
Publisher:
Cengage Learning
Prelude to Programming
Prelude to Programming
Computer Engineering
ISBN:
9780133750423
Author:
VENIT, Stewart
Publisher:
Pearson Education
Sc Business Data Communications and Networking, T…
Sc Business Data Communications and Networking, T…
Computer Engineering
ISBN:
9781119368830
Author:
FITZGERALD
Publisher:
WILEY