Conversation
| if word == endWord: | ||
| return num_steps | ||
| for i in range(len(word)): | ||
| for alpha_offset in range(26): |
There was a problem hiding this comment.
マジックナンバーを使っているので、自分ならstring.ascii_lowercaseを使うか、26は別で定義します。
| @@ -0,0 +1,80 @@ | |||
| 1回目。答えを見た。 | |||
| 変数名がキャメルケースなのは違和感があるが、入力がキャメルケースなので少し納得した。 | |||
There was a problem hiding this comment.
leetcodeならば、関数名はともかく、引数となっている変数名に関しては変更可能です。
There was a problem hiding this comment.
Python の標準的な naming convention では、snake 使いますね。
https://peps.python.org/pep-0008/#naming-conventions
Python は呼び出し方が、位置とキーワードの2つがあるので、本当は変更すると動かなくなる可能性はあります。
def f(pos1, pos2, /, pos_or_kwd, *, kwd1, kwd2):https://docs.python.org/3/tutorial/controlflow.html#special-parameters
| return num_steps | ||
| for i in range(len(word)): | ||
| for alpha_offset in range(26): | ||
| transformed_word = word[:i] + chr(ord('a') + alpha_offset) + word[i + 1:] |
There was a problem hiding this comment.
ord('a') + alpha_offsetという部分に関して、以下のリンクが参考になるかもしれません。
t0hsumi/leetcode#12 (comment)
| return num_steps | ||
| for i in range(len(word)): | ||
| for alpha_offset in range(26): | ||
| transformed_word = word[:i] + chr(ord('a') + alpha_offset) + word[i + 1:] |
There was a problem hiding this comment.
文字列の連結には、f-stringもしくはjoinを使うと良いと思います。
https://google.github.io/styleguide/pyguide.html#310-strings
There was a problem hiding this comment.
これは知りませんでした。ありがとうございます!
| for i in range(len(word)): | ||
| for ch in range(26): | ||
| transformed = word[:i] + chr(ord('a') + ch) + word[i+1:] | ||
| if transformed in wordSet: |
There was a problem hiding this comment.
ネストが深すぎるため、ぱっと見て読むのに負荷を感じました。
意味のある単位で処理を区切ったメソッドを利用できると読みやすくなりそうです。
| return steps | ||
|
|
||
| for i in range(len(word)): | ||
| for ch in range(26): |
There was a problem hiding this comment.
個人的にはこの解答だと入力の対象になる文字列が英語小文字以外から増えた時に困るなあと思いました
There was a problem hiding this comment.
確かにそうですね。こちらで指摘されているように、string.ascii_lowercase を使うとよいかもしれないと思いました。
SuperHotDogCat/coding-interview#45 (comment)
https://leetcode.com/problems/word-ladder/