Im facing a question in Python where I need the function to return True if all the numbers of List1 can be divisible by ANY number in List2. I tried to use the all function for this like :
for num1 in List1:
if all(num1 % num2 == 0 for num2 in List2)
return True
but the problem with this is that it check if ALL the numbers in list 1 can be divisible by ALL the numbers in list2. Im wondering if there is a way to combine the all and the any functions to do this problem?
CodePudding user response:
You're almost there. List comprehensions can contain an arbitrary number of variables, in which case all combinations of them will be considered. You can simply say
return all(l1_elm % l2_elm == 0 for l1_elm in List1 for l2_elm in List2)
This is equivalent to
for l1_elm in List1:
for l2_elm is List2:
# if this doesn't evaluate to 0
if l1_elm % l2_elm:
return False
return True
By the way, it's idiomatic in python to use snake_case for variables and PascalCase for classes, so your List1
and List2
should ideally be written as list_1
(or just list1
) and list_2
, respecitively.
@ThePyGuy also makes a good point. The modulo operator fails if the second argument is 0
with ZeroDivisionError: integer division or modulo by zero
. If you expect that List2
might contain a 0
value, you should also check for that before attempting to divide, i.e. modify the condition to if l2_elm == 0 or l1_elm % l2_elm
.
CodePudding user response:
You can combine all
and any
in a comprehension:
>>> l1=[8,10,20]
>>> l2=[2,3,0]
>>> any(all(n1%n2==0 for n1 in l1) for n2 in l2)
True
CodePudding user response:
I think @ThePyGuy is right but here was my attempt before I saw his post:
List1 = [1,2,3,4,5,6]
List2 = [7,8,9,10,11,12]
def testlist():
for num2 in List2:
if all(List1) % num2 == 0:
return True
else:
return False
evaluate = testlist()
print(evaluate)