Crimson
Crimson

Reputation: 155

How to write a nested for loop as a one liner?

Here is my function:

def find_how_many_pumpkins_are_needed_to_feed_animals(animal_list: list) -> int:
    """
    Find how many pumpkins are needed to feed all herbivorous and omnivorous animals in the Zoo.

    For the sake of this calculation, let's assume that there are 2 animals of each type at our zoo and each animal eats
    (on average) 6% of their body weight (average of values in the weight range) worth of pumpkins every day.
    One pumpkin weighs 3kg.
    Let's also assume that we are feeding the animals over the course of one 3-month-long winter (90 days)

    :param animal_list: input list
    :return: amount of pumpkins needed to sustain all the animals over the winter (rounded up).
    """
    cnt=0
    for i in range(90):
        for animal in animal_list:
            if animal.diet == "herbivorous" or animal.diet == "omnivorous":
                cnt += 2*(((animal.weight_range[0] + animal.weight_range[1]) / 2) * 0.06)
    return math.ceil(cnt/3) 

If I wanted to create the nested for loop into a one liner, how would I go about doing that?

Upvotes: 0

Views: 128

Answers (1)

Aplet123
Aplet123

Reputation: 35560

Since you're just summing values, you can use the sum function along with a generator function (also you run the loop 90 times then dividing by 3, but the loop isn't dependent on index, so you should just multiply the value by 30). You can also pull some of the multiplications out:

math.ceil(sum(((animal.weight_range[0] + animal.weight_range[1]) / 2) * 0.06 for animal in animal_list) * 30 * 2 * 0.06)

Here it is formatted in a more readable way:

math.ceil(
    sum(
        ((animal.weight_range[0] + animal.weight_range[1]) / 2) * 0.06
        for animal in animal_list
    )
    * 30 * 2 * 0.06
)

Upvotes: 2

Related Questions