Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

The function is returning empty List

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)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading