[Tutor] Ummmmmm, suggestions please?
Joseph J. Strout
joe@strout.net
Wed, 16 Jun 1999 09:03:38 -0700
At 5:29 AM -0700 06/16/99, Kenneth M. Power wrote:
>What I want is to accumulate like items into a group. Thus by putting
>two (2) boxes into my Inven(tory), I would get this result:
>
>room1.show()
>Item Volume
>Box(2) 10 #Or something similar
>Total Volume: 10
>
>Any suggestions on how to accomplish this?
This is what dictionaries are for. Each unique key in a dictionary maps to
some value. Basically, try this (untested code):
def show(self):
qtys = {} # empty dictionary mapping items to qty of that item
totals = {} # empty dictionary mapping items to their total volume
for item in self.contents:
if item in qtys.keys():
# something we've seen already!
qtys[item] = qtys[item] + 1
totals[item] = totals[item] + item.cube
else:
# not something we've seen already
qtys[item] = 1
totals[item] = item.cube
# now we have totals, print 'em out
for item in qtys.keys():
print "%s(%d)\t\t%f" % (item.name, qtys[item], totals[item])
If you don't want a (1) after single items, then you'll need to use an if
statement to get you to a different print format.
If anything in the above isn't clear, just let me know...
Cheers,
-- Joe
,------------------------------------------------------------------.
| Joseph J. Strout Biocomputing -- The Salk Institute |
| joe@strout.net http://www.strout.net |
`------------------------------------------------------------------'