The Most Expensive First
A long receipt is easier to read when the most expensive lines come first: you see at once what the money went on. So the receipt will be sorted by the price of its lines, from the highest.
From the lesson on sorting, you know that sorted() can take a key function in key: it calls the function on each element and sorts the elements by what it returns. With reverse=True, the largest come first. For a list of objects, you write the key function yourself:
class Book:
def __init__(self, title, pages):
self.title = title
self.pages = pages
def by_pages(book):
return book.pages
books = [Book("Matilda", 240), Book("The Hobbit", 310), Book("Momo", 280)]
for book in sorted(books, key=by_pages, reverse=True):
print(book.title)The Hobbit
Momo
MatildaThe function goes into key without parentheses: key=by_pages. You give sorted() the function itself, and it calls it on each book. With parentheses, Python would call it right away, with no book, and the program ends with TypeError: by_pages() missing 1 required positional argument: 'book'.
In print_receipt(), use sorted(), not .sort(). sorted() gives a new list and leaves the cart as it was, while items.sort() would rearrange the cart itself. A function that prints the cart shouldn't change it.
Instructions
- 1
Above
print_receipt(), write a key functionby_line_total(item)that returns the price of the item's line,item.line_total(). - 2
In
print_receipt(), let the loop go throughsorted(items, key=by_line_total, reverse=True)instead ofitems. The receipt then starts withChocolate: 3 x $5 = $15and ends withBread: 2 x $3 = $6, and the total stays$54.