Conversation
| ncols = len(grid[0]) | ||
|
|
||
| def calculate_area(row: int, col: int) -> int: | ||
| inner_grid = lambda r, c: 0 <= r < nrows and 0 <= c < ncols |
There was a problem hiding this comment.
このlambda objectはcalculate_areaが呼ばれるたびに作られるので、多少のオーバーヘッドはあるかと思います。
There was a problem hiding this comment.
関数内の関数も、毎回オブジェクトとして作られているので、やはりオーバーヘッドがあるんじゃないでしょうか。
There was a problem hiding this comment.
いずれの書き方でも、calculate_areaの外側でinner_gridを作るようにすればオーバーヘッドは減らせるということですかね (推奨してるわけではなく認識しておけという意味だと理解してます)。
関数内部に書けばスコープが狭まるメリットもあるので、オブジェクトを作るコストとか単体テスト書けないデメリットとかとのトレードオフだと思ってます。
|
|
||
| def calculate_area(row: int, col: int) -> int: | ||
| inner_grid = lambda r, c: 0 <= r < nrows and 0 <= c < ncols | ||
| if not inner_grid(row, col) or grid[row][col] != Solution.UNVISITED: |
There was a problem hiding this comment.
関数の始めでこれらの条件を確認すると、確かにすっきりはしますが、関数呼び出しのオーバーヘッドはありますね。
| ncols = len(grid[0]) | ||
|
|
||
| def calculate_area(start_row: int, start_col: int) -> int: | ||
| inner_grid = lambda r, c: 0 <= r < nrows and 0 <= c < ncols |
There was a problem hiding this comment.
inner_grid は is_inner_grid または is_in_grid とすると座標が grid 内にあるか判定して boolean を返す関数だと認識しやすくなると思いました。
| def _link(self, i: int, j: int): | ||
| if i == j: | ||
| return | ||
| if self.size[i] < self.size[j]: | ||
| self.parent[i] = j | ||
| self.size[j] += self.size[i] | ||
| else: | ||
| self.parent[j] = i | ||
| self.size[i] += self.size[j] |
There was a problem hiding this comment.
これは Introduction to Algorithms という教科書を参考にして書きまして、そこでそう書いてたから、というだけですね...
教科書で関数を分けて書いている理由は分からないですが、根を見つける部分と木をマージする部分で分けた方が多少キレイだから、くらいなんじゃないだろうかと勝手に思っています
https://leetcode.com/problems/max-area-of-island/description/