|
| 1 | +# exercise 8.2.2 from unit 8 |
| 2 | +''' |
| 3 | +Exercise 8.2.2 |
| 4 | +Write a function called sort_prices defined as follows: |
| 5 | +
|
| 6 | +def sort_prices(list_of_tuples): |
| 7 | +The function receives a list of tuples that each have an item and a price. |
| 8 | +The function returns a list of tuples sorted by the price of the items in them from the largest to the smallest. |
| 9 | +
|
| 10 | +Define the list of tuples that the function receives according to the following form: |
| 11 | +
|
| 12 | +[('item', 'price'), ('item', 'price'), ('item', 'price')] |
| 13 | +Note that all members are of string type and price is written as a non-integer number. |
| 14 | +
|
| 15 | +Running examples of the sort_prices function |
| 16 | +>>> products = [('milk', '5.5'), ('candy', '2.5'), ('bread', '9.0')] |
| 17 | +>>> sort_prices(products) |
| 18 | +[('bread', '9.0'), ('milk', '5.5'), ('candy', '2.5')] |
| 19 | +''' |
| 20 | + |
| 21 | +def sort_prices(list_of_tuples): |
| 22 | + def get_price(tuple): |
| 23 | + return float(tuple[1]) |
| 24 | + |
| 25 | + # sort the list of tuples by the price of the item in each tuple |
| 26 | + sorted_list = sorted(list_of_tuples, key=get_price, reverse=True) |
| 27 | + return sorted_list |
| 28 | + |
| 29 | +# test the function |
| 30 | +products = [('milk', '5.5'), ('candy', '2.5'), ('bread', '9.0')] |
| 31 | +print(sort_prices(products)) |
0 commit comments