如何打破两个循环(while和for)

时间:2017-05-03 14:27:28

标签: python loops

我想构建这样的函数:

  

给出两个单词,beginWord和endWord,以及一个已批准的单词列表   单词,找到最短转换序列的长度   beginWord to endWord这样:

     
      
  • 一次只能更改一个字母
  •   
  • 每个转换后的单词必须存在于wordList中。
  •   
     

返回最短转换序列的长度,如果不是,则返回0   存在这样的转换序列。

示例:

对于beginWord = "hit"endWord = "cog"wordList = ["hot", "dot", "dog", "lot", "log", "cog"],输出应为

wordLadder(beginWord, endWord, wordList) = 5

最短的转换为"hit" -> "hot" -> "dot" -> "dog" -> "cog",长度为5。

我的尝试:

from collections import Counter

def wordLadder(beginWord, endWord, wordList):
    count = 0
    if endWord not in wordList:
        raise ValueError("endword is not in wordList")
    while True:
        for i in range(len(wordList)):
            common = Counter(beginWord) & Counter(wordList[i])
            if beginWord == endWord:
                break
            if sum(common.values()) == len(beginWord) - 1:
                beginWord = wordList[i]
                wordList = wordList[i:]
                count +=1
                break
            else:
                break

但我不知道如何摆脱第二轮(while)。 我怎么能这样做?

1 个答案:

答案 0 :(得分:1)

您可以通过引发自定义异常来摆脱嵌套循环。例如:

from collections import Counter

class Stop(Exception): pass

def wordLadder(beginWord, endWord, wordList):
    if endWord not in wordList:
        raise ValueError("endword is not in wordList")

    count = 0
    try:
        while True:
            for i in range(len(wordList)):
                common = Counter(beginWord) & Counter(wordList[i])
                if beginWord == endWord:
                    raise Stop
                if sum(common.values()) == len(beginWord) - 1:
                    beginWord = wordList[i]
                    wordList = wordList[i:]
                    count +=1
                    raise Stop
                else:
                    raise Stop
    except Stop:
        return count

beginWord = "hit"
endWord = "cog"
wordList = ["hot", "dot", "dog", "lot", "log", "cog"]

print(wordLadder(beginWord, endWord, wordList))

但是,这不会为您提供5所需的结果。我不清楚你的函数/算法如何能够找到当前编写的“最短转换序列”,即使能够终止这两个循环。