Conversation
| def maxAreaOfIsland(self, grid: List[List[int]]) -> int: | ||
| num_rows, num_columns = len(grid[0]), len(grid) | ||
| unvisited = set() | ||
| max_area_island = 0 |
There was a problem hiding this comment.
何のareaかは、読む側・ユーザーとも認識がずれないと思うので、_island は冗長に感じました。
| max_area_island = 0 | |
| max_area = 0 |
| unvisited = set() | ||
| max_area_island = 0 | ||
|
|
||
| same_island_directions = ((-1, 0), (1, 0), (0, -1), (0, 1)) |
There was a problem hiding this comment.
same_ の意味が取れませんでした。 陸続き のislandのcellを探索するときの、方向のバリエーション、くらいの意味でしょうか。
directions でも意味は通じそうに思いました。長くするなら directons_to_traverse_land とかでしょうか。
| LAND = 1 | ||
| WATER = 0 |
There was a problem hiding this comment.
些末ですが、ここに書くと他のモジュールからもimportできてしまいます。多くのケースでは maxAreaOfIsland 内での宣言の方がスコープ的に必要十分であるように思います。
| while traversed_points: | ||
| row, col = traversed_points.pop() | ||
|
|
||
| def _try_visit(row, col, area_island): |
There was a problem hiding this comment.
inner function の名前は、snake_case で命名することをお勧めします。
_ で始まる識別子は、他のクラスやモジュールから使用しないことを意思表示する際に使用することが多いと思います。
参考までに、関連するスタイルガイドを共有いたします。
https://peps.python.org/pep-0008/#descriptive-naming-styles
_single_leading_underscore: weak “internal use” indicator. E.g. from M import * does not import objects whose names start with an underscore.
https://peps.python.org/pep-0008/#function-and-variable-names
Function names should be lowercase, with words separated by underscores as necessary to improve readability.
https://google.github.io/styleguide/pyguide.html#316-naming
function_name
なお、LeetCode の解答では関数名が lowerCamel(mixedCase)で書かれていることがありますが、一般的な Python コードではあまり見かけません。PEP 8 でも以下のように、特殊な場合を除いて推奨されていません。
https://peps.python.org/pep-0008/#function-and-variable-names
mixedCase is allowed only in contexts where that’s already the prevailing style (e.g. threading.py), to retain backwards compatibility.
なお、これらのスタイルガイドが唯一の正解というわけではなく、数あるガイドラインの一つに過ぎません。
チームごとに好まれる命名規則が異なる場合もありますので、ご自身の中に基準を持ちつつ、最終的にはチームの一般的な書き方に合わせることをお勧めします。
| while traversed_points: | ||
| row, col = traversed_points.pop() | ||
|
|
||
| def _try_visit(row, col, area_island): |
There was a problem hiding this comment.
try***() という関数名は、何かを試しにやってみて、失敗したら False を返すというニュアンスを感じます。単に visit() で十分だと思います。
| while traversed_points: | ||
| row, col = traversed_points.pop() | ||
|
|
||
| def _try_visit(row, col, area_island): |
There was a problem hiding this comment.
自分ならループの中にインラインで書くと思います。理由は、ループの中にこの関数の中身を書いても、読みづらくはなく、 inner function にくくりだす必要性を感じないためです。趣味の範囲だと思います。
| def _try_visit(row, col, area_island): | ||
| if (row, col) not in unvisited: | ||
| return | ||
| if row < 0 or num_rows <= row: |
There was a problem hiding this comment.
if not (0 <= row < num_rows):と書くと、登場する値が数直線上に一直線上になり、理解しやすくなると思います。
if not 0 <= row < num_rows:と書くこともできますが、 not がどこまで係っているか分かりづらいかもしれません。
問題
695. Max Area of Island
次に解く問題
323. Number of Connected Components in an Undirected Graph