How do you Change valuemycollection () function to use higher level functions like reduce and map. or Use lambda function as a function argument.
JavaScript
x
72
72
1
from cards import Card
2
from functools import reduce
3
4
5
myCards = []
6
def readcardinfo (f):
7
# read info from file for 1 card (5 lines) and return the Card
8
instance to the main program.
9
# use f.readline to read each attribute value and assign to the
10
instance attributes below
11
team = f.readline().strip()
12
name = f.readline().strip()
13
cardyear = int(f.readline().strip())
14
cardcondition = f.readline().strip()
15
cardvalue = int(f.readline().strip())
16
return Card (team, name,cardyear,cardcondition,cardvalue)
17
18
class Card:
19
def __init__(self, team, name,cardyear,cardcondition,cardvalue):
20
self.team = team
21
self.name = name
22
self.cardyear = cardyear
23
self.cardcondition = cardcondition
24
self.cardvalue = int (cardvalue)
25
def __str__ (self):
26
return "{:<20s} {:<15s} {:4d} {:4s} {:5d}".format(self.team,
27
self.name, self.cardint, self.cardcondition, self.cardvalue)
28
def __lt__ (self, other):
29
return self.cardvalue < other.cardvalue
30
def updatevalue (self, newvalue):
31
self.cardvalue = newvalue
32
def getvalue(self):
33
return self.cardvalue
34
35
def printmycollection ():
36
# change to print (c) using __str__ class method
37
for c in myCards:
38
print(c)
39
def sortmycollectionbyvalue ():
40
# define __lt__ class method
41
myCards.sort ()
42
def updatesandykoufaxvalue ():
43
#define updatevalue () mutator class method and getvalue() extractor
44
method
45
for i in myCards:
46
if i.name == "Sandy Koufax":
47
break
48
i.updatevalue (i.getvalue() + 1000)
49
def valuemycollection ():
50
#change to use reduce () high level function.
51
collvalue = 0
52
for i in myCards:
53
collvalue += i.getvalue ()
54
return collvalue
55
def main ():
56
f = open ("players.txt", "r")
57
# append Card instances (5) read from file
58
for i in range (5):
59
myCards.append (readcardinfo (f))
60
f.close ()
61
printmycollection ()
62
sortmycollectionbyvalue ()
63
print ("I own $%d in baseball cards!" %(valuemycollection ()))
64
updatesandykoufaxvalue () # increase by $1000
65
sortmycollectionbyvalue ()
66
printmycollection ()
67
print ("I own now $%d in baseball cards!" %(valuemycollection
68
()))
69
70
if __name__ == "__main__":
71
main ()
72
Advertisement
Answer
Sum function makes more sense
JavaScript
1
3
1
def valuemycollection():
2
return sum(i.getvalue() for i in myCards)
3