总结没有双打的数组
Summing up arrays without doubles
我想知道我是否已经按照下面的方式生成了 3 个数组,如何在不对每个数组中出现的数字求和的情况下对所有 3 个数组的所有数字求和。
(我只想计算 10 一次,但我不能添加数组 X_1 andX_2 因为它们都有 10 和 20,我只想计算一次这些数字。)
也许这可以通过从 X_1、X_2 和 X_3 中创建一个新数组来完成,什么是双打?
def get_divisible_by_n(arr, n):
return arr[arr%n == 0]
x = np.arange(1,21)
X_1=get_divisible_by_n(x, 2)
#we get array([ 2, 4, 6, 8, 10, 12, 14, 16, 18, 20])
X_2=get_divisible_by_n(x, 5)
#we get array([ 5, 10, 15, 20])
X_3=get_divisible_by_n(x, 3)
#we get array([3, 6, 9, 12, 15, 18])
效率不高且未使用 numpy,但这是一种解决方案:
def get_divisible_by_n(arr, n):
return [i for i in arr if i % n == 0]
x = [i for i in range(21)]
X_1 = get_divisible_by_n(x, 2)
X_2 = get_divisible_by_n(x, 5)
X_3 = get_divisible_by_n(x, 3)
X_all = X_1+X_2+X_3
y = set(X_all)
print(sum(y)) # 142
又是我!
这是我使用 numpy 的解决方案,因为这次我有更多时间:
import numpy as np
arr = np.arange(1,21)
divisable_by = lambda x: arr[np.where(arr % x == 0)]
n_2 = divisable_by(2)
n_3 = divisable_by(3)
n_5 = divisable_by(5)
what_u_want = np.unique( np.concatenate((n_2, n_3, n_5)) )
# [ 2, 3, 4, 5, 6, 8, 9, 10, 12, 14, 15, 16, 18, 20]
我想知道我是否已经按照下面的方式生成了 3 个数组,如何在不对每个数组中出现的数字求和的情况下对所有 3 个数组的所有数字求和。
(我只想计算 10 一次,但我不能添加数组 X_1 andX_2 因为它们都有 10 和 20,我只想计算一次这些数字。)
也许这可以通过从 X_1、X_2 和 X_3 中创建一个新数组来完成,什么是双打?
def get_divisible_by_n(arr, n):
return arr[arr%n == 0]
x = np.arange(1,21)
X_1=get_divisible_by_n(x, 2)
#we get array([ 2, 4, 6, 8, 10, 12, 14, 16, 18, 20])
X_2=get_divisible_by_n(x, 5)
#we get array([ 5, 10, 15, 20])
X_3=get_divisible_by_n(x, 3)
#we get array([3, 6, 9, 12, 15, 18])
效率不高且未使用 numpy,但这是一种解决方案:
def get_divisible_by_n(arr, n):
return [i for i in arr if i % n == 0]
x = [i for i in range(21)]
X_1 = get_divisible_by_n(x, 2)
X_2 = get_divisible_by_n(x, 5)
X_3 = get_divisible_by_n(x, 3)
X_all = X_1+X_2+X_3
y = set(X_all)
print(sum(y)) # 142
又是我! 这是我使用 numpy 的解决方案,因为这次我有更多时间:
import numpy as np
arr = np.arange(1,21)
divisable_by = lambda x: arr[np.where(arr % x == 0)]
n_2 = divisable_by(2)
n_3 = divisable_by(3)
n_5 = divisable_by(5)
what_u_want = np.unique( np.concatenate((n_2, n_3, n_5)) )
# [ 2, 3, 4, 5, 6, 8, 9, 10, 12, 14, 15, 16, 18, 20]