Editor

Shopping Cart Class

#604 · Classes · Intermediate · Review the AI's code · 70 XP · about 10 min

Someone asked an AI assistant: "Write a Cart class with methods to add items, remove items, count the items and get the total price." This is its answer. It looks right, but it has a bug.

Cart() starts empty. Its methods:

  • add(name, price, quantity=1) puts quantity units of an item in the cart. Adding an item that is already in the cart increases its quantity, and the item keeps the price it was first added at.
  • remove(name) takes the item out completely. Removing an item that is not in the cart does nothing.
  • count() returns the total number of units in the cart.
  • total() returns the price of everything in the cart, rounded to 2 decimal places.

Examples

cart = Cart()
cart.add('shirt', 15.0)
cart.add('socks', 4.5, 2)
cart.count()   # returns 3
cart.total()   # returns 24.0
cart.add('shirt', 15.0)
cart.count()   # returns 4

Constraints

  • At most 100 different items; prices are from 0 to 1,000 and quantities from 1 to 100.

Fastest solvers

Leaderboard

First solves only, ranked by stars and then time.