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
相关产品推荐
相关产品推荐

