Information about cookies on this page

Our website uses cookies to ensure the functionality of the website, to collect and analyze information about the performance and usage of the website. Privacy Policy

  • Courses
    • Discord
    • Twitter
    • Linkedin
    • Facebook
    • Instagram
  • Pricing
  • English
  • Čeština
  • Deutsch
  • Русский
Sign inStart free
  • Courses
  • Pricing

Community

Sign in
  
  • Courses
    • Discord
    • Twitter
    • Linkedin
    • Facebook
    • Instagram
  • Pricing
  • English
  • Čeština
  • Deutsch
  • Русский
Sign inStart free
  • Courses
  • Pricing

Community

Sign in

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
Matilda

The 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. 1

    Above print_receipt(), write a key function by_line_total(item) that returns the price of the item's line, item.line_total().

  2. 2

    In print_receipt(), let the loop go through sorted(items, key=by_line_total, reverse=True) instead of items. The receipt then starts with Chocolate: 3 x $5 = $15 and ends with Bread: 2 x $3 = $6, and the total stays $54.

Back

8/9

  1. 1. The Shopping Cart
  2. 2. The Price of a Line
  3. 3. The Total
  4. 4. Free Delivery
  5. 5. Adding Items
  6. 6. The Same Item Twice
  7. 7. Reading the Order
  8. 8. The Most Expensive First
  9. 9. Congratulations!
Next

Try it yourself

Do this exercise right here in your browser. No account needed.