Reputation: 39
Write a sequence of statements that prints out the list of Restaurants RC in order from least expensive to most expensive (best dish). it should use the sort(), and key=restaurant_price as an argument to sort()
Given this code:
from collections import namedtuple
Restaurant = namedtuple('Restaurant', 'name cuisine phone dish price')
RC = [
Restaurant("Thai Dishes", "Thai", "334-4433", "Mee Krob", 12.50),
Restaurant("Nobu", "Japanese", "335-4433", "Natto Temaki", 5.50),
Restaurant("Nonna", "Italian", "355-4433", "Stracotto", 25.50)]
def restaurant_price (restaurant:Restaurant)-> float:
return restaurant.price
I wrote:
print(sort(RC,key=restaurant_price()))
My code gets an error statement of "name 'sort' is not defined"
Upvotes: 2
Views: 1777
Reputation: 180481
sort
is an inplace method that operates on the original list and returns None, you can use sorted:
print(sorted(RC,key=restaurant_price)) # creates new list
Using sorted:
In [23]: sorted(RC,key=restaurant_price)
Out[23]:
[Restaurant(name='Nobu', cuisine='Japanese', phone='335-4433', dish='Natto Temaki', price=5.5),
Restaurant(name='Thai Dishes', cuisine='Thai', phone='334-4433', dish='Mee Krob', price=12.5),
Restaurant(name='Nonna', cuisine='Italian', phone='355-4433', dish='Stracotto', price=25.5)]
Or call .sort on the list:
RC.sort(key=restaurant_price) # sort original list
print(RC)
.sort:
In [20]: RC.sort(key=restaurant_price)
In [21]: RC
Out[21]:
[Restaurant(name='Nobu', cuisine='Japanese', phone='335-4433', dish='Natto Temaki', price=5.5),
Restaurant(name='Thai Dishes', cuisine='Thai', phone='334-4433', dish='Mee Krob', price=12.5),
Restaurant(name='Nonna', cuisine='Italian', phone='355-4433', dish='Stracotto', price=25.5)]
To just get the names:
In [24]: [x.name for x in sorted(RC,key=restaurant_price)]
Out[24]: ['Nobu', 'Thai Dishes', 'Nonna']
without using an explicit for loop loop or zip:
from operator import itemgetter
print(list(map(itemgetter(0),sorted(RC,key=restaurant_price)))
['Nobu', 'Thai Dishes', 'Nonna']
Upvotes: 4