简体   繁体   中英

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.

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))))

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 :)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM