查找最后一个单词的长度

Find the length of the last word

提问人:Abhijit Sarkar 提问时间:10/26/2023 最后编辑:Abhijit Sarkar 更新时间:10/27/2023 访问量:201

问:

我正在研究 LeetCode 58。最后一句话的长度

给定一个由单词和空格组成的字符串 s,返回字符串中最后一个单词的长度。

单词是仅由非空格字符组成的最大子字符串。

例:

输入: s = “带我飞到月球”

输出: 4

解释:最后一个词是“月亮”,长度为 4。

这可以按如下方式轻松解决:

return len(s.split()[-1])

假设这个问题是在面试中被问到的,习惯上会施加人为的限制,所以,假设内置的或不能使用。没关系。splitsplitlines

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,那么,我如何获得相同的效果呢?methodcallerisspaceisSpacenot . isSpace

请注意,还有其他方法可以解决这个问题,例如使用反向循环。我不是在寻找其他或更好的选项,只是如何通过否定 返回的可调用对象来使上述代码工作。formethodcaller

python-itertools python-operator

评论

0赞 Codist 10/26/2023
什么是not_(空间)?MRE将很有用 stackoverflow.com/help/minimal-reproducible-example
1赞 Abhijit Sarkar 10/26/2023
@Codist、 添加了导入。operator.not_
0赞 Codist 10/26/2023
没有_not运算符,即使有,您的代码仍会引起 NameError 异常
2赞 Alexey S. Larionov 10/26/2023
我个人并不觉得它优雅,而是不必要的过度设计。恕我直言
0赞 Abhijit Sarkar 10/26/2023
@Codist 这是一个错别字,在最后。现在显示的代码是 MRE_

答:

2赞 RomanPerekhrest 10/26/2023 #1

虽然您当前的实验只是一项简单任务的过度复杂化,但这里有一种方法可以修复您的方法的基础。
与其否定空格字符检查,不如检查当前剥离字符的真实性,因为空字符串的计算结果为:
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

评论

0赞 Abhijit Sarkar 10/26/2023
如果我们要使用 ,我认为没有必要,因为这是可以做到的。我给你投了赞成票,因为我没有意识到像这样的函数可以用作引用,因为它是使用 .stripfuncword = itertools.takewhile(str.isalnum, itertools.dropwhile(str.isspace, s[::-1]))isspace.
0赞 RomanPerekhrest 10/26/2023
@AbhijitSarkar,不会涵盖像 .所以它会失败str.isalnumcross-sites = " fly me to the know-how "
0赞 iDibya.com 10/26/2023 #2

您只需创建一个否定 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
1赞 blhsing 10/26/2023 #3

你需要的是一个函数,它接受一个可调用对象并返回一个包装函数,该函数将调用可调用对象并返回其返回值 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

演示:https://ideone.com/taGtmS

评论

1赞 Abhijit Sarkar 10/26/2023
"没有内置这样的高阶函数“是我所追求的。赞成票。
1赞 Kelly Bundy 10/26/2023
Funcy 称它为 Complement,可能是一个更好的名字。
0赞 blhsing 10/27/2023
@KellyBundy 啊,很棒的包,适合那里的函数式编程爱好者。 确实是一个更合适的名字。谢谢。complement
-2赞 Abhijit Sarkar 10/26/2023 #4

OP在这里;我确定了以下几点:

def lengthOfLastWord(s: str) -> int:
    word = itertools.takewhile(str.isalnum, itertools.dropwhile(str.isspace, s[::-1]))
    return len(list(word))

评论

1赞 RomanPerekhrest 10/26/2023
str.isalnum不会涵盖像 .所以它会失败cross-sites = " fly me to the know-how "
0赞 Abhijit Sarkar 10/26/2023
@RomanPerekhrest 问题指出约束 “s 仅由英文字母和空格 ' '.这就是我链接到原始问题的原因。