Conversation
| node.next = ListNode(value) | ||
| node = node.next | ||
| next_carry = total // 10 | ||
| return add_two_numbers(list1, list2, next_carry, node) |
There was a problem hiding this comment.
こちらの場合はreturnした値は必要無いはずなのでreturn無しで終わらせるのが自然かと思いました
| return add_two_numbers(list1, list2, next_carry, node) | |
| add_two_numbers(list1, list2, next_carry, node) |
There was a problem hiding this comment.
ご指摘のとおり、行きがけの再帰だと文字通り行きがけで各ステップの処理が完結するので、returnは再帰の底でNoneを返せば十分でした。
副作用でリストを作ってるので関数の戻り値はたしかに必要ないですね。
| carry = total // base_number | ||
| value = total % base_number |
There was a problem hiding this comment.
参考までにこちらはdivmodでまとめることも可能ですね
https://docs.python.org/ja/3/library/functions.html#divmod
| - ループ条件は省略せずに`if l1 is not None`まで書き、ループ内の条件は`if l1`などと省略した。 | ||
| - ループの部分で条件が明示されてるので条件分岐のところで省略しても可読性は下がらないのではないか、という予想。 |
There was a problem hiding this comment.
個人的には逆に表記ゆれのように見えてしまうかもしれません。
また厳密にはif l1 is not None:とif l1:では違う判定をしているので、判定が異なることに何か意味があるのかと思われるかなと思いました。
There was a problem hiding this comment.
確かにif l1 is not None: はl1とNoneの非同一性のチェックですが、if l1: はl1がTrueがどうかのチェックですね。意識していませんでした。
https://docs.python.org/ja/3.13/library/stdtypes.html#truth-value-testing
| carry = total // base_number | ||
| value = total % base_number | ||
| node.next = ListNode(value) | ||
| node = node.next |
There was a problem hiding this comment.
全体的に詰まっている感じがあるのでこの後に一行空行を入れてもいいかもしれません。
好みだと思います。
There was a problem hiding this comment.
空行入れたくなる感覚をまだつかみ切れていないので助かります。
今回の問題: 2. Add Two Numbers
次回の問題: 20. Valid Parentheses