Created
March 9, 2019 07:50
-
-
Save tirinox/7fb5606c99dc6e6f878d10619661f5b2 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import operator | |
class Item: | |
def __init__(self, name, price, qty): | |
self.name = name | |
self.price = price | |
self.qty = qty | |
def total_cost(self): | |
return self.price * self.qty | |
def __repr__(self): | |
return f'({self.name} ${self.price} x {self.qty} = ${self.total_cost()})' | |
items = [ | |
Item("iPhone", 999, 5), | |
Item("iMac", 2999, 2), | |
Item("iPad", 599, 11) | |
] | |
def print_items(title, item_list): | |
print(title) | |
print(*item_list, sep=', ', end='\n\n') | |
print_items('Original:', items) | |
items_by_price = sorted(items, key=operator.attrgetter('price')) | |
print_items('Sorted by price:', items_by_price) | |
items_by_total_cost = sorted(items, key=operator.methodcaller('total_cost')) | |
print_items('Sorted by total cost:', items_by_total_cost) | |
""" | |
Original: | |
(iPhone $999 x 5 = $4995), (iMac $2999 x 2 = $5998), (iPad $599 x 11 = $6589) | |
Sorted by price: | |
(iPad $599 x 11 = $6589), (iPhone $999 x 5 = $4995), (iMac $2999 x 2 = $5998) | |
Sorted by total cost: | |
(iPhone $999 x 5 = $4995), (iMac $2999 x 2 = $5998), (iPad $599 x 11 = $6589) | |
""" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment