142. linked list cycle II#3
Conversation
| - https://discord.com/channels/1084280443945353267/1246383603122966570/1252209488815984710 | ||
| - この説明を見る前は証明的なことをして数式で理解しに行ったが、直感的にも理解できるようになった! | ||
| - https://github.com/mizuha0214/saito03601/pull/3/files | ||
| - このPRのように、合流点見つけるロジックと循環の開始点見つけるロジックそれぞれをメソッドで分けてやっていることをメソッド名で表すとよりわかりやすいなと思った |
There was a problem hiding this comment.
コメント集に整え方を書いておいたと思うのですが、フラグを立てたくなったら何か整え方があるくらいに思っておくといいでしょう。
There was a problem hiding this comment.
| - https://discord.com/channels/1084280443945353267/1246383603122966570/1252209488815984710 | ||
| - この説明を見る前は証明的なことをして数式で理解しに行ったが、直感的にも理解できるようになった! | ||
| - https://github.com/mizuha0214/saito03601/pull/3/files | ||
| - このPRのように、合流点見つけるロジックと循環の開始点見つけるロジックそれぞれをメソッドで分けてやっていることをメソッド名で表すとよりわかりやすいなと思った |
There was a problem hiding this comment.
| while True: | ||
| if from_start is from_join_point: | ||
| return from_start | ||
| from_start = from_start.next |
There was a problem hiding this comment.
無限ループはバグの原因になりかねないため、個人的には避けたい気持ちです。今回は確かに無限ループから抜けることは確定しているので安全ですが、実務の場合は、こちらのコードに今後他の人が手を加える可能性もあり、意図せず無限ループが起きてしまうリスクがあるように感じます。以下のようなコードはどうでしょうか。
while from_start is not from_join_point:
from_start = from_start.next
from_join_point = from_join_point.next
return from_startThere was a problem hiding this comment.
ご指摘ありがどうございます!
また、例までありがとうございます。参考にさせていただきます。
Discordの中もあさってみたところ、いくつか過去にも同様な議論がありました。
- 絶対ダメというものではない
- whileの条件式にループの条件をまとめておけば、ループの「主役」や終了条件がわかりやすい(→無限ループも起きにくくなる)
と自分は理解しました〜
There was a problem hiding this comment.
リンクありがとうございます!オープンソースでも無限ループけっこう使用されているのですね。バグの温床のイメージがあったため結構驚きでした。チームや状況に応じて使い分けができると良さそうですね。
| fast = head | ||
| slow = head | ||
|
|
||
| joinPoint = None |
There was a problem hiding this comment.
ローカル変数は、snake_case で命名することをお勧めします。
参考として、関連するスタイルガイドを共有いたします。
https://peps.python.org/pep-0008/#function-and-variable-names
Function names should be lowercase, with words separated by underscores as necessary to improve readability.
Variable names follow the same convention as function names.
https://google.github.io/styleguide/pyguide.html#316-naming
local_var_name
なお、これらのスタイルガイドは唯一の正解というわけではなく、複数あるガイドラインの一つに過ぎません。
所属するチームによって好まれる書き方が異なることもありますので、ご自身の中で基準を持ちつつ、最終的にはチームの一般的な書き方に寄せることをお勧めします。
This: https://leetcode.com/problems/linked-list-cycle-ii/description/
Next: https://leetcode.com/problems/remove-duplicates-from-sorted-list/description/