循环计算可偏差整数的和

2024-04-25 20:27:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在寻找一种方法来计算1到20之间可以被2、3或5除的整数之和

我创建了一个1到20的整数数组。 Y= np.arange(1, 21, 1)

我知道计算和检查应该在循环中完成,如果循环检查Y是否可以除以2、3或5,然后如果该语句为true,则将true语句相加。我该怎么做

我用下面的方法试过了,但是有一个错误

for i in np.arange(1, 21, 1):
    if i%2 ==0:
    print(x=0)
    else 
    print(x=i)

我想上面的代码会给我一个向量x,其中,如果不能除以to,则范围中的I为0,如果可以除以2,则整数I的值为2。 我怎样才能纠正这个错误


3条回答

您可以使用模运算符:

5%5 = 0
5%3=2
4%2 = 0

所以只要x%n不等于0,它就不可整除

如何检查一个数字是否可以被另一个数字分割?简单,只要用%操作符检查a除以b的余数是否为零,检查here

例如:

def is_dividable_by_2(n):
    return bool(n % 2 == 0)


num = 5

if is_dividable_by_2(num):
    print('%s is dividable by two' % num)
else:
    print('%s is not dividable by two' % num)

num = 4
if is_dividable_by_2(num):
    print('%s is dividable by two' % num)
else:
    print('%s is not dividable by two' % num)

输出:

$ python dividable.py 
5 is not dividable by two
4 is dividable by two

利用您已经使用的numpy,您可以执行以下操作:

def get_divisible_by_n(arr, n):
    return arr[arr%n == 0]

x = np.arange(1,21)

get_divisible_by_n(x, 2)
#array([ 2,  4,  6,  8, 10, 12, 14, 16, 18, 20])

get_divisible_by_n(x, 5)
#array([ 5, 10, 15, 20])

一个数除以n的条件是number%n == 0。当您执行arr[arr%n == 0]操作时,您将把条件应用于数组的每个位置

相关问题 更多 >