method remove_item that requires similar arguments as add_item. It should remove items that have been added to the shopping cart and are not required. This method should deduct the cost of these items from the current total and also update the items dict accordingly. If the quantity of items to be removed exceeds current quantity in cart, assume that all entries of that item are to be removed.
class ShoppingCart(object):
#constructor
def __init__(self):
self.total = 0
self.items = {}
#method to add items in the shoping cart
def add_item(self,item_name, quantity, price):
self.total += (price * quantity )
self.items[item_name] = quantity
#method to remove items
def remove_item(self,item_name, quantity, price):
keys = self.items.keys()
for keys,v in self.items.items():
if keys == item_name and quantity > self.items[keys]: #if item_name equals iterated item
self.total -= (price * quantity )
del( self.items[keys] )
del(self.items[keys])
self.total -= (quantity * price)
And there are test units to check
def test_add_item_hidden(self):
self.cart.add_item('Mango', 3, 10)
self.cart.add_item('Orange', 16, 10)
self.assertEqual(self.cart.total, 190, msg='Cart total not correct after adding items')
self.assertEqual(self.cart.items['Orange'], 16, msg='Quantity of items not correct after adding item')
The method remove_item
gives an error that dictionary changed size during iteration
even after trying to access via keys
as shown above