I want to build the function such that:
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.
Example:
For beginWord = "hit"
, endWord = "cog"
, and wordList = ["hot", "dot", "dog", "lot", "log", "cog"]
, the output should be
wordLadder(beginWord, endWord, wordList) = 5
The shortest transformation is "hit" -> "hot" -> "dot" -> "dog" -> "cog"
with a length of 5.
My attempt:
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
But I don't know how to break from second loop (while
).
How can I do this?