Method Chaining Solution in Python

Problem Description

So, you want to find heavy animals? Well, welcome to the club! The problem is as straightforward as trying to find your keys in a messy room. You have a DataFrame of animals, each with a name and a weight. Your task is to filter out the heavyweights—those that tip the scales at over 100 units. And just to make it a bit more interesting, you need to sort them in descending order of their weight. Because who doesn’t want to know which animal could potentially crush a car?

Imagine you’re at a zoo, and you’re trying to figure out which animals you should avoid in a wrestling match. Spoiler alert: it’s the heavy ones!

Code Solution

import pandas as pd

def findHeavyAnimals(animals: pd.DataFrame) -> pd.DataFrame:
    return animals[animals['weight'] > 100].sort_values(
        by='weight',
        ascending=False
    )[['name']]

Approach

The approach here is as simple as pie. You filter the DataFrame to include only those animals whose weight exceeds 100. Then, you sort the resulting DataFrame in descending order based on weight. Finally, you return just the names of these heavyweights. It’s like going to a buffet and only picking the dishes that are over 100 calories—no one wants to know about the salad!

Time and Space Complexity

Time Complexity: O(n log n), where n is the number of animals. This is due to the sorting operation.

Space Complexity: O(n), as we are storing the filtered DataFrame.

Real-World Example

Think of this as a weight-loss program for animals. You want to identify which animals are eligible for a diet plan. You filter out the ones that are already lightweights (under 100) and focus on the heavyweights. This way, you can create a tailored diet plan for those who need it the most.

Similar Problems

If you enjoyed this problem, you might also like these:

  • 2-Sum Solution in Python