面试题答案
一键面试def check_conditions(data, nums, text):
for value in data.values():
if isinstance(value, list) and len(value) > 2:
if sum(nums) > 100 and 'error' not in text:
return True
return False
优化思路和技巧:
- 提前返回:一旦找到满足
data
中值为长度大于2的列表的键值对,就立刻检查其他条件,如果都满足则提前返回True
,避免不必要的循环。 - 使用生成器表达式:如果数据量非常大,可以考虑将
sum(nums)
替换为生成器表达式,例如sum((num for num in nums))
,这样在计算和的过程中可以减少内存占用,适用于大数据量的情况。 - 短路求值:Python的逻辑运算符
and
和or
具有短路特性,如代码中的sum(nums) > 100 and 'error' not in text
,当sum(nums) <= 100
时,后面的'error' not in text
就不会被执行,提高了效率。