How do you Change valuemycollection () function to use higher level functions like reduce and map. or Use lambda function as a function argument.
from cards import Card
from functools import reduce
myCards = []
def readcardinfo (f):
# read info from file for 1 card (5 lines) and return the Card
instance to the main program.
# use f.readline to read each attribute value and assign to the
instance attributes below
team = f.readline().strip()
name = f.readline().strip()
cardyear = int(f.readline().strip())
cardcondition = f.readline().strip()
cardvalue = int(f.readline().strip())
return Card (team, name,cardyear,cardcondition,cardvalue)
class Card:
def __init__(self, team, name,cardyear,cardcondition,cardvalue):
self.team = team
self.name = name
self.cardyear = cardyear
self.cardcondition = cardcondition
self.cardvalue = int (cardvalue)
def __str__ (self):
return "{:<20s} {:<15s} {:4d} {:4s} {:5d}".format(self.team,
self.name, self.cardint, self.cardcondition, self.cardvalue)
def __lt__ (self, other):
return self.cardvalue < other.cardvalue
def updatevalue (self, newvalue):
self.cardvalue = newvalue
def getvalue(self):
return self.cardvalue
def printmycollection ():
# change to print (c) using __str__ class method
for c in myCards:
print(c)
def sortmycollectionbyvalue ():
# define __lt__ class method
myCards.sort ()
def updatesandykoufaxvalue ():
#define updatevalue () mutator class method and getvalue() extractor
method
for i in myCards:
if i.name == "Sandy Koufax":
break
i.updatevalue (i.getvalue() 1000)
def valuemycollection ():
#change to use reduce () high level function.
collvalue = 0
for i in myCards:
collvalue = i.getvalue ()
return collvalue
def main ():
f = open ("players.txt", "r")
# append Card instances (5) read from file
for i in range (5):
myCards.append (readcardinfo (f))
f.close ()
printmycollection ()
sortmycollectionbyvalue ()
print ("I own $%d in baseball cards!" %(valuemycollection ()))
updatesandykoufaxvalue () # increase by $1000
sortmycollectionbyvalue ()
printmycollection ()
print ("I own now $%d in baseball cards!" %(valuemycollection
()))
if __name__ == "__main__":
main ()
CodePudding user response:
Sum function makes more sense
def valuemycollection():
return sum(i.getvalue() for i in myCards)