A Shopping Cart Object

Easy ⏱ 8 min 82% acceptance ★★★★★ 4.6
Implement Cart with methods add(name, price), remove(name) (silently ignoring unknown names), and total(). Items live in an internal dict of name → price; adding the same name twice overwrites the price.

Examples

Example 1
Input
c = Cart(); c.add('pen', 10); c.add('book', 250); c.remove('pen'); c.total()
Output
250
Explanation

Only the book remains.

Constraints

  • remove never raises.
  • total sums current prices.

Topics

OOPstateful methods

Companies

AmazonFlipkartMyntra

Hints

Hint 1

A dict keyed by name keeps it simple.

Hint 2

dict.pop(name, None) removes safely.

Loading the Python runtime… Run executes your code and shows printed output; Submit checks your function against this problem's examples.