Intersection of java.util.Map
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());
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());
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.
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
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
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
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