Create Linked List Cycle #9
Conversation
Updated the Linked List Cycle documentation with reflections on the implementation steps, variable naming conventions, and algorithmic approaches.
| ##### 考え | ||
| - OptionalにO(1)とあるが、思いつかなかったので、素直にnextをたどり続ける方針とした。 | ||
| - Optional[T]型の処理を忘れていて手間取った(Optional[T] はT | None のalias) | ||
| - head.nextの型がListNodeでいいのか、また、それをどう確かめればいいのかわからず手間取った |
There was a problem hiding this comment.
型を知りたいときに built-in 関数の type と isinstance があるかとおもいます。
https://discord.com/channels/1084280443945353267/1339428945845555252/1363800603884523683
| - step2→step3でBlank Lineを使うかどうかがブレた | ||
| - https://google.github.io/styleguide/pyguide.html#35-blank-lines | ||
| > Use single blank lines as you judge appropriate within functions or methods. | ||
| - 常識はどこに空行をいれるのだろうか |
There was a problem hiding this comment.
これはまずは入れたいように入れて見たらいいと思います。ただ、認識の仕方が変わって減っていくことが多いようです。
t-ooka
left a comment
There was a problem hiding this comment.
コードがステップを追うごとに洗練されていく過程がメモされていてとてもわかり易かったです!
| while True: | ||
| if head is None: | ||
| return False | ||
| if head in visited: |
There was a problem hiding this comment.
好みかもしれませんが、head よりも node という変数を使ったほうがわかりやすいかも?と思いました。
(head と聞くと ListNodeの先頭nodeを連想するかもしれないため)
node = head
visited_nodes = set()
while node:
if node in visited_nodes:
return True:
~~ 後続の処理 ~~
There was a problem hiding this comment.
ありがとうございます。renameのためだけに変数を追加するのを躊躇ってしまいheadのまま突き通してしまいましたが、読みにくいですよね
There was a problem hiding this comment.
私も同意見です。
例えば、もし将来的に何らかの変更を加えてheadを返すときに今の実装だと位置が変わってしまっているhead(もはやheadではない)を返してしまうことになるので意味が異なる場合は別の変数に入れた方が良いと思います。
| while True: | ||
| if head is None: | ||
| return False | ||
| if head in visited: |
There was a problem hiding this comment.
私も同意見です。
例えば、もし将来的に何らかの変更を加えてheadを返すときに今の実装だと位置が変わってしまっているhead(もはやheadではない)を返してしまうことになるので意味が異なる場合は別の変数に入れた方が良いと思います。
| if flag is True: | ||
| return True | ||
| return False |
There was a problem hiding this comment.
結局flagは使わない方針にしているので意味のあるコメントかどうか微妙ですが、flag自体に真偽値が入っているので以下で良いと思いました。
return flag|
|
||
| class Solution: | ||
| def hasCycle(self, head: Optional[ListNode]) -> bool: | ||
| flag = False |
There was a problem hiding this comment.
flag という変数名ですと、中にどのような値が入っているのか、実際に値が代入されるまで追いかけなければ理解できず、全体として理解しにくくなるように思いました。 cycled という変数名はいかがでしょうか?
| def hasCycle(self, head: Optional[ListNode]) -> bool: | ||
| flag = False | ||
| pos_set = set() | ||
| while True: |
There was a problem hiding this comment.
個人的には無限ループにはせず、終了条件を条件式として指定したいです。理由は、無限ループにならないことを確認するため、無限ループを抜ける条件を明示的に確認しなければならないためです。この場合は最後まで辿ったらループを抜けるため、 while head is not None: とするのはいかがでしょうか・
| if head is None: | ||
| break | ||
| if head in pos_set: | ||
| flag = True |
There was a problem hiding this comment.
early return のため、ここで return True してしまってよいと思います。
This problem:
https://leetcode.com/problems/linked-list-cycle/
Next problem:
https://leetcode.com/problems/linked-list-cycle-ii/