"Multiples of 3 and 5"
Of the natural numbers less than 10, there are four that are multiples of 3 or 5, and the sum of these is 23.
In the same way, find the sum of the numbers that are multiples of 3 or 5 less than 1000.
You can use list comprehension notation to create a description close to a functional type.
List comprehension
multiplesOf3or5 = [n for n in range(1, 1000) if n % 3 == 0 or n % 5 == 0]
answer = sum(multiplesOf3or5)
print(answer)
If you write it more functionally with the filter function,
Functional type
def isMultipleOf3or5(n):
return n % 3 == 0 or n % 5 == 0
multiplesOf3or5 = filter(isMultipleOf3or5, range(1, 1000))
answer = sum(multiplesOf3or5)
print(answer)
In Python, the function name becomes a function object as it is, so you can just write the function name in the first argument of the filter function. It's much easier and more intuitive than a C # delegate.
You can also replace the function with a lambda expression. Lambda expressions in Python lambda [argument 1], [argument 2]: [expression] I will write it as. (I wrote only two arguments, but of course three or more are OK.)
Lambda expression
multiplesOf3or5 = filter(lambda n: n % 3 == 0 or n % 5 == 0, range(1, 1000))
answer = sum(multiplesOf3or5)
print(answer)
If you use a lambda expression, it will look like a list comprehension. In this case, I feel that the list notation is more intuitive than the lambda expression.
Recommended Posts