LeetCode 题解工作台
方法链
DataFrame animals +-------------+--------+ | Column Name | Type | +-------------+--------+ | name | object | | species | object | | age | int | | weig…
0
题型
1
代码语言
0
相关题
当前训练重点
简单 · Method Chaining core interview pattern
答案摘要
import pandas as pd def findHeavyAnimals(animals: pd.DataFrame) -> pd.DataFrame:
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 Method Chaining core interview pattern 题型思路
题目描述
DataFrame animals
+-------------+--------+
| Column Name | Type |
+-------------+--------+
| name | object |
| species | object |
| age | int |
| weight | int |
+-------------+--------+
编写一个解决方案来列出体重 严格超过 100 千克的动物的名称。
按体重 降序 返回动物。
返回结果格式如下示例所示。
示例 1:
输入: DataFrame animals: +----------+---------+-----+--------+ | name | species | age | weight | +----------+---------+-----+--------+ | Tatiana | Snake | 98 | 464 | | Khaled | Giraffe | 50 | 41 | | Alex | Leopard | 6 | 328 | | Jonathan | Monkey | 45 | 463 | | Stefan | Bear | 100 | 50 | | Tommy | Panda | 26 | 349 | +----------+---------+-----+--------+ 输出: +----------+ | name | +----------+ | Tatiana | | Jonathan | | Tommy | | Alex | +----------+ 解释: 所有体重超过 100 的动物都应包含在结果表中。 Tatiana 的体重为 464,Jonathan 的体重为 463,Tommy 的体重为 349,Alex 的体重为 328。 结果应按体重降序排序。
在 Pandas 中,方法链 允许我们在 DataFrame 上执行操作,而无需将每个操作拆分成单独的行或创建多个临时变量。
你能用 一行 代码的方法链完成这个任务吗?
解题思路
方法一
import pandas as pd
def findHeavyAnimals(animals: pd.DataFrame) -> pd.DataFrame:
return animals[animals['weight'] > 100].sort_values('weight', ascending=False)[
['name']
]
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Evaluate the candidate's ability to implement method chaining cleanly and concisely.
- question_mark
Assess whether the candidate understands the importance of readable and efficient code.
- question_mark
Check how the candidate handles both filtering and sorting operations in a single, streamlined code flow.
常见陷阱
外企场景- error
Failing to apply method chaining properly, leading to overly complex or less readable code.
- error
Incorrectly ordering the method calls, which may result in unexpected outputs.
- error
Forgetting to check for edge cases, such as an empty DataFrame or no animals above 100 kilograms.
进阶变体
外企场景- arrow_right_alt
Introduce additional filtering conditions, such as filtering based on species or age.
- arrow_right_alt
Instead of sorting by weight, sort by another property, like age or name.
- arrow_right_alt
Use a different type of data structure for storing animals, such as a list of dictionaries, to apply method chaining in a different context.