Timeline for Sum Square Difference, which way is more Pythonic?
Current License: CC BY-SA 4.0
5 events
when toggle format | what | by | license | comment | |
---|---|---|---|---|---|
Aug 16, 2019 at 13:04 | comment | added | maxb |
@AdamBarnes It is entirely possible to learn Python without ever touching numpy , but I'd definitely argue that the example I provided is in no way unreadable. Even to someone who has barely touched Python, I'd argue that (nums**2).sum() is more readable than sum(n**2 for n in nums) . However, I might be biased from having used numpy extensively. I definitely find Nikos Oikou's answer clear, concise and readable, but I wanted to present alternative approaches that might be usable. And in my own opinion, anyone learning Python should also put some focus on numpy .
|
|
Aug 16, 2019 at 12:52 | comment | added | Adam Barnes |
I -1'd this (even though I don't have the reputation to), because I would argue this is not answering the OP's question. He's not asking for the best computational way to do the sum of squares, he's asking for the most readable. numpy is very much unreadable to the initiated. Compare your examples to Nikos Oikou's, from the perspective of someone who knows Python, but has never used numpy .
|
|
Aug 16, 2019 at 7:36 | comment | added | maxb | @NickMatteo Of course you could simplify it even further, I just wanted to present the way I would have done it. I prefer splitting up the logic, since generally you could have more complicated formulas, and combining them adds an extra layer of debugging for a future developer. I just googled the closed expressions for these sums, and wrote them into the code. That way, it will be easy for any future developer to verify that these formulas are correct. | |
Aug 16, 2019 at 6:51 | comment | added | Nick Matteo |
If you're going to do the math, you might as well do the subtraction as well, no? Then sum_square_analytical is just return (3*n**4 + 2*n**3 - 3*n**2 - 2*n)//12 . Or factor it, which seems faster: return n*(n+1)*(n-1)*(3*n+2)//12
|
|
Aug 15, 2019 at 7:51 | history | answered | maxb | CC BY-SA 4.0 |