我想构建这样的函数:
Given two words, beginWord and endWord, and a wordList of approved words, find the length of the shortest transformation sequence from beginWord to endWord such that:
- Only one letter can be changed at a time
- Each transformed word must exist in the wordList.
Return the length of the shortest transformation sequence, or 0 if no such transformation sequence exists.
示例:
对于 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
)中中断。
我怎样才能做到这一点?
最佳答案
您可以在 for
循环之后添加另一个 if beginWord == endWord:break
。如果第一个 break
条件得到满足,新的条件也将得到满足。
def wordLadder(beginWord, endWord, wordList):
count = 0
if endWord not in wordList:
raise ValueError("endword is not in wordList")
while True:
<b>if beginWord == endWord:
break</b>
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
但就您而言,return
可能更简单。
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:
<b>return</b>
if sum(common.values()) == len(beginWord) - 1:
beginWord = wordList[i]
wordList = wordList[i:]
count +=1
break
else:
break
关于python - 如何打破两个循环(while 和 for),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43762900/