提问人:Abhijit Sarkar 提问时间:10/26/2023 最后编辑:Abhijit Sarkar 更新时间:10/27/2023 访问量:201
查找最后一个单词的长度
Find the length of the last word
问:
我正在研究 LeetCode 58。最后一句话的长度。
给定一个由单词和空格组成的字符串 s,返回字符串中最后一个单词的长度。
单词是仅由非空格字符组成的最大子字符串。
例:
输入: s = “带我飞到月球”
输出: 4
解释:最后一个词是“月亮”,长度为 4。
这可以按如下方式轻松解决:
return len(s.split()[-1])
假设这个问题是在面试中被问到的,习惯上会施加人为的限制,所以,假设内置的或不能使用。没关系。split
splitlines
from operator import methodcaller, not_
from itertools import takewhile, dropwhile
def lengthOfLastWord(s: str) -> int:
space = methodcaller("isspace")
word = takewhile(not_(space), dropwhile(space, s[::-1]))
return len(list(word))
这给了我以下错误:
TypeError: 'bool' object is not callable
return len(list(word))
当然,我可以使用 lambda 代替 ,但知道我需要使用相同的函数,上述尝试似乎更优雅。在像Haskell这样的语言中,我将能够简单地直接使用。Python 不是 Haskell,那么,我如何获得相同的效果呢?methodcaller
isspace
isSpace
not . isSpace
请注意,还有其他方法可以解决这个问题,例如使用反向循环。我不是在寻找其他或更好的选项,只是如何通过否定 返回的可调用对象来使上述代码工作。for
methodcaller
答:
虽然您当前的实验只是一项简单任务的过度复杂化,但这里有一种方法可以修复您的方法的基础。
与其否定空格字符检查,不如检查当前剥离字符的真实性,因为空字符串的计算结果为:False
from itertools import takewhile
def length_last_word(s: str) -> int:
func = str.strip
word = takewhile(func, s[::-1].strip())
return len(list(word))
s = " fly me to the moon "
print(length_last_word(s)) # 4
评论
strip
func
word = itertools.takewhile(str.isalnum, itertools.dropwhile(str.isspace, s[::-1]))
isspace
.
str.isalnum
cross-site
s = " fly me to the know-how "
您只需创建一个否定 isspace 方法结果的 lambda 函数,即可在不丢失代码结构的情况下实现所需的输出。这是你如何做到的-
from operator import methodcaller
from itertools import takewhile, dropwhile
def lengthOfLastWord(s: str) -> int:
space = methodcaller("isspace")
not_space = lambda x: not space(x)
word = takewhile(not_space, dropwhile(space, s[::-1]))
return len(list(word))
# Example usage:
s = " fly me to the moon "
result = lengthOfLastWord(s)
print(result) # Output: 4
你需要的是一个函数,它接受一个可调用对象并返回一个包装函数,该函数将调用可调用对象并返回其返回值 not'd。not_
由于 Python 标准库中没有内置这样的高阶函数,因此您只需要自己编写一个:
def complement(func):
def wrapper(*args, **kwargs):
return not func(*args, **kwargs)
return wrapper
因此:
def lengthOfLastWord(s: str) -> int:
space = methodcaller("isspace")
word = takewhile(complement(space), dropwhile(space, s[::-1]))
return len(list(word))
print(lengthOfLastWord(" fly me to the moon "))
输出:4
评论
complement
OP在这里;我确定了以下几点:
def lengthOfLastWord(s: str) -> int:
word = itertools.takewhile(str.isalnum, itertools.dropwhile(str.isspace, s[::-1]))
return len(list(word))
评论
str.isalnum
不会涵盖像 .所以它会失败cross-site
s = " fly me to the know-how "
评论
operator.not_
_