I am trying to make a code (in python) where I can input a range and it will find the sum off all the numbers besides the ones that are divisible by x (which i also choose).
For example:
if the range is 0<N<10
and x = 3
then I want the code to sum the numbers 1 + 2 + 4 + 5 + 7 + 8 and output 27.
or if the range is 0<N<5
and x = 2
I want the code to sum the numbers 1 + 3 and output 4
But, the problem is I have no idea how to do it. Can anyone help me?
对于您的第二个示例:( 0<N<5
, x=2
):
sum(i for i in range(1, 5) if i%2)
You could do something like this:
>>> div = 3
>>> n = 10
>>> num_div = filter(lambda x: x%div, range(n))
>>> sum(num_div)
27
or as a function
def func(n,div):
return sum(filter(lambda x: x%div, range(n))
The other answers implicitly assume the range will always start from 0. If you want to be able to set both the start and end points of your range, you could use:
def sumrange(start, stop, n):
return sum(i for i in range(start, stop) if i%n)
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.