pythonarraysfunctionsumdouble

Summing up arrays without doubles


I would like to know if I have generated the 3 arrays in the manner below, how can I sum all the numbers up from all 3 arrys without summing up the ones that appear in each array.

(I would like to only som upt 10 once but I cant add array X_1 andX_2 because they both have 10 and 20, I only want to som up those numbers once.)

Maybe this can be done by creating a new array out of the X_1, X_2 and X_3 what leave out doubles?

 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]) 

Solution

  • it is me again! here is my solution using numpy, cuz i had more time this time:

    import numpy as np
    
    arr = np.arange(1,21)
    
    divisible_by = lambda x: arr[np.where(arr % x == 0)]
    n_2 = divisible_by(2)
    n_3 = divisible_by(3)
    n_5 = divisible_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]