+ 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?

26th Nov 2020, 8:42 AM
Mohammad Shireen
Mohammad Shireen - avatar
6 Respostas
+ 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
26th Nov 2020, 8:45 AM
Angelo
Angelo - avatar
+ 3
A simple check would be return bool(set(list1) & set(list2)) It also will be faster on average for large lists
26th Nov 2020, 12:16 PM
Volodymyr Chelnokov
Volodymyr Chelnokov - avatar
+ 2
Ratnapal Shende your code would fail if the first element in list1 is not in list 2
26th Nov 2020, 11:30 AM
Angelo
Angelo - avatar
+ 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]))
26th Nov 2020, 12:08 PM
Benjamin Jürgens
Benjamin Jürgens - avatar
+ 1
Angelo Landi Thank you for finding bug 😉 I solved it...
26th Nov 2020, 11:36 AM
Ratnapal Shende
Ratnapal Shende - avatar
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
26th Nov 2020, 11:06 AM
Ratnapal Shende
Ratnapal Shende - avatar