Question: Hello please see below is a homework question I am working on for this week. Please help me fix the code so it will work
Hello please see below is a homework question I am working on for this week. Please help me fix the code so it will work properly in Cengage?
Thank you for all your help in advanced.
Question 9.3
Elena The__str__method of theBankclass (inbank.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 thebankclass 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 theSavingsAccountclass (insavingsaccount.py).
The__eq__method should returnTrueif the account names are equal during a comparison,Falseotherwise.
The__it__method should returnTrueif the name of one account is less than the name of another,Falseotherwise.
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
Code:
Bank.py
"""
File:bank.py
Project9.3
ThestrforBankreturnsastringofaccountssortedbyname.
"""
importpickle
importrandom
fromsavingsaccountimportSavingsAccount
classBank:
"""Thisclassrepresentsabankasacollectionofsavingsaccounts.
Anoptionalfilenameisalsoassociated
withthebank,toallowtransferofaccountstoand
frompermanentfilestorage."""
"""Thestateofthebankisadictionaryofaccountsandafilename.IfthefilenameisNone,afilenameforthebankhasnotyetbeenestablished."""
def__init__(self,fileName=None):
"""Createsanewdictionarytoholdtheaccounts.
Ifafilenameisprovided,loadstheaccountsfrom
afileofpickledaccounts."""
self.accounts={}
self.fileName=fileName
iffileName!=None:
fileObj=open(fileName,'rb')
whileTrue:
try:
account=pickle.load(fileObj)
self.add(account)
exceptException:
fileObj.close()
break
def__str__(self):
"""Returnsthestringrepresentationofthebank."""
#TODO:Sorttheaccountvaluesbeforeprintingtothescreen
return" ".join(map(str,self.accounts.values()))
defmakeKey(self,name,pin):
"""Returnsakeyfortheaccount."""
returnname+"/"+pin
defadd(self,account):
"""Addstheaccounttothebank."""
key=self.makeKey(account.getName(),account.getPin())
self.accounts[key]=account
defremove(self,name,pin):
"""Removestheaccountfromthebankand
andreturnsit,orNoneiftheaccountdoes
notexist."""
key=self.makeKey(name,pin)
returnself.accounts.pop(key,None)
defget(self,name,pin):
"""Returnstheaccountfromthebank,
orreturnsNoneiftheaccountdoes
notexist."""
key=self.makeKey(name,pin)
returnself.accounts.get(key,None)
defcomputeInterest(self):
"""Computesandreturnstheintereston
allaccounts."""
total=0
foraccountinself._accounts.values():
total+=account.computeInterest()
returntotal
defgetKeys(self):
"""Returnsasortedlistofkeys."""
return[]
defsave(self,fileName=None):
"""Savespickledaccountstoafile.Theparameter
allowstheusertochangefilenames."""
iffileName!=None:
self.fileName=fileName
elifself.fileName==None:
return
fileObj=open(self.fileName,'wb')
foraccountinself.accounts.values():
pickle.dump(account,fileObj)
fileObj.close()
#Functionsfortesting
defcreateBank(numAccounts=1):
"""Returnsanewbankwiththegivennumberof
accounts."""
names=("Brandon","Molly","Elena","Mark","Tricia",
"Ken","Jill","Jack")
bank=Bank()
upperPin=numAccounts+1000
forpinNumberinrange(1000,upperPin):
name=random.choice(names)
balance=float(random.randint(100,1000))
bank.add(SavingsAccount(name,str(pinNumber),balance))
returnbank
deftestAccount():
"""Testfunctionforsavingsaccount."""
account=SavingsAccount("Ken","1000",500.00)
print(account)
print(account.deposit(100))
print("Expect600:",account.getBalance())
print(account.deposit(-50))
print("Expect600:",account.getBalance())
print(account.withdraw(100))
print("Expect500:",account.getBalance())
print(account.withdraw(-50))
print("Expect500:",account.getBalance())
print(account.withdraw(100000))
print("Expect500:",account.getBalance())
defmain(number=10,fileName=None):
"""Createsandprintsabank,eitherfrom
theoptionalfilenameargumentorfromtheoptional
number."""
testAccount()
##iffileName:
##bank=Bank(fileName)
##else:
##bank=createBank(number)
##print(bank)
if__name__=="__main__":
main()
Savingsaccount.py
"""
File:savingsaccount.py
ThismoduledefinestheSavingsAccountclass.
"""
classSavingsAccount:
"""Thisclassrepresentsasavingsaccount
withtheowner'sname,PIN,andbalance."""
RATE=0.02#Singlerateforallaccounts
def__init__(self,name,pin,balance=0.0):
self.name=name
self.pin=pin
self.balance=balance
def__str__(self):
"""Returnsthestringrep."""
result='Name:'+self.name+' '
result+='PIN:'+self.pin+' '
result+='Balance:'+str(self.balance)
returnresult
defgetBalance(self):
"""Returnsthecurrentbalance."""
returnself.balance
defgetName(self):
"""Returnsthecurrentname."""
returnself.name
defgetPin(self):
"""Returnsthecurrentpin."""
returnself.pin
defdeposit(self,amount):
"""Iftheamountisvalid,addsit
tothebalanceandreturnsNone;
otherwise,returnsanerrormessage."""
self.balance+=amount
returnNone
defwithdraw(self,amount):
"""Iftheamountisvalid,sunstractit
fromthebalanceandreturnsNone;
otherwise,returnsanerrormessage."""
ifamount<0:
return"Amountmustbe>=0"
elifself.balance return"Insufficientfunds" else: self.balance-=amount returnNone defcomputeInterest(self): """Computes,deposits,andreturnstheinterest.""" interest=self.balance*SavingsAccount.RATE self.deposit(interest) returninterest def__eq__(self,other): """ReturnsTrueifnamesareequalorFalseotherwise.""" #TODO:Implementthelogicforaccountnamecomparisons returnself.name==other.name def__lt__(self,other): """ReturnsTrueifnameofselfislessthan nameofother,orFalseotherwise.""" #TODO:Implementthelogicforlessthancomparisons returnself.name
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
