Skip to content

Instantly share code, notes, and snippets.

@vinay13
Created October 10, 2015 11:15
Show Gist options
  • Save vinay13/a62df5e7d9e2f047c3d6 to your computer and use it in GitHub Desktop.
Save vinay13/a62df5e7d9e2f047c3d6 to your computer and use it in GitHub Desktop.
class MyDict(dict):
def __init__(self):
self=dict()
def addItem(self,key,value):
if key in self:
self[key] +=value
else:
self[key]=value
def delItem(self,key,value):
if key in self:
self[key] -=value
myd=MyDict()
myd.addItem('apples',6)
myd.addItem('bananas',3)
myd.addItem('apples',4)
myd.delItem('apples',1)
print (myd)
class Item(object):
def __init__(self,unq_id,name,price,qty):
self.unq_id=unq_id
self.product_name=name
self.price=price
self.qty=qty
class Cart(object):
def __init__(self):
self.content = dict()
def update(self, item):
if item.unq_id not in self.content:
self.content.update({item.unq_id: item})
return
for k, v in self.content.get(item.unq_id).items():
if k == 'unq_id':
continue
elif k == 'qty':
total_qty = v.qty + item.qty
if total_qty:
v.qty = total_qty
continue
self.remove_item(k)
else:
v[k] = item[k]
def get_total(self):
return sum([v.price * v.qty for _, v in self.content.items()])
def get_num_items(self):
return sum([v.qty for _, v in self.content.items()])
def remove_item(self, key):
self.content.pop(key)
if __name__=='__main__':
item1=Item(1,"Banana",1.,3)
item2=Item(2,"Apple",2.5,2)
cart=Cart()
cart.update(item1)
cart.update(item2)
cart.remove_item(1)
#print("you have %i items in your cart " , cart.get_num_items())
print ("You have %i items in your cart for a total of $%.02f" %(cart.get_num_items(),cart.get_total()))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment