Reputation: 45
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
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
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