[英]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<10
且x = 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<5
和x = 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)
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.