You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

LeetCode58:如何否定methodcaller返回的可调用对象求解单词长度

解决operator.not_否定methodcaller可调用对象的TypeError问题

问题原因

你遇到的TypeError: 'bool'对象不可调用,本质是对operator.not_的用法理解偏差:

  • operator.methodcaller('isspace')返回的是一个可调用对象,作用是接收字符后调用其isspace()方法。
  • operator.not_是对值取反的一元函数,它会直接计算传入参数的布尔取反结果,而非返回一个新的可调用对象。当你写not_(methodcaller('isspace'))时,实际是计算not methodcaller('isspace')——由于methodcaller对象本身是真值,结果为False(一个布尔值),而takewhile需要的是可调用对象,因此触发报错。

解决方案

要否定methodcaller返回的可调用对象,你需要创建一个新的可调用对象:它接收输入后,先调用原methodcaller函数,再对结果取反。由于你不想用lambda,可通过自定义高阶函数实现:

代码示例

from itertools import takewhile, dropwhile
from operator import methodcaller

# 高阶函数:接收一个可调用对象,返回其否定版的可调用对象
def negate(func):
    def wrapper(x):
        return not func(x)
    return wrapper

# 生成否定isspace判断的可调用对象
negate_isspace = negate(methodcaller('isspace'))

# 处理LeetCode第58题逻辑
s = "Hello World  "
# 反转字符串→跳过开头空格(对应原字符串末尾空格)→取连续非空格字符
last_word = takewhile(negate_isspace, dropwhile(methodcaller('isspace'), reversed(s)))
print(len(list(last_word)))  # 输出:5

内容的提问来源于stack exchange,提问作者Abhijit Sarkar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 23:35:30