I need to input three lists and make a Boolean check whether there is a common element to all lists. So far it the main part of the code looks like this:
def in_all_three(listA, listB, listC):
for x in listA:
if x in listB and x in listC:
return True
else:
return False
I don't know why, but it only returns True if the lists are identical. What is wrong with my code?
Algorithm. Step1: input the elements of three lists. Step2: Use intersection method, first convert lists to sets then apply intersection method of two sets and find out common elements then this set intersect with the third set.
Each list is iterated once to create the sets, and then the sets are intersected. The naive way to solve this using a filtered list comprehension as Geotob did will iterate lists b and c for each element of a , so for longer list, this will be a lot less efficient.
You can transform the lists to sets, and then use Set. retainAll method for intersection between the different sets. Once you intersect all sets, you are left with the common elements, and you can transform the resulting set back to a list.
Method 2:Using Set's intersection property Convert the list to set by conversion. Use the intersection function to check if both sets have any elements in common. If they have many elements in common, then print the intersection of both sets.
You can use intersection of sets for this purpose.
def check_common_element(listA, listB, listC):
common_elements = set.intersection(set(listA), set(listB), set(listC))
if common_elements:
return True
else:
return False
# Test case 1: Testing when there is a common value among lists
list_a = [1,2,3]
list_b = [1,5,6]
list_c = [1,8,9]
print(check_common_element(list_a,list_b,list_c))
# output: True
# Test case 2: Testing when there is no common value among lists
list_a = [1,2,3]
list_b = [1,5,6]
list_c = [7,8,9]
print(check_common_element(list_a,list_b,list_c))
# output: False
As @Reti43 suggested, you can do return bool(common_elements)
instead of if-else
as its a better option for the reasons described in the comments below. In that case, the modified function would look like this:
def check_common_element(listA, listB, listC):
common_elements = set.intersection(set(listA), set(listB), set(listC))
return bool(common_elements)
Logically you need to return False only after all items were checked and no match was found. In order to do that you need to RETURN FALSE; after the loop done.
def in_all_three(listA, listB, listC):
for x in listA:
if x in listB and x in listC:
return True
return False
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With