intersection_with()
Like intersection but accepts a comparator which is invoked to compare the elements of all arrays. The order and references of result values are determined by the first array. The comparator is invoked with two arguments: ``(arr_val, oth_val)``.
Implementation
Args: array: The array to find the intersection of. *args: Lists to check for intersection with `array`. Returns: Intersection of provided lists.
Example
array = ["apple", "banana", "pear"]
others = (["avocado", "pumpkin"], ["peach"])
comparator = lambda a, b: a[0] == b[0]
intersection_with(array, *others, comparator=comparator)
Expected output: ['pear']
Source Code
def intersection_with(array: List[T], *args) -> List[T]:
# last arg may be comparator
comparator = None
arrays: List[List[T]] = []
if args and (callable(args[-1]) or args[-1] is None):
comparator = args[-1]
arrays = list(args[:-1]) # type: ignore
else:
arrays = list(args) # type: ignore
if not arrays:
return array.copy()
cmp = comparator if callable(comparator) else (lambda a, b: a == b)
result: List[T] = []
for x in array:
if any(cmp(x, y) for y in result):
continue
if all(any(cmp(x, y) for y in arr) for arr in arrays):
result.append(x)
return result