Create 127WordLadder.md#20
Conversation
| def ladderLength(self, begin_word: str, end_word: str, word_list: List[str]) -> int: | ||
| # 計算量は文字数×単語数の階乗 | ||
| # 多すぎるきがする | ||
| num_c = len(begin_word) |
|
|
||
| 動きません。 | ||
|
|
||
| けっこう時間を費やしてしまったので、次回以降は解法がわからなければ解答をすぐ見る |
There was a problem hiding this comment.
発想の仕方はありますが、とはいえ、さっさと答えを見ていいと思います。
5分考えて手が止まったら、調べるくらいがいいように思っています。
だいたいコメント集からたどれます。
https://docs.google.com/document/d/11HV35ADPo9QxJOpJQ24FcZvtvioli770WWdZZDaLOfg/edit?tab=t.0
| ```python | ||
| class Solution: | ||
| def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int: | ||
| num_word = len(beginWord) |
There was a problem hiding this comment.
num_word ですと、単語の数という意味に感じます。 word_length のほうが直感的だと思います。
| def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int: | ||
| num_word = len(beginWord) | ||
| word_queue = deque([(beginWord, 1)]) | ||
| word_set = set(wordList) |
There was a problem hiding this comment.
自分は変数名には型を表す単語は含めないことが多いのです。ただ、今回は wordList が list 型で、それに対して word_set と定義しているため、悩ましいところです。
|
|
||
| while word_queue: | ||
| word, step = word_queue.popleft() | ||
| result = search_end_word(word, step) |
There was a problem hiding this comment.
search_end_word() の中で word_queue に要素が追加されるという流れが読み取りづらいように感じました。この程度の分量であれば、インラインで書いてしまってもよいと思います。
| queue = deque([(beginWord, 1)]) | ||
| while queue: | ||
| word, step = queue.popleft() | ||
| next_words = get_next_words(word) | ||
| next_step = step + 1 | ||
| for target in next_words: | ||
| if target == endWord: | ||
| return next_step | ||
| queue.append((target, next_step)) |
There was a problem hiding this comment.
好みですが、get_next_words()は階層的(あるwordに対して、次の遷移可能な語を全て出している)な一方で、queueの方はiterativeに出し入れしていることが違和感に感じました。
ぼくなら、ネストが深くなりますがfor next_word in get_next_words(word)としてiterativeに書いていくか、下のようにqueueをあるステップで遷移可能な語でまとめ上げるかなと思います。
words = [beginWord]
num_transformations = 1
while words:
next_words = []
for word in words:
if word == endWord:
return num_transformations
next_words.extend(get_next_words(word))
words = next_words
num_transformations += 1There was a problem hiding this comment.
There was a problem hiding this comment.
その視点はありませんでした。ありがとうございます。
| # まず入出力を合わせる | ||
| num_c = len(beginWord) | ||
|
|
||
| def is_one_diff(x, y): |
There was a problem hiding this comment.
こちらでも問題なさそうですがis_adjacentとか他の候補もありそうです!
https://leetcode.com/problems/word-ladder/description/