sum([x for x in xrange(1, 101) if x % 3 == 0 and x % 5 == 0])
edit: actually sum the list. Of course, it's even shorter if you realize you can write it as: sum([x for x in xrange(1, 101) if x % 15 == 0]) sum([x for x in xrange(1, 101) if x % 3 == 0 and x % 5 == 0])
edit: actually sum the list. Of course, it's even shorter if you realize you can write it as: sum([x for x in xrange(1, 101) if x % 15 == 0])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.
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.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.)