首页 > 解决方案 > 变量不能被一组不特定的数字整除

问题描述

我刚开始编写代码并尝试在 Python/NumPy 中构建我的第一个函数。我的第一个目标是列出所有不能被数字 1>31 整除的 31 的倍数,我想通了

这是代码:

c = float(input("Range?"))
a = np.arange(1,c)
A = np.array([31*a])
B=(A[(A%2!=0) & (A%3!=0) & (A%5!=0) & (A%7!=0) & (A%11!=0) & (A%13!=0) & (A%17!=0) & (A%19!=0) & (A%23!=0) & (A%29!=0)] )
print(B)

下一步是使函数更灵活,但像这样简单的想法是行不通的,显然:

c = float(input("Range?"))
a = np.arange(1,c)
d = float(input("multiplier of?"))
A = np.array([d*a])
C=(A[(A%d!=0)])

标签: pythonarraysnumpy

解决方案


答案将类似于

def can_multiply(border_num, num) -> bool:
# 2 instead of 1 here because every num is divisible to 1
arr = [x for x in range(2, border_num)]
for number in arr:
    if num % number == 0:
        return False
return True


c = float(input("Range?"))
a = np.arange(1, c)
d = float(input("multiplier of?"))
A = np.array([d * a])
print(A[0])
C = [x for x in A[0] if can_multiply(int(d), x)]
print(C)

列表推导式在哪里[x for x in A[0] if ....]意味着我们将数组 A[0] 中的每个元素添加到新数组 C 中,如果can_multiplyfunc 返回 True


推荐阅读