Conversation
| left = self.depth(node.left) if node.left else 0 | ||
| right = self.depth(node.right) if node.right else 0 | ||
|
|
||
| self.diameter = max(self.diameter,left + right) |
There was a problem hiding this comment.
, のあとに 1 つスペースを空けましょう。
https://peps.python.org/pep-0008/#whitespace-in-expressions-and-statements
There was a problem hiding this comment.
ありがとうございます。
,のあとに詰めて書いてしまったコードが多いので、すべて修正させていただきます。
承知しました。
該当箇所のpep8読ませていただきました。
| self.diameter = max(self.diameter,left + right) | ||
| return max(left,right) + 1 | ||
|
|
||
| def diameterOfBinaryTree(self,root): |
There was a problem hiding this comment.
diameterOfBinaryTree() を異なる木に対して複数回呼んだ場合に、結果が意図しないものになってしまう点が気になりました。複数の木に対して読んでも正しい結果となるような実装にするとよいと思います。
https://ja.wikipedia.org/wiki/%E5%8F%82%E7%85%A7%E9%80%8F%E9%81%8E%E6%80%A7
There was a problem hiding this comment.
参照透過性知らなかったです。ありがとうございます。
誤操作・誤作動のもとになりそうなので注意しますが、
修正方法ぱっと思い浮かばないので、
後ほど時間かけて取り組ませていただきます。
(再度、修正版のちほどあげさせていただきます。)
There was a problem hiding this comment.
修正方法は、
- 返り値をペアにするか
- 他の言語だと引数に参照を渡すとかができるのですが、Python だとそれは難しいのでリストを渡してそのリストの0番目をみんなで書き換えるか
あたりです。
There was a problem hiding this comment.
方向性教えていただきありがとうございます。
特に1で返り値をペアで出力できることをそもそも知らなかったです。
こちら後日取り組ませていただきます。
There was a problem hiding this comment.
複数回呼んだ場合に結果が意図しない、のは、絶対に駄目というわけではないのです。
たとえば、HTML の Parser みたいなものだと、複数回呼べなくても自然かなとは思います。抽出した情報を返す仕事を別のクラスにしないというのも選択だからです。
ただ、これくらい単純なものだと、しない選択肢もあるだろうに、何を代償にわざわざそうしたんだろう、という感覚です。
| def __init__(self): | ||
| self.diameter = 0 | ||
|
|
||
| def depth(self,node): |
There was a problem hiding this comment.
関数名は、関数がどのようなことを行うかを端的に表す英単語または英語句とし、動詞で始めることをお勧めいたします。 get_depth() としたいですが、 self.diameter の更新も行っているため、不正確に感じます。 traverse() あたりがよいと思います。
There was a problem hiding this comment.
traverse()、承知いたしました。
ありがとうございます。
| def __init__(self): | ||
| self.diameter = 0 | ||
|
|
||
| def calc_depth_diameter(self,node): |
There was a problem hiding this comment.
原則単語は省略せずにフルスペルで書くことをお勧めいたします。 number of を表す num_ や、 max number of を表す max_ 等、広く用いられているものについては使っても良いと思います。
https://google.github.io/styleguide/pyguide.html#316-naming
また、計算はしているとは言えないため、 calculate で始めるのは違和感があります。
There was a problem hiding this comment.
原則省略せずにフルスペル承知いたしました。
社内のかき捨てのコードに影響されてしまっていると思うので、意識して直します。
ほかの命名だとupdate_depth_diameter(ただ、depthが更新でよいのか気になります)などが思いつきますが、
以前教えていただいたtravarse単体で対応しようと思います。
There was a problem hiding this comment.
別問題別言語ですがこれが参考になるでしょう。
https://discord.com/channels/1084280443945353267/1206101582861697046/1230424716645240892
https://leetcode.com/problems/diameter-of-binary-tree/