Conversation
| while l1 or l2: | ||
| l1_val = l1.val if l1 else 0 | ||
| l2_val = l2.val if l2 else 0 | ||
| total = carry + l1_val + l2_val |
There was a problem hiding this comment.
total = l1_val + l2_val + carryの順の方が自然だと思いました。
また、l1_val, l2_valよりv1, v2でもいいのかなと思いました。
|
|
||
| 思考ログ | ||
| - Step1の改修できる箇所をさがす | ||
| - x、y⇒l1_val、l2_valとか? 関数化も視野かなと思ったが、これくらいならむしろしなくていいんじゃないかという気もする |
There was a problem hiding this comment.
Pythonだと3項演算子でパッと書けるので僕も関数化しなくていいと思いました
Arai60/LinkedList/answer.md
Outdated
| # Step3 | ||
| かかった時間:5min | ||
|
|
||
| step2を何回か書き直してSubした |
| carry = 0 | ||
|
|
||
| while l1 or l2: | ||
| l1_val = l1.val if l1 else 0 |
There was a problem hiding this comment.
0を足すことはつまり何もしないことと同じなので、下のif文とまとめて分岐の数を減らすことも出来そうです。
There was a problem hiding this comment.
ちょっと考えてみたのですが、あまりしっくりくるものが作れませんでした。ただ考える過程で最後のifがなくてもよいことに気づけました。ありがとうございます。
There was a problem hiding this comment.
ここの inline if と下の同じ条件のところをまとめて、以下のようなものを考えてました。元のコードで十分読みやすいので、単なる選択肢の一つとして捉えていただけますと。
class Solution:
def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
dummy_head = ListNode()
current = dummy_head
carry = 0
while l1 or l2 or carry:
total = carry
if l1:
total += l1.val
l1 = l1.next
if l2:
total += l2.val
l2 = l2.next
carry = total // 10
current.next = ListNode(total % 10)
current = current.next
return dummy_head.next| ```python | ||
| class Solution: | ||
| def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]: | ||
| dummyHead = ListNode(0) |
There was a problem hiding this comment.
snake caseを使うことをおすすめします。
https://peps.python.org/pep-0008/#function-and-variable-names
| 思考ログ | ||
| - Step1の改修できる箇所をさがす | ||
| - x、y⇒l1_val、l2_valとか? 関数化も視野かなと思ったが、これくらいならむしろしなくていいんじゃないかという気もする | ||
| - sumは予約語になってるケースもあるので名前変える |
There was a problem hiding this comment.
予約語 (reserved words) という言葉は、言語によって意味が変わることもあるのですが、Python においては、予約語は keywords のことで、def, elif, pass みたいにパースの仕方から変わるものです。
https://docs.python.org/3/reference/lexical_analysis.html#keywords
sum は組み込み関数 (Built-in Functions) ですね。
https://docs.python.org/3/library/functions.html#sum
There was a problem hiding this comment.
雰囲気一緒だなと思って誤って覚えてました。ご指摘ありがとうございます。
|
step4まで見ましたが、既に指摘されている部分を除き全体的に良いと思いました。 |
問題:https://leetcode.com/problems/add-two-numbers/
考えたこと兼解法:https://github.com/ask-1407/leetcode/blob/add_two_numbers/Arai60/LinkedList/answer.md
次に解く予定:https://leetcode.com/problems/valid-parentheses/