suppose that x is a numpy array whose elements are integers. using advanced indexing, write a single line expression that gives elements of x between 5 and 100 divisible by 7 in python

main.py
x[(x > 5) & (x < 100) & (x % 7 == 0)]
38 chars
2 lines

Explanation:

  • (x > 5) creates a boolean mask of values greater than 5
  • (x < 100) creates a boolean mask of values smaller than 100
  • (x % 7 ==0) creates a boolean mask of values divisible by 7
  • & operator combines boolean masks in element-wise manner, logical AND operator
  • Using boolean masks we can index our original array and get the desired values

related categories

gistlibby LogSnag