7 ms·
this is what happens when people who "dont need math to program" write code. if you want to sum over even numbers, just do: sum([j*2 for j in range(0, end_ran
by wayn3 9y ago
this is what happens when people who "dont need math to program" write code.
if you want to sum over even numbers, just do:
sum([j*2 for j in range(0, end_range/2)])
and yes, brackets supercede pythons "whitespace is syntax". if you need linebreaks where, ordinarily, linebreaks are not allowed, just write brackets.
- odonnellryan 9y agoThat's silly! Programming is more than that. This is best: sum(range(0, end_range, 2)) ;)
- wayn3 9y agoi dont know if thats better. but both solutions are a lot better than a statement that contains about half a dozen implied negations.
- odonnellryan 9y agoWhy don't you think it is better? Easier to understand. I was mostly joking, but I think it's a little unfair to imply people who are not great at math are bad programmers.
- wayn3 9y agothey are certainly bad computer scientists, since its a subdiscipline of mathematics. can they be great artisans? sure. why do i think its not better? i said im not sure. i think the two options are about equal in readability, up to taste. yours is probably more efficient in terms of cpu cycles.
- odonnellryan 9y agoIs yours even correct, though? I can't prove it...
- wayn3 9y agoyou can prove it by opening a terminal, typing "python", hitting enter, then copying my line and verifying the result. whats your sticking point?
- odonnellryan 9y agosum([j*2 for j in range(0, 11/2)]) ? It's not right. It doesn't give you the value 10, as you'd "expect".
- wayn3 9y ago0 2 2+4 = 6 2+4+6 = 12 if you sum even numbers, starting from 0, "10" is not a possible result. i dont know what youre trying to do there.
- odonnellryan 9y agoI mean the list: [j*2 for j in range(0, 11/2)] Does not give you the item "10" in the list. So it skips 10...
- wayn3 9y agoyea, because 5 is the end of the range. if you do sum(range(0,10,2)), 10 isn't reached either. why are we having this discussion?
- odonnellryan 9y agoYeah, but if you write "end_range" I'd expect that to be the end range. So your implementation should actually be something like: [j2 for j in range(0, (11+1)/2)] Your code is wrong. sum(range(0,11,2)) works as expected, [j*2 for j in range(0, (11)/2)] does not.
- wayn3 9y ago
- elgenie 9y agoWhat the code in the article is doing is: Given an iterable of pairs, sum the first elements of the pairs for which the first element of the pair is odd and the second element is truthy. What the code you're suggesting does is, to be polite, unrelated.
- wayn3 9y agoand no sane person would write it that way. whatever it is that its trying to do. i agree that i misinterpreted the codes intention.