Python – Sorts the list of numbers based on the index

Sorts the list of numbers based on the index… here is a solution to the problem.

Sorts the list of numbers based on the index

I need to create a program with a class that creates the object “Food” and a list called “fridge” that contains these objects created by the class “Food”.

class Food:
    def __init__(self, name, expiration):
        self.name = name
        self.expiration = expiration

fridge = [Food("beer",4), Food("steak",1),  Food("hamburger",1),  Food("donut",3),]

It’s not that hard. Then I created a function that will give you the food with the highest expiry date.

def exp(fridge):
    expList=[]
    xen = 0
    for i in range(0,len(fridge)):
        expList.append(fridge[xen].expiration)
        xen += 1
    print(expList)
    sortedList = sorted(expList)
    return sortedList.pop()

exp(fridge)

This one also works, now I have to create a function to return a list where the index of the list is the expiration date and the number of the index is the number of food with that expiration date.
The output should look like this: [0,2,1,1] – The first index 0 indicates that there is no food with an expiration date of “0”. Index 1 indicates that there are 2 food items left with 1 left in their shelf life. And so on. I’m stuck with too many if lines and I can’t get it to work at all. How should I handle this? Thanks for your help.

Solution

In order to return it as a list, you first need to calculate the maximum shelf life in the refrigerator.

max_expiration = max(food.expiration for food in fridge) +1 # need +1 since 0 is also a possible expiration
exp_list = [0] * max_expiration
for food in fridge:
    exp_list[food.expiration] += 1
print(exp_list)

Returns [0, 2, 0, 1

, 1].

Related Problems and Solutions