I have the following code. In this case I have a Big O(n^2). How can I write this code in a better way using another Big O Notation? The code is suppose to return True if one value from the list matches one value from another, else it should return False.
l1 = [1, 2, 3, 4]
l2 = [1, 6, 7, 8]
def common_inputs(list1, list2):
for i in l1:
for j in l2:
if i == j:
return True
else:
return False
print(common_inputs(l1, l2))
I have an example but is written in JavaScript and can't understand that much.
array1 = [1, 2, 3, 4]
array2 = [1, 6, 7, 8]
function commonInputs(arr1, arr2) {
let map = {};
for (let i=0; i < arr1.length; i++) {
if (!map[i]) {
const item = arr1[i];
map[item] = true;
}
}
for (let j=0; j < arr2.length; j++) {
if (map[arr2[j]]) {
return true;
}
}
return false;
}
Any advice will be appreciated. Thanks in advance.
The python idiom to test if two sets intersect would be
intersect = not set(a1).isdisjoint(a2)
In javascript there's no such thing, so you'll have to loop the second list:
function intersect(a1, a2) {
let s1 = new Set(a1)
return a2.some(x => s1.has(x))
}
You can use set for more pythonic way.
l1 = [1, 2, 3, 4]
l2 = [1, 6, 7, 8]
common = set(l1) & set(l2)
len(common) > 0
>> True