Add 1. Two Sum.md#2
Conversation
| raise NoValueError("There is no such pair that sums to the target") | ||
| ``` | ||
|
|
||
| そういえばpythonのエラーってどんな感じだったっけと思って見直した |
| https://github.com/ksaito0629/leetcode_arai60/pull/10/changes/bb1ae591a98e7810711de49f212bb97f5fc34ce9#r2811748134 | ||
| 辞書の名前としてkey_to_valueはなるほど感がある。 | ||
| というか2周ループを回す必要は別になくて探しながら追加したらいいだけだな。 | ||
| あとleetcodeで書くときにエラーをraiseする習慣はなかったけど他の人のコードを見ていると書いているっぽい。仕事なら書いてるけども。 |
There was a problem hiding this comment.
たとえば、面接の場面では、とりあえず動くものが書けることは大事です。その後に、なにか仕事の場だったらどうこのコードについて感じますか、などと聞かれたときに raise するなあなどのコメントが自然に出てくるならばあまり問題は感じないです。
There was a problem hiding this comment.
なるほど、ただ習慣として意識せずに書ける方がミスが減るので気をつけます。
| num_to_index = {} | ||
| for index, num in enumerate(nums): | ||
| if target - num in num_to_index: | ||
| return [index, num_to_index[target-num]] |
There was a problem hiding this comment.
二項演算子の両側にスペースが開いているものとあいてないものが混在しており、読み手にとってノイズになりそうだと思いました。
個人的には、二項演算子の左右にスペースを入れることが多いです。
参考までに、関連するスタイルガイドを共有いたします。
https://peps.python.org/pep-0008/#other-recommendations
Always surround these binary operators with a single space on either side: assignment (=), augmented assignment (+=, -= etc.), comparisons (==, <, >, !=, <=, >=, in, not in, is, is not), Booleans (and, or, not).
https://google.github.io/styleguide/pyguide.html#36-whitespace
Surround binary operators with a single space on either side for assignment (=), comparisons (==, <, >, !=, <>, <=, >=, in, not in, is, is not), and Booleans (and, or, not). Use your better judgment for the insertion of spaces around arithmetic operators (+, -, *, /, //, %, **, @).
なお、これらのスタイルガイドは唯一絶対のルールではなく、数あるガイドラインの一つに過ぎません。チームによって重視する書き方が異なる場合もあります。
そのため、ご自身の中に基準を持ちつつも、最終的にはチーム内で一般的とされる書き方に寄せていくことをお勧めいたします。
| if target - num in num_to_index: | ||
| return [index, num_to_index[target-num]] | ||
| num_to_index[num] = index | ||
| raise NoValueError("There is no such pair that sums to the target") |
There was a problem hiding this comment.
NoValueErrorは組み込み例外ではないので、ここまで到達した場合、NameErrorが出るかと思います。
https://docs.python.org/3/library/exceptions.html#exception-hierarchy
| def twoSum(self, nums: List[int], target: int) -> List[int]: | ||
| num_to_index = {} | ||
| for index, num in enumerate(nums): | ||
| if target - num in num_to_index: |
There was a problem hiding this comment.
target - num は複数回登場する意味のある値なので complementなどと名前をつけるのもアリかもしれません。
There was a problem hiding this comment.
高々2回ぐらいだからいいやと思ってましたが2回目が出てきた瞬間に置き換えてしまった方が良さそうですね。
This Problem
https://leetcode.com/problems/two-sum/description/
Next Problem
https://leetcode.com/problems/kth-largest-element-in-a-stream/description/