Problem :
If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
Finish the solution so that it return
s the sum of all the multiples of 3 or 5 below the number passed in.
Note : If the number is a multiple of both 3 and 5, only count it once.
Code :
def solution(number):
return sum( (i%3==0 or i%5==0) for i in range (number))
solution(10)
The problem asks you to sum the numbers which are multiples of 3 or 5, but here you're summing the result of (i%3==0 or i%5==0)
, which is a boolean (which in Python is equal to the integers 0 and 1).
Meaning you're just counting the number of multiples of 3 and 5, not summing them. This can trivially be checked by just running the function locally in a Python shell: you'll get 5 (because range
starts at 0 inclusive, so while 0 does not matter to the sum it matters to the counting).
A generator comprension is "value returned [for] value [in] producer [if] condition". Your test needs to go at the end, as a condition.
Basically you are summing the boolean values that's why your answer is not correct please try following code
Code:
def solution(number):
return sum( i for i in range (number) if (i%3==0 or i%5==0))
solution(10)
In each iteration of the loop, you are evaluating the condition
(i%3==0 or i%5==0)
which is True exactly five times when number
is 10. Each True
counts as a 1
, hence you get 5 for the sum.
To get the correct answer, you need to rearrange the statement so that you evaluate i
whenever your condition is true. For more details, see list comprehensions .
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.