PostgreSQL check if array contains any element from left-hand array
Sure, use the && array-overlaps operator: SELECT ARRAY[1,2] && ARRAY[1,3,4,7]; See array functions and operators.
Sure, use the && array-overlaps operator: SELECT ARRAY[1,2] && ARRAY[1,3,4,7]; See array functions and operators.
That depends on your set implementation. If you have a hash set (O(1) lookup), then the approach indicated by all the other posters is correct. Iterate across all the elements in the first set. If it’s in the second set, then add it to the result. This runs in O(n) time. If you have a … Read more
How about: Map map1 = …; Map map2 = …; Map result = new …(map1); result.keySet().retainAll(map2.keySet()); or: Map map1 = …; Map map2 = …; Set result = new …(map1.keySet()); result.retainAll(map2.keySet());
The simplest one-line solution is this: set1.addAll(set2); // Union set1.retainAll(set2); // Intersection The above solution is destructive, meaning that contents of the original set1 my change. If you don’t want to touch your existing sets, create a new set: var result = new HashSet<>(set1); // In Java 10 and above Set<Integer> result = new HashSet<>(set1); … Read more
You could define three functions inBoth, inFirstOnly, and inSecondOnly which all take two lists as arguments, and return a list as can be understood from the function name. The main logic could be put in a common function operation that all three rely on. Here are a few implementations for that operation to choose from, … Read more
My attempt: def merge(lsts): sets = [set(lst) for lst in lsts if lst] merged = True while merged: merged = False results = [] while sets: common, rest = sets[0], sets[1:] sets = [] for x in rest: if x.isdisjoint(common): sets.append(x) else: merged = True common |= x results.append(common) sets = results return sets lst … Read more
You could put all elements of the first list into a hash set. Then, iterate the second one and, for each of its elements, check the hash to see if it exists in the first list. If so, output it as an element of the intersection.
From Python version 2.6 on you can use multiple arguments to set.intersection(), like u = set.intersection(s1, s2, s3) If the sets are in a list, this translates to: u = set.intersection(*setlist) where *a_list is list expansion Note that set.intersection is not a static method, but this uses the functional notation to apply intersection of the … Read more