kwispychickyjoy
kwispychickyjoy

Reputation: 45

How to make a function that returns all integers that are multiples of either parameters n1 or n2 within the list n

The 3 parameters: list of integers (n), integer number (n1), and another integer number (n2), not including 0

I have:

def hw(n, n1, n2):
    multiples = []
    for i in n:
        if i % n1 == 0 and i % n2 == 0:
            return multiples

which is wrong and not even returning anything. I'm not sure where I went wrong, though? the test script:

sol= hw(np.arange(20), 3, 4)
assert sol==[3, 4, 6, 8, 9, 12, 15, 16, 18]

Upvotes: 0

Views: 296

Answers (2)

Krishna Chaurasia
Krishna Chaurasia

Reputation: 9580

With return you just return from the function in the very first iteration, you need to append to the list and return the list outside of the loop.

def hw(n, n1, n2):
    multiples = []
    for i in n:
        if i % n1 == 0 or i % n2 == 0:
            multiples.append(i)
    return multiples

Also, use or instead of and if you need multiples of 3 or 4.

Upvotes: 1

Irfan wani
Irfan wani

Reputation: 5095

This is how you can do it using list comprehension:

def fun(n, n1, n2):
    multiples = [i for i in n if i % n1 == 0 and i % n2 == 0]
    return multiples

res = fun([18, 23, 21, 42, 3], 3, 7)
print(res)

Upvotes: 0

Related Questions