I am creating a function which takes an array and a number. The function should return a new array which should consist all the numbers of input array which are perfectly divisible by number. But the function() is returning an empty list. In the Case below it should return – [45,30].
Here is my Code.
def function(arr,number):
array = []
for val in arr:
if number % val == 0:
array.append(val)
return array
arr = [2,34,11,77,45,30]
number = 5
array = function(arr,number)
print(array)
>Solution :
The problem is in if condition. If you want that the value in array should be perfectly divisible by number, then you should use value % number == 0, the same way you divide value // number.
Updated Code
def function(arr,number):
array = []
for val in arr:
if val % number == 0: # Correct Condition For checking perfect divisibility
array.append(val)
return array
arr = [2,34,11,77,45,30]
number = 5
array = function(arr,number)
print(array)
Output
[45,30]