python - How to calculate the sum of numbers divisible by 3 and 5 using lambda's range, map, filter and reduce -
i need calculating sum of numbers divisible 3 or 5 within given range. far i've gotten this;
print filter(reduce(map(lambda x, y: x % 3 == 0 or y % 5 == 0, x + y, range(30))))
which throws error
traceback (most recent call last): file "<pyshell#65>", line 1, in <module> print filter(reduce(map(lambda x, y: x % 3 == 0 or y % 5 == 0, x + y, range(30)))) nameerror: name 'x' not defined
i don't think i'm close finding solution or on right track, if point me in direction great, cheers.
after defining a
, b
b > a
:
reduce(lambda x, y: x + y, filter(lambda x: x % 3 == 0 or x % 5 == 0, range(a, b)))
in case:
reduce(lambda x, y: x + y, filter(lambda x: x % 3 == 0 or x % 5 == 0, range(30)))
or without reduce
, filter
:
sum(x x in range(30) if x % 3 == 0 or x % 5 == 0)
if range of values large (not 30
) use xrange
if on python 2 returns generator instead of list.
if want include map
function can use identity function follows:
reduce(lambda x, y: x + y, filter(lambda x: x % 3 == 0 or x % 5 == 0, map(lambda x: x, range(30))))
Comments
Post a Comment