简体   繁体   中英

Sum of all numbers within a range without numbers divisible by x in python

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)
def fn(N, x):
    total = 0
    for i in range(N):
        if i%x:
            total += i
    return total

Read up on loops and ranges in python if you are new.

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.

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