I think your main focus should be readability and the underlying data structure.
Something like this is very readable and (likely) as high performance as you can achieve by rolling you own:
from collections import Counter
class Fridge(object):
def __init__(self,things,name):
self.things=Counter(things)
self.wanted=set()
self.name=name
def look(self, thing):
print 'There are {} {} in {}'.format(self.things[thing],thing,self.name)
def stare_inside(self):
cathave=sorted([(co,it) for it,co in self.things.items() if co])
print '{} items in {}:'.format(len(cathave),self.name)
for i, item in enumerate(cathave,1):
print ' {}: {} -- {}'.format(i,item[1],item[0])
def shop(self):
shop_list=[it for it,co in self.things.items() if co==0]
for item in shop_list:
del self.things[item]
shop_list.extend(list(self.wanted))
self.wanted=set()
print "shopping list:"
for i, item in enumerate(sorted(shop_list),1):
print ' {}: {}'.format(i,item)
def consume(self,thing,count):
if self.things[thing]>=count:
self.things[thing]-=count
else:
print 'Not enough {} to consume {} -- {} in the {}.'.format(
thing,count,self.things[thing],self.name)
self.wanted.add(thing)
def stock(self,things):
self.things+=Counter(things)
Now try it:
>>> kitchen=Fridge({'coke':2, 'whole milk':1,'ketchup':1, 'anchovies':24},'kitchen fridge')
>>> kitchen.look('coke')
There are 2 coke in kitchen fridge
>>> kitchen.stock({'coke':1,'pepsi':2,'banana':3})
>>> kitchen.stare_inside()
6 items in kitchen fridge:
1: ketchup -- 1
2: whole milk -- 1
3: pepsi -- 2
4: banana -- 3
5: coke -- 3
6: anchovies -- 24
>>> kitchen.consume('red bull',22)
Not enough red bull to consume 22 -- 0 in the kitchen fridge.
>>> kitchen.consume('coke',3)
>>> kitchen.consume('whole milk',1)
>>> kitchen.stare_inside()
4 items in kitchen fridge:
1: ketchup -- 1
2: pepsi -- 2
3: banana -- 3
4: anchovies -- 24
>>> kitchen.shop()
shopping list:
1: coke
2: red bull
3: whole milk
This is based on the collection module Counter class. You are unlikely to come up with something that is native Python that is faster.