简体   繁体   中英

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]

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 .

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM