+ 2
Def a function and pass 2 lists.. Print true if both the list have at least 1 common element?
https://code.sololearn.com/csqTqaa5ki5d/?ref=app I did in this way.. It showing false for no common elements.. But it is repeating true for many times for common elements... Can any one help?
6 Réponses
+ 4
Try:
def f(a, b):
if type(a) == list and type(b) == list:
for e in a:
if e in b : return True
return false
+ 3
A simple check would be
return bool(set(list1) & set(list2))
It also will be faster on average for large lists
+ 2
Ratnapal Shende your code would fail if the first element in list1 is not in list 2
+ 2
You should try to use what is included, in this case function any()
With that it can be done in one line and much easier to read and understand
def common(l1, l2):
return any(e1 in l2 for e1 in l1)
print(common([1,2,3,4],[5,6,7,8]))
print(common([1,2,3,4],[4,5,6,7]))
+ 1
Angelo Landi Thank you for finding bug 😉
I solved it...
0
Mohammad Shireen your code is working fine their no repeated True..
better way to do this :
def any_common(list1,list2):
value=None
for i in list1:
if i in list2:
value=True
break
else:
value=False
return value
print(any_common([1,2,3,4,5],[6,7,8,4,5]))
output : True #since 4 and 5 is common
https://code.sololearn.com/c2IVrRD8BLZc/?ref=app