Shopping Baskets with + and len()
Python
30 pts
Shopping Baskets with + and len()
Create a class Basket:
__init__(self, owner)stores the owner and an empty listself.items.add(name, price)adds the tuple(name, price)toself.items.total()returns the sum of all prices.__len__returns the number of items.__add__(other)returns a newBasketwhose owner is"Owner1 & Owner2"and whose items are the items of both baskets. The two original baskets must not change.
The code at the bottom is ready. Expected output:
2 3 Selam & Abel 155
Checklist
- Define a class
Basketthat stores the owner and an empty list of items, with anadd(name, price)method. - Add
__len__so thatlen(basket)gives the number of items. - Add
total(), which returns the sum of all prices. - Add
__add__so thatbasket1 + basket2returns a new combined basket and leaves the original baskets unchanged. - Run the code at the bottom.
🔑 Solution
If you view the solution before passing, you earn half points for this exercise. You still need to type it and press Check to finish.
How it works, step by step
Point at a step to highlight its lines. Type the solution yourself and press Check answer to finish.
