How to sort pizza starting with the lowest price?


With the knowledge i have, my answer sorts only the pizza toppings not the price list, the task is to sort the pizzas starting with the lowest price. How can i do it using the knowledge given by codeacademy till this topic?
Thanks

2 Likes

Hi again,
It’s kinda advanced, but I’ll try to explain it.
So the sort function accepts a parameter called key, this is what we’ll need to use.
The key parameter is to specify a function to be called on each list element prior to making comparisons.
This is the way we’ll have to use it:

pizzas.sort(key=lambda pizza : pizza[1])

A lambda function is a small anonymous function.
It is used:
lambda arguments : expression
Basically what we’re doing, is that python will pass a parameter into the lambda function which is the pure value, for example if the list we call sort on is a simple list:

nums = [1,2,3,4]

then it will pass in 1 then 2 then 3 then 4 or the way the sorting algorithm is written.
But in our case it passes in firstly ('anchovies', 7) then ('cheese', 1) and so on.
In our case when passing the lambda function as key, our lambda function returns the price and the sorting algorithm sorts it based on the returned value (price)
Here’s the python wiki.

I hope this helps :grinning:

2 Likes

If you dobule check the previous instruction it suggests creating the list with prices ordered first. In this case .sort() would operate on the first sublist in the list pizzas and would therefore sort as expected. So at this stage in the lessons it would probably be best just to stick to the instructions.
inst0
Sorting with a key and lambda is a perfectly reasonable method but if I remember rightly lambda functions would not have been covered in the course previously, not would using the key parameter of the list.sort() method.

Edit: Double checked and loops haven’t been introduced either so at this stage in the lessons forget about this bit too.
You could create a sorting algorithm for example using loops and if statements but it is a bit of a push at this stage in the lessons. Sorting algorithms are a cornerstone of computer science and are included as part of the computer science path in CodeAcademy but they won’t pop up for a while (assuming this is the path you’re on) and I’d advise you to skip over them for now. That is, of course, entirely up to you.

4 Likes