Just curious; do u have a sort of path one can take to get better at code? I feel like a run into random problems and end up learning from the top down, which is like trying to put a camel through the eye of a needle. I’ve done all of the python and cs paths but I find that doing problems is more helpful than just running the modules.
And I should add, none of it is difficult to implement, because the operations are things like…
And if you study what you do with pen and paper, those are the actions that you are using. Your code can do the same thing.
What’s making things difficult is skipping deciding what to do. Yes, it is difficult then.
To append to an empty list, discard the empty list and create a new node, return the node.
To append to a non-empty list, obtain the last node, set next of that node to a new node, return the original list.
Obtaining last node is done by repeatedly looking at next of current. Try it with pen and paper. It might seem too trivial to bother trying it with pen and paper.
Guess what, it is trivial, so do it with pen and paper if you need to study how it’s done.
Doing it in code doesn’t make it difficult (see the operations listed above). Doing it in code without having decided what’s being done is difficult.
val = l1.val + l2.val + c c = val // 10 ret = ListNode(val % 10 ) if (l1.next != None or l2.next != None or c != 0): if l1.next == None: l1.next = ListNode(0) if l2.next == None: l2.next = ListNode(0) ret.next = self.addTwoNumbers(l1.next,l2.next,c) return ret
given this code, I think it would work till the end until another zero is appended to the end of the list. I need to stop that somehow. Rest of code should be good
Not saying it’s wrong (not going to read it) but I will say that I generally avoid having multiple NOT in an expression, normally one NOT is the most I will tolerate, because humans are really bad with multiple negations (yeah you can practice it but …)
if not (l1.next == None and l2.next == None and c == 0): ...
or better yet:
if any([l1.next, l2.next, c])
^ you can’t get that wrong. compare to what you wrote where one would probably need to spend a minute to be confident about it
end of the list means something specific which is easily testable
you should probably be considering the current node, not the next one. might even be wrong, I suspect I can create an input that causes this to do the wrong thing (add extra zeros)
…or that might even be an infinite loop, if it continously adds something for next step to process
yeah I keep screwing up because of the ‘not’ statement
Since there are only three, that could also be written as:
if l1.next or l2.next or c:
(if one is going to mention each of them anyway, then one may as well use
any would be for if one already has some iterable)
but then again,
any reads very nicely.
and corresponds to