Skip to content

Create 22. Generate Parentheses.md#53

Open
tokuhirat wants to merge 1 commit intomainfrom
22.-Generate-Parentheses
Open

Create 22. Generate Parentheses.md#53
tokuhirat wants to merge 1 commit intomainfrom
22.-Generate-Parentheses

Conversation

@tokuhirat
Copy link
Owner

This Problem
22. Generate Parentheses
Next Ploblem
283. Move Zeroes
言語: Python

return

if num_open == num_close:
generate_helper(parentheses + "(", num_open - 1, num_close)
Copy link

Choose a reason for hiding this comment

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

generate_helper(parentheses + "(", num_open - 1, num_close)

が 2 回登場するのが気になりました。 step3 で重複をなくせているのはとても良いと思います。


results = []

def generate_helper(parentheses: str, num_open: int, num_close: int) -> None:

Choose a reason for hiding this comment

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

num_open / num_close が、parentheses (引数) に含まれる parentheses の数ではなく、残り必要な数なのが気になりました。
残りの数であれば remaining や required を使う、もしくは num_open / close の定義を含まれる数、というふうにして書き直すほうが自然だと感じました。

Copy link
Owner Author

Choose a reason for hiding this comment

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

コメントありがとうございます。remaining などとした方がわかりやすいですね。
個人的には、実行時間が問題ないのであればコードはシンプルにしたいため、重複した情報は渡さない(引数の parentheses に含まれるかっこの数は数えたらわかる)のが好みなので、他の引数としては残りの括弧の数となるのは自然と思っていました。この辺は考え方次第でしょうか。
あとは括弧の残りが 0 になれば終了と書いた方が関数の処理の記述が n に依存しないため自然に思います。

generate_helper([""], n, n)
return results
```
- 手元で実行時間を計測したところ (10000 回の平均)、n = 8 で、文字列に追記する場合が 0.43 ms, list に追加する場合が 0.48 ms で、文字列に追記しても遅いわけではなかった。理由として、短い文字列であること、CPythonの場合は最適化される場合があること、が考えられるところでしょうか。

Choose a reason for hiding this comment

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

実測して検証しているのはよいと思います。
面接だと、「一般には O(N) になる可能性があるが、xx の実装では yy の条件で最適化されることが保証されるのでこうしました。保証されない可能性があれば zz のように書くと思います」くらいがさらっと言えたら十分じゃないでしょうか (どういう条件でこの最適化が起きるかの議論があったように思いますが、ちょっと正確に覚えていません)。

Copy link
Owner Author

Choose a reason for hiding this comment

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

そうですね。どの条件で最適化が起こるかは把握までできていません。

https://discord.com/channels/1084280443945353267/1200089668901937312/1210619083385479258

つまり、気にしているのは、オーダーが正しく動くか、ではなくて、半年後に読んだ別の同僚が不安にならないか、環境の変化に対して頑健か、なのです。

今後は list を使って join する書き方をすると思います。

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.

3 participants