简体   繁体   English

在python中没有被x整除的数字的范围内所有数字的总和

[英]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).我正在尝试编写一个代码(在 python 中),我可以在其中输入一个范围,它会找到除可被 x 整除的数字之外的所有数字的总和(我也选择)。

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.如果范围是0<N<10x = 3那么我希望代码对数字 1 + 2 + 4 + 5 + 7 + 8 求和并输出 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或者如果范围是0<N<5x = 2我希望代码对数字 1 + 3 求和并输出 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.如果您是新手,请阅读 Python 中的循环范围

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:其他答案隐含地假设范围始终从 0 开始。如果您希望能够设置范围的起点和终点,您可以使用:

def sumrange(start, stop, n):
    return sum(i for i in range(start, stop) if i%n)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用python中的while循环求和所有可被y整除的0到x的数字 - Sum all numbers 0 to x that are divisible by y using while loop in python Python:打印x和y可除范围内的所有数字 - Python: Print all numbers in range divisible by x and y 从 0 到给定数字范围内的所有数字的总和,这些数字可以被 7 整除 - Sum of all numbers in range from 0 to a given number that are divisible with 7 打印范围内可以被 4 或 5 整除的所有数字,但不能同时被 4 或 5 整除 - print all the numbers in a range that are divisible by 4 or 5, but not both 在列表中查找 X 个数字的总和(Python) - finding a sum of X numbers within a list (Python) 我正在尝试编写一个代码来打印 'a' 范围内不能被 y 整除的数字 - Am trying to write a code that will print the numbers within the range of 'a' that are not divisible by y 返回一个范围内所有奇数之和的递归函数 - Recursive function that returns sum of all odd numbers within a range 获取范围内所有数字的总和 - Get sum of all numbers in range 无法得到 n 以下所有数字的总和可被 3 或 5 整除 - Can't get the sum of all numbers below n divisible by either 3 or 5 高效的算法,可找到可被数字整除的数的计数,而该数没有范围内的余数 - Efficient algorithm to find the count of numbers that are divisible by a number without a remainder in a range
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM