You can just write it as
sum(x for x in xrange(1,101) if x % 3 == 0 and x % 5 == 0)
and skip the inner set of parenthesis; the parenthesis on a generator expression are not needed if it is the only argument to a function.
Re:Collection Of Puzzles For Programmers
by darkestkhan on Sunday August 19, 2012 @03:34AM
(#4403496)
Can't you all think for a bit? All of These solutions are
O (n) in both time and space... there is solution that will take O (1) time and space - and I think that you learned it in math class at (latest) high school (hint: arithmetic progression)
Seriously? The discussion is about language features, not optimal algorithms.
One could imagine the question was actually "sum BusyBeaver(n) for n divisible by 3 and 5 between 1 and 100", i.e. no closed form. In Python:
sum(BusyBeaver(x) for x in xrange(1,101) if x % 3 == 0 and x % 5 == 0)
(And yes, if one was being really pedantic, one could replace the condition with x % 15 == 0.)
Re:Collection Of Puzzles For Programmers
by darkestkhan on Sunday August 19, 2012 @03:57AM
(#4403522)
The thing is that people start using those libraries w/o thinking before - and theirs' solutions end up doing much more work than is needed
This could be said of most anything high level.
Re:Collection Of Puzzles For Programmers
by the_cat_kittles on Saturday August 18, 2012 @04:12PM
(#4402168)
true, but xrange(1,101) is so tiny, who cares!
sum((x for x in xrange(1, 101) if x % 3 == 0 and x % 5 == 0))
Notice the parenthesis instead of square brackets. Your version actually creates a list in memory. A generator generates the items one by one and doesn't need to store them all at the same time.