Conversation
| if symbol != correct_close: | ||
| return False | ||
|
|
||
| remaining = unclosed_opens.pop() |
There was a problem hiding this comment.
私はこれ return remaining == [sentinel] にするかもしれません。
There was a problem hiding this comment.
remaining = unclosed_opens
return remaining == [sentinel]
とすれば条件分岐する必要なくなりますね。気づいてなかったです。
| https://github.com/SanakoMeine/leetcode/pull/7#discussion_r1903350766 | ||
| - スタックの底に番兵を置くというテクニック。自分の選択肢に番兵が入っていないのは番兵を使ったことがないことが最大の原因なので、step2で使ってみる。 | ||
|
|
||
| https://discord.com/channels/1084280443945353267/1225849404037009609/1231648833914802267 |
There was a problem hiding this comment.
これは一般によく考えられることだと思います。
たとえばブラウザやアプリでユーザが入力するケースでは変な入力は弾きたいです。
逆に、この関数が決まった箇所で使われて常にカッコしか入ってこないなら想定外への対応はいらないかも知れないです。
例えばですが、この問題を実用的に考えるなら、コードのformatterとかですかね?その場合は括弧以外は無視でも良いかも???
There was a problem hiding this comment.
確かにユーザーの入力を処理するときは止まってほしい場面がありますね。開発経験に基づいたコメントは大変ありがたいです。
| if symbol != correct_close: | ||
| return False | ||
|
|
||
| remaining = unclosed_opens.pop() |
There was a problem hiding this comment.
return len(unclosed_opens) == 1;とするのが読みやすいように感じました。
There was a problem hiding this comment.
文字列の走査は終わってるのでスタックの中身を触りに行く必要なかったですね。条件の書き方については趣味に応じて何通りかあるのだと理解しました。
| ```python | ||
| class Solution: | ||
| def isValid(self, s: str) -> bool: | ||
| open_to_close = { |
There was a problem hiding this comment.
やっぱりclose_to_openよりopen_to_closeの方が読みやすいですね!
| } | ||
| open_brackets = set(open_to_close.keys()) | ||
| close_brackets = set(open_to_close.values()) | ||
| valid_brackets = open_brackets.union(close_brackets) |
There was a problem hiding this comment.
二項演算子|のオーバーロードを用いて、
valid_brackets = open_brackets | close_bracketsと書くこともできますね。
| if symbol not in valid_brackets: | ||
| continue |
| continue | ||
|
|
||
| if symbol in close_to_open_dict: | ||
| if len(open_stack) == 0: |
There was a problem hiding this comment.
Implicit false を利用し、
if not open_stack:と書くことをおすすめします。
参考までにスタイルガイドへのリンクを貼ります。
https://google.github.io/styleguide/pyguide.html#2144-decision
For sequences (strings, lists, tuples), use the fact that empty sequences are false, so if seq: and if not seq: are preferable to if len(seq): and if not len(seq): respectively.
上記のスタイルガイドは唯一絶対のルールではなく、複数あるスタイルガイドの一つに過ぎないということを念頭に置くことをお勧めします。また、所属するチームにより何が良いとされているかは変わります。自分の中で良い書き方の基準を持ちつつ、チームの平均的な書き方で書くことをお勧めいたします。
| if len(open_stack) == 0: | ||
| return False | ||
| checking = open_stack.pop() | ||
| correct_open = close_to_open_dict[symbol] |
There was a problem hiding this comment.
自分なら expected という単語を使うと思います。
単体テストでは、 actual、expected という単語が使われる場合があります。
| continue | ||
| i += 1 | ||
|
|
||
| if len(open_stack) != 0: |
今回の問題: 20. Valid Parentheses
次回の問題: 206. Reverse Linked List