Skip to content

Conversation

@fhiyo
Copy link
Owner

@fhiyo fhiyo commented Jun 13, 2024

ncols = len(grid[0])

def calculate_area(row: int, col: int) -> int:
inner_grid = lambda r, c: 0 <= r < nrows and 0 <= c < ncols

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

このlambda objectはcalculate_areaが呼ばれるたびに作られるので、多少のオーバーヘッドはあるかと思います。

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

関数内の関数も、毎回オブジェクトとして作られているので、やはりオーバーヘッドがあるんじゃないでしょうか。

Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

いずれの書き方でも、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:

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

関数の始めでこれらの条件を確認すると、確かにすっきりはしますが、関数呼び出しのオーバーヘッドはありますね。

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
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

inner_gridis_inner_grid または is_in_grid とすると座標が grid 内にあるか判定して boolean を返す関数だと認識しやすくなると思いました。

Comment on lines +78 to +86
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]

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

union_linkで関数を分けた理由ってありますか?

Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

これは Introduction to Algorithms という教科書を参考にして書きまして、そこでそう書いてたから、というだけですね...
教科書で関数を分けて書いている理由は分からないですが、根を見つける部分と木をマージする部分で分けた方が多少キレイだから、くらいなんじゃないだろうかと勝手に思っています

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants