python - 变量不能被一组不特定的数字整除
问题描述
我刚开始编写代码并尝试在 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)])
解决方案
答案将类似于
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_multiply
func 返回 True
推荐阅读
- c++ - 如何在 gn 中包含共享库
- reactjs - ';' react js中的预期错误ts(1005),为什么我会收到这个错误?
- python - 如何在 Azure 应用服务上配置 Nginx .conf 文件
- reactjs - onClick 事件未在 React.js 中触发
- javascript - Vue使用道具保持折线图更新
- javascript - 如何修复 HTML onclick 事件中的“未定义函数”?
- python - 为什么我在使用 matplotlib 时得到一个空图?
- android - 编译安卓内核
- aws-lambda - 将消息从 AWS Lambda 服务发布到 GCP Pub/Sub
- javascript - 在选择的onchange中显示来自mysql的数据不起作用