Brody
Brody

Reputation: 89

How to calculate the sum of numbers divisible by 3 and 5 using lambda's range, map, filter and reduce

I need help with calculating the sum of numbers divisible by 3 or 5 within a given range. So far I've gotten to this;

print filter(reduce(map(lambda x, y: x % 3 == 0 or y % 5 == 0, x + y, range(30))))

which throws this 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' is not defined

I don't think I'm close to finding the solution or even on the right track, so if anyone could point me in the direction that would great, cheers.

Upvotes: 0

Views: 3367

Answers (3)

crackpotHouseplant
crackpotHouseplant

Reputation: 401

reduce(lambda x, y: x + y, filter(lambda x : x % 3 == 0 or x%5 == 0, range(11)), 0)

Upvotes: 0

se7entyse7en
se7entyse7en

Reputation: 4294

After defining a and b with b > a:

reduce(lambda x, y: x + y, filter(lambda x: x % 3 == 0 or x % 5 == 0, range(a, b)))

in your case:

reduce(lambda x, y: x + y, filter(lambda x: x % 3 == 0 or x % 5 == 0, range(30)))

or without reduce and filter:

sum(x for x in range(30) if x % 3 == 0 or x % 5 == 0)

if the range of values is large (not 30) you could use xrange if on python 2 so that it returns a generator instead of a list.

If you really want to also include the map function you can use it with the identity function as follows:

reduce(lambda x, y: x + y, filter(lambda x: x % 3 == 0 or x % 5 == 0,
                                  map(lambda x: x, range(30))))

Upvotes: 1

shaman-apprentice
shaman-apprentice

Reputation: 190

Try this one :

sum([i for i in range(1,100) if i%3==0 and i%5==0])

Feel free to ask, if you need some explanation :)

Upvotes: 0

Related Questions