Python 单词列表中的两个元素都没有

Python 单词列表中的两个元素都没有,python,Python,我有这样一个功能: 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): ret

我有这样一个功能:

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 any([x not in wordList for x in [endWord, beginWord]]):
        return 0

如果所有
If
-块都执行以下操作:

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

附注1

没有
else
子句通常是很好的,但是在您的情况下,您可能会有一个返回
0
None
的函数,这不是最佳的\推荐的。如果可以,请按照上述要求重新设计

如果不是,我就不会费心去改变条件了。你有一个非常可读,没有比这更好的选择。当然你可以做到:

if not all(x in wordList for x in (endWord, beginWord)):
    return 0
但基本上就是这样


如果您希望这个函数加速一点(<代码> o(log n)< />代码>而不是<代码> o(n)< /代码> -考虑更改<代码>单词列表< /C> >类型> <代码> SET[STR] < /代码>。在这种情况下,功能将是:

def ladderLength(self, beginWord, endWord, wordList):
    """
    :type beginWord: str
    :type endWord: str
    :type wordList: Set[str]
    :rtype: int
    """
    return int(bool({beginWord, endWord} & wordList))

如果不满足条件,您会返回什么?它们并不麻烦。
def ladderLength(self, beginWord, endWord, wordList):
    """
    :type beginWord: str
    :type endWord: str
    :type wordList: Set[str]
    :rtype: int
    """
    return int(bool({beginWord, endWord} & wordList))