wordList中都没有元素

时间:2019-04-03 08:24:43

标签: python

我有这样的功能:

var mymodel = new PersonViewModel();

...

return View(mymodel);

多次布尔操作很麻烦。

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

如何使其变得简洁明了?

3 个答案:

答案 0 :(得分:4)

如果您的if块全部是这样:

  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)))

  

注释1

     

没有else子句通常是完全可以的,但是在您的情况下,您将拥有一个可能返回0None的函数,并且该函数不是最佳的\建议。如果可以,请按照上面的说明重新设计。

     

如果没有的话,我不会费心更改条件。您所拥有的是一个很好的可读性,没有其他更好的选择。当然可以:

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

但这差不多。

答案 1 :(得分:0)

我认为这应该可行。

   if any([x not in wordList for x in [endWord, beginWord]]):
        return 0

答案 2 :(得分:0)

如果您希望此功能加快速度(O(log n)而不是O(n))-请考虑将wordList的{​​{1}}类型更改。在这种情况下,功能将是:

Set[str]