gpt4 book ai didi

python - wordList 中的两个元素

转载 作者:太空宇宙 更新时间:2023-11-03 14:38:28 24 4
gpt4 key购买 nike

我有这样一个功能:

def ladderLength(self, beginWord, endWord, wordList):
"""
:type beginWord: str
:type endWord: str
:type wordList: List[str]
:rtype: int
"""
if (endWord not in wordList) or (beginWord not in wordList):
return 0

多个bool操作很麻烦。

    if (endWord not in wordList) or (beginWord not in wordList):
return 0

如何让它变得简洁明了?

最佳答案

如果你所有的 if-block 都是这样的:

  if (endWord not in wordList) or (beginWord not in wordList):
return 0
else: # <- I am assuming this, see Note 1
return 1

然后你可以将整个东西替换为:

return int(all(x in wordList for x in (endWord, beginWord)))

Note 1

Not having an else clause is generally perfectly fine but in your case you would have a function that might return 0 or None and that is not optimal\recommended. If you can, redesign it as per above.

If not, I wouldn't bother changing the condition. The one you have is very readable and there are no alternatives that are much better. Sure you could do:

if not all(x in wordList for x in (endWord, beginWord)):
return 0

but that is pretty much it.

关于python - wordList 中的两个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55490414/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com