Python: Shopping Cart
The task is to implement two classes: ShoppingCart and Item according to the following requirements:
Item
– An item is instantiated using the constructor Item(name: str, price: int) where the name denotes the name of the item, and the price denotes the price of the item.
– Its name can be retrieved as a normal attribute, that is, if item is an instance of Item, then item.name returns the name of the item.
ShoppingCart
– A shopping cart is instantiated using a constructor without arguments, i.e. ShoppingCart()
– It has a method add(item: Item) that adds the given item to the cart. An item may be added to the cart multiple times. An item will be added each time the add method is called.
– It has a method, total() -> int, that returns the sum of the prices of all items currently in the cart.
– Calling len(cart) where the cart is an instance of a ShoppingCart returns the number of items in the cart.
Implementations of the classes will be tested by a provided code stub and several input files that contain parameters. First, the stub initializes instances of Items an instance of the ShoppingCart. Next, it performs the given operations on the ShoppingCart instance. The result of their executions will be printed to the standard output by the provided code.
Constraints
- There will be at most 5 different items.
- There will be at most 500 operations to perform on the cart.
SOLUTION:
#!/bin/python3
import math
import os
import random
import re
import sys
class Item:
def __init__(self, name: str, price: int):
self.name = name
self.price = price
class ShoppingCart:
def __init__(self):
self.items = []
def add(self, item: Item):
self.items.append(item)
def total(self) -> int:
return sum(item.price for item in self.items)
def __len__(self):
return len(self.items)
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
n = int(input())
items = []
for _ in range(n):
name, price = input().split()
item = Item(name, int(price))
items.append(item)
cart = ShoppingCart()
q = int(input())
for _ in range(q):
line = input().split()
command, params = line[0], line[1:]
if command == "len":
fptr.write(str(len(cart)) + "\n")
elif command == "total":
fptr.write(str(cart.total()) + "\n")
elif command == "add":
name = params[0]
item = next(item for item in items if item.name == name)
cart.add(item)
else:
raise ValueError("Unknown command %s" % command)
fptr.close()