Skip to content
Advertisement

Variable is not divisible by an unspecific set of Numbers

I just started to code and try to build my first function in Python/NumPy. My first goal was to get a list for all multiplies of 31 which are not divisible by numbers 1>31 and I figured it out

Here is the code:

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)

The next step is to make the function more flexible, but easy ideas like this just don’t work, obviously:

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

Advertisement

Answer

The answer will be something like

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)

where [x for x in A[0] if ....] is a list comprehension meaning we take every element in array A[0] and add it to the new array C if can_multiply func returns True

Advertisement