Array Functions
Transformations
Array restructuring operations like flatten, zip, and partition.
Operations that transform arrays into different structures.
flatten()
Flattens nested arrays to a specified depth
Implementation
Uses a recursive approach to flatten nested structures
Example
flattened = UniCoreFW.flatten([1, [2, 3], [4, [5]]])
Expected output: [1, 2, 3, 4, 5]
Source Code
def flatten(*args, depth=None):
# Determine if the last positional argument is 'n' (depth) when depth is not specified
if depth is None and len(args) >= 1 and isinstance(args[-1], int):
n = args[-1]
args = args[:-1]
else:
n = depth
# Validate 'n' (depth)
if n is not None:
if isinstance(n, bool):
n = int(n)
elif not isinstance(n, int):
raise ValueError("Depth must be a non-negative integer or None.")
if n < 0:
raise ValueError("Depth must be a non-negative integer or None.")
# Determine the array to flatten
if len(args) == 1 and isinstance(args[0], list):
array = args[0]
else:
array = list(args)
# Handle edge cases for None or empty lists
if array is None or not array:
return [] if n is not None else None
# Set maximum depth
max_depth = float("inf") if n is None else n
result = []
def _flatten(current, current_depth):
for item in current:
if isinstance(item, list) and current_depth > 0:
_flatten(item, current_depth - 1)
else:
result.append(item)
_flatten(array, max_depth)
return result
zip()
Combines multiple arrays into an array of tuples
Implementation
Uses Python's zip function with list conversion
Example
zipped = UniCoreFW.zip([1, 2, 3], ["a", "b", "c"])
Expected output: [(1, "a"), (2, "b"), (3, "c")]
Source Code
def zip(*arrays):
return list(zip(*arrays))
unzip()
Reverses the zip operation by separating tuples into arrays
Implementation
Uses zip(*array) to transpose the data structure
Example
unzipped = UniCoreFW.unzip([(1, "a"), (2, "b"), (3, "c")])
Expected output: [[1, 2, 3], ["a", "b", "c"]]
Source Code
def unzip(array_of_tuples):
return list(map(list, zip(*array_of_tuples)))
partition()
Splits an array into two based on a predicate
Implementation
Creates two lists using list comprehensions for passing and failing elements
Example
partitioned = UniCoreFW.partition([1, 2, 3, 4, 5], lambda x: x % 2 == 0)
Expected output: [[2, 4], [1, 3, 5]]
Source Code
def partition(array, predicate):
truthy = [item for item in array if predicate(item)]
falsy = [item for item in array if not predicate(item)]
return [truthy, falsy]
unzip_()
Implementation
Implementation details are not available.
Example
Expected output: ``
Source Code
def unzip_(array_of_tuples: List[Tuple[Any, ...]]):
return unzip(array_of_tuples, as_lists=False)
range()
Generates a range of numbers as an array
Implementation
Wraps Python's range function with list conversion
Example
range_arr = UniCoreFW.range(1, 6)
Expected output: [1, 2, 3, 4, 5]
Source Code
def range(start, stop=None, step=1):
if stop is None:
start, stop = 0, start
return list(range(start, stop, step))
max_value()
Return the maximum value in the array, based on an optional key function. Returns None if the array is empty.
Implementation
Implementation details are not available.
Example
max_value([1, 2, 3])
Expected output: 3
Source Code
def max_value(
array: List[T], key_func: Optional[Callable[[T], Any]] = None
) -> Optional[T]:
if not array:
return None
if key_func:
return builtins.max(array, key=key_func)
return builtins.max(array) # type: ignore
difference()
Returns values from the first array not present in others
Implementation
Uses set operations to find differences
Example
diff = UniCoreFW.difference([1, 2, 3, 4], [2, 4], [1])
Expected output: [3]
Source Code
def difference(array, *others):
other_elements = set().union(*others)
return [x for x in array if x not in other_elements]
intersection()
Returns elements common to all arrays
Implementation
Uses set intersection operations
Example
intersect = UniCoreFW.intersection([1, 2, 3], [2, 3, 4], [2, 3, 5])
Expected output: [2, 3]
Source Code
def intersection(*arrays):
common_elements = set(arrays[0])
for arr in arrays[1:]:
common_elements.intersection_update(arr)
return list(common_elements)
xor_with()
Creates an array of unique values that is the symmetric difference of the provided arrays relative to the comparator function.
Implementation
The comparator function is called with two arguments: (value, other), where value is a value from an array and other is a value from another array. The comparator should return True if the values are equal and False otherwise.
The order of result values is determined by the order they occur in the input arrays.
Args:
*arrays: The arrays to process.
comparator: A callable comparator function to determine equality of values.
Returns:
A new array with unique values.
Example
xor_with([1, 2, 3], [2, 4], lambda x, y: x == y)
Expected output: [1, 3, 4]
Source Code
def xor_with(*args: Any) -> List[Any]:
if len(args) < 2:
raise ValueError("xor_with requires at least one array and one comparator")
*arrays, comparator = args
if not callable(comparator):
raise TypeError("Last argument must be a callable comparator function")
# Normalize & validate
lists: List[List[Any]] = []
for i, arr in enumerate(arrays):
if not isinstance(arr, (list, tuple)):
raise TypeError(f"Argument {i} must be a list or tuple")
lists.append(list(arr))
# Trivial: only one array
if len(lists) == 1:
return lists[0].copy()
def _xor2(a: List[Any], b: List[Any]) -> List[Any]:
out: List[Any] = []
# keep from a those x for which no y in b satisfies comparator(x,y)
for x in a:
try:
if not any(comparator(x, y) for y in b):
out.append(x)
except Exception as e:
raise TypeError(f"Comparator function failed: {e}")
# keep from b those y for which no x in a satisfies comparator(y,x)
for y in b:
try:
if not any(comparator(y, x) for x in a):
out.append(y)
except Exception as e:
raise TypeError(f"Comparator function failed: {e}")
return out
# Fast path for exactly two arrays
if len(lists) == 2:
return _xor2(lists[0], lists[1])
# N-way via reduce
return ft_reduce(_xor2, lists)
xor_by()
Creates an array of unique values that is the symmetric difference of the provided arrays.
Implementation
Args: *arrays: The arrays to process fn: The iteratee applied per element
Returns:
A new array with unique values
Example
xor_by([1, 2, 3], [2, 3, 4], lambda x: x % 2)
Expected output: [1, 4]
Source Code
def xor_by(*args: Any) -> List[T]:
arrays = list(args)
if arrays and callable(arrays[-1]):
fn = arrays.pop() # type: ignore
else:
raise TypeError("Missing iteratee for xor_by")
def sym(a, b):
kb = {fn(x) for x in b}
ka = {fn(x) for x in a}
return [x for x in a if fn(x) not in kb] + [y for y in b if fn(y) not in ka]
return ft_reduce(sym, arrays) if arrays else []
xor()
Creates an array of unique values that is the symmetric difference of the provided arrays.
Implementation
Args: *arrays: The arrays to process
Returns:
A new array with unique values
Example
xor([1, 2, 3], [2, 3, 4])
Expected output: [1, 4]
Source Code
def xor(*arrays: List[T]) -> List[T]:
if not arrays:
return []
def sym(a, b):
return [x for x in a if x not in b] + [y for y in b if y not in a]
return ft_reduce(sym, arrays)
unshift()
Adds elements to the beginning of an array.
Implementation
Args: array: The array to modify *values: The values to add to the beginning of the array
Returns:
The modified array
Example
unshift([2, 3], 1)
Expected output: [1, 2, 3]
Source Code
def unshift(array: List[T], *values: T) -> List[T]:
for v in reversed(values):
array.insert(0, v)
return array
zip_with()
Merges together the values of each of the arrays with the corresponding values of the other arrays, based on their index.
Implementation
Args: *args: The arrays to merge
Returns:
A list with the merged values
Example
zip_with([1, 2, 3], [4, 5, 6], [7, 8, 9])
Expected output: [(1, 4, 7), (2, 5, 8), (3, 6, 9)]
Source Code
def zip_with(*args) -> List[Any]:
if not args:
return []
func = args[-1] if callable(args[-1]) else None
arrays = list(args[:-1]) if func else list(args)
if func:
return [func(*group) for group in zip(*arrays)]
return list(zip(*arrays))
add()
Helper function to calculate a raised to the power of b. Used in the test cases for unzip_with.
Implementation
Args: a: Base number b: Exponent
Returns:
a raised to the power of b
Example
Expected output: ``
Source Code
def add(a: Union[int, float], b: Union[int, float]) -> Union[int, float]:
return a + b
power()
Helper function to calculate a raised to the power of b. Used in the test cases for unzip_with.
Implementation
Args: a: Base number b: Exponent
Returns:
a raised to the power of b
Example
power(2, 3)
Expected output: 8
Source Code
def power(a: Union[int, float], b: Union[int, float]) -> Union[int, float]:
return a**b
unzip_with()
This method is like unzip except that it accepts an iteratee to specify how regrouped values should be combined. The iteratee is invoked with the elements of each group.
Implementation
Args: arrays: List of arrays to process iteratee: Optional function to combine the grouped values
Returns:
List of regrouped elements, optionally transformed by iteratee
Security & Performance:
- Input validation for safety
- Efficient list comprehension for transposition
- Handles empty arrays gracefully
- Supports variable argument functions via unpacking
Example
unzip_with([[1, 2, 3], [4, 5, 6]], lambda x: sum(x))
Expected output: [5, 7, 9]
Source Code
def unzip_with(
arrays: List[List[Any]], iteratee: Optional[Callable] = None
) -> List[Any]:
# Handle empty input
if not arrays:
return []
# Input validation
if not isinstance(arrays, (list, tuple)):
raise TypeError("First argument must be a list or tuple of arrays")
# Handle empty arrays list
if len(arrays) == 0:
return []
# Validate that all elements are lists/tuples
for i, arr in enumerate(arrays):
if not isinstance(arr, (list, tuple)):
raise TypeError(f"Element at index {i} must be a list or tuple")
# Handle case where arrays contain empty lists
if any(len(arr) == 0 for arr in arrays):
return []
# Validate iteratee if provided
if iteratee is not None and not callable(iteratee):
raise TypeError("Iteratee must be callable")
# Find the minimum length to avoid index errors
min_length = min(len(arr) for arr in arrays)
# If no minimum length, return empty
if min_length == 0:
return []
# Transpose the arrays and optionally apply iteratee
result = []
try:
for i in range(min_length):
# Get the i-th element from each array
group = [arr[i] for arr in arrays]
if iteratee is None:
# Return as tuple if no iteratee provided
result.append(tuple(group))
else:
# Apply iteratee to the group
# Use unpacking to support functions that take multiple arguments
transformed = iteratee(*group)
result.append(transformed)
except (TypeError, IndexError) as e:
raise TypeError(f"Failed to process arrays: {str(e)}")
return result
intersection_by()
Creates an array of unique values that is the intersection of all given arrays, using a provided iteratee to generate the criterion by which uniqueness is computed.
Implementation
Args: array: The array to inspect. *args: The values to intersect. iteratee: The iteratee to transform values.
Returns:
The intersection of values.
Example
intersection_by([1, 2, 3], [2, 3, 4], lambda x: x % 2)
Expected output: [2]
Source Code
def intersection_by(array: List[T], *args) -> List[T]:
# last arg may be iteratee
iteratee = None
arrays: List[List[T]] = []
if args and (callable(args[-1]) or isinstance(args[-1], str) or args[-1] is None):
iteratee = args[-1]
arrays = list(args[:-1]) # type: ignore
else:
arrays = list(args) # type: ignore
if not arrays:
return array.copy()
# key function
if isinstance(iteratee, str):
def fn(x: T) -> Any:
if isinstance(x, dict):
return x.get(iteratee) # type: ignore # noqa: E701
return getattr(x, iteratee, None) # type: ignore
elif callable(iteratee):
fn = iteratee # type: ignore
else:
fn = lambda x: x # type: ignore # noqa: E731
sets = [{fn(v) for v in arr} for arr in arrays]
seen: set = set()
result: List[T] = []
for x in array:
key_val = fn(x)
if key_val in seen:
continue
if all(key_val in s for s in sets):
seen.add(key_val)
result.append(x)
return result
sort()
Sorts an array in-place and returns it.
Implementation
Args: array: The list to sort comparator: Optional comparison function that returns -1, 0, or 1 key: Optional key function to extract comparison value from elements reverse: If True, sort in descending order
Returns:
The sorted array (same reference as input)
Raises:
ValueError: If both comparator and key are provided
TypeError: If array is not a list or inputs are invalid types
Security & Stability Notes:
- Validates input types to prevent injection attacks
- Uses built-in sorted() for performance and stability
- Handles edge cases gracefully
Example
sort([3, 1, 2])
Expected output: [1, 2, 3]
Source Code
def sort(
array: List[Any],
comparator: Optional[Callable[[Any, Any], int]] = None,
key: Optional[Callable[[Any], Any]] = None,
reverse: bool = False,
) -> List[Any]:
# Security: Validate input types
if not isinstance(array, list):
raise TypeError("First argument must be a list")
if comparator is not None and not callable(comparator):
raise TypeError("Comparator must be callable")
if key is not None and not callable(key):
raise TypeError("Key must be callable")
# DRY principle: Single validation for mutually exclusive parameters
if comparator is not None and key is not None:
raise ValueError("Cannot specify both comparator and key parameters")
# Performance: Handle empty arrays efficiently
if not array:
return array
# Stability & Performance: Use Python's stable Timsort algorithm
try:
if comparator is not None:
# Convert comparator to key function for performance
array.sort(key=ft_cmp_to_key(comparator))
else:
# Use built-in sort with optional key and reverse
array.sort(key=key, reverse=reverse)
except (TypeError, AttributeError) as e:
# Security: Catch and re-raise with context
raise TypeError(f"Sort operation failed: {str(e)}")
return array
ft_cmp_to_key()
Convert a comparison function to a key function that can be used with sorted() etc.
Implementation
The comparison function should take two arguments and return a negative integer, zero or a positive integer depending on whether the first argument is considered smaller than, equal to, or larger than the second argument.
The returned key function takes one argument and returns an object that can be
compared with other objects returned by the same key function.
Example
sorted([4, 2, 9, 6, 5, 1, 8, 3, 7], key=ft_cmp_to_key(lambda x, y: x - y))
Expected output: [1, 2, 3, 4, 5, 6, 7, 8, 9]
Source Code
def ft_cmp_to_key(cmp: Callable[[Any, Any], int]):
class K:
__slots__ = ("obj",)
def __init__(self, obj: Any):
self.obj = obj
def __lt__(self, other: "K") -> bool: # type: ignore
return cmp(self.obj, other.obj) < 0 # type: ignore
def __gt__(self, other: "K") -> bool: # type: ignore
return cmp(self.obj, other.obj) > 0 # type: ignore
def __eq__(self, other: "K") -> bool: # type: ignore
return cmp(self.obj, other.obj) == 0 # type: ignore
def __le__(self, other: "K") -> bool: # type: ignore
return cmp(self.obj, other.obj) <= 0 # type: ignore
def __ge__(self, other: "K") -> bool: # type: ignore
return cmp(self.obj, other.obj) >= 0 # type: ignore
def __ne__(self, other: "K") -> bool: # type: ignore
return cmp(self.obj, other.obj) != 0 # type: ignore
return K
ft_reduce()
Applies a rolling computation to sequential pairs of values in an iterable.
Implementation
Args: func: A binary function to be applied to the items of the iterable. iterable: An iterable to be reduced. initializer: An initial value for the accumulator.
Returns:
The final accumulated value.
Raises:
TypeError: If the iterable is empty and no initializer is provided.
Example
ft_reduce(lambda x, y: x + y, [1, 2, 3, 4, 5])
Expected output: 15
Source Code
def ft_reduce(
func: Callable[[U, T], U], iterable: Iterable[T], initializer: Optional[U] = None
) -> U:
it = iter(iterable)
if initializer is None:
try:
acc: U = next(it) # type: ignore
except StopIteration:
raise TypeError("reduce() of empty sequence with no initial value")
else:
acc = initializer
for x in it:
acc = func(acc, x)
return acc # type: ignore
slice_()
Return a portion of array from index start up to, but not including, end.
Implementation
If end is None, return the single element at start as a list.
Args:
array: The list or string to slice.
start: The starting index of the slice.
end: The ending index of the slice (non-inclusive). Defaults to None.
Returns:
A list or substring representing the slice.
Example
slice_([1, 2, 3, 4], 1, 3)
Expected output: [2, 3]
Source Code
def slice_(
array: Union[List[T], str], start: int, end: Optional[int] = None
) -> Union[List[T], str]:
if end is None:
# return single element at index
try:
return [array[start]] # type: ignore
except Exception:
return []
return array[start:end] # type: ignore
remove()
Implementation
Implementation details are not available.
Example
Expected output: ``
Source Code
def remove(array: List[T], predicate: Callable[[T], bool]) -> List[T]:
removed: List[T] = []
i = 0
while i < len(array):
if predicate(array[i]):
removed.append(array.pop(i))
else:
i += 1
return removed
pull_at()
Removes elements from array corresponding to the specified indexes and returns a list of the
removed elements. Indexes may be specified as a list of indexes or as individual arguments.
Implementation
Args: array: List to pull from. indexes: Indexes to pull.
Returns:
Modified `array`.
Warning:
`array` is modified in place.
Example
pull_at([1, 2, 3, 4], 0, 2)
Expected output: [2, 4]
Source Code
def pull_at(array: List[T], *indexes: int) -> List[T]:
idxs = list(indexes)
if len(idxs) == 1 and isinstance(idxs[0], (list, tuple)):
idxs = list(idxs[0]) # type: ignore
to_remove = set(i if i >= 0 else i + len(array) for i in idxs)
return [x for i, x in enumerate(array) if i not in to_remove]
pop()
Remove and return an element from the list at the specified index. If no index is specified, removes and returns the last element.
Implementation
Args: array: The list to pop from. index: The index of the element to remove and return. If negative, it counts from the end of the list. Defaults to the last element.
Returns:
The element removed from the list.
Raises:
IndexError: If the list is empty.
Example
pop([1, 2, 3])
Expected output: 3
Source Code
def pop(array: List[T], index: Optional[int] = None) -> T:
if not array:
raise IndexError("pop from empty list")
if index is None:
return array.pop()
if index < 0:
index += len(array)
return array.pop(index)
intercalate()
Creates a new list by intercalating a given list of elements with a separator value.
Implementation
Args: array: List of elements to intercalate. separator: List of separator values to insert between elements.
Returns:
New list with separator values inserted between elements.
Example
intercalate([1, 2, 3], [4, 5, 6])
Expected output: [1, 4, 5, 6, 2, 4, 5, 6, 3]
Source Code
def intercalate(array: List[T], separator: List[T]) -> List[T]:
result: List[T] = []
for i, x in enumerate(array):
if i:
result.extend(separator)
if isinstance(x, list):
result.extend(x)
else:
result.append(x) # type: ignore
return result
sorted_uniq_by()
Creates a duplicate-free version of an array, keeping only the first occurrence of each element based on the iteratee function, then sorted by the original elements.
Implementation
Args: array: The input array to process iteratee: Function to compute the unique key for each element
Returns:
New array with unique elements (by iteratee) sorted by the original element values
Algorithm:
1. Collect unique elements by iteratee key, keeping first occurrence
2. Sort the unique elements by their original values (not iteratee values)
3. Return the sorted unique array
Security & Performance:
- Input validation for safety
- Efficient single-pass uniqueness detection
- Direct sorting of original elements
Example
sorted_uniq_by([1, 2, 3, 2, 1], lambda x: x % 2)
Expected output: [1, 2]
Source Code
def sorted_uniq_by(array: List[Any], iteratee: Callable[[Any], Any]) -> List[Any]:
if not array:
return []
if not callable(iteratee):
raise TypeError("Iteratee must be callable")
# Track seen keys and collect unique elements
seen_keys: Set[Any] = set()
unique_elements: List[Any] = []
# First pass: collect unique elements (first occurrence only)
for element in array:
try:
key = iteratee(element)
if key not in seen_keys:
seen_keys.add(key)
unique_elements.append(element)
except (TypeError, AttributeError) as e:
raise TypeError(f"Iteratee function failed on element {element}: {str(e)}")
# Sort by the original elements themselves, not by iteratee values
unique_elements.sort()
return unique_elements
sorted_uniq()
Creates a duplicate-free version of an array, keeping only the first occurrence of each element, then sorted by the original elements.
Implementation
Args: array: The input array to process
Returns:
New array with unique elements sorted by the original element values
Algorithm:
1. Collect unique elements, keeping first occurrence
2. Sort the unique elements by their original values
3. Return the sorted unique array
Security & Performance:
- Input validation for safety
- Efficient single-pass uniqueness detection
- Direct sorting of original elements
Example
sorted_uniq([1, 2, 3, 2, 1])
Expected output: [1, 2, 3]
Source Code
def sorted_uniq(array: List[T]) -> List[T]:
seen = set()
result: List[T] = []
for x in sorted(array): # type: ignore
if x not in seen:
seen.add(x)
result.append(x)
return result
sorted_last_index_by()
Returns the highest index at which value should be inserted into array in order to maintain
the sort order, using a key function to extract the comparison key.
Implementation
Args: array: The array to inspect. value: The value to evaluate for insertion. key: A function or string to extract the key from each element.
Returns:
The index at which the value should be inserted to keep the array sorted.
Example
sorted_last_index_by([{'x': 1}, {'x': 2}, {'x': 3}], {'x': 2}, 'x')
Expected output: 2
Source Code
def sorted_last_index_by(
array: List[T], value: T, key: Union[str, Callable[[T], Any]]
) -> int:
if isinstance(key, str):
fn = lambda x: x.get(key) if isinstance(x, dict) else getattr(x, key, None) # noqa: E731
else:
fn = key # type: ignore
keys = [fn(x) for x in array]
return bisect.bisect_right(keys, fn(value)) # type: ignore
sorted_index_by()
Returns the index at which the value should be inserted to maintain sorted order.
Implementation
Args: array: The array to search. value: The value to search for. key: A function or string to extract the key from each element.
Returns:
The index at which the value should be inserted.
Example
sorted_index_by([1, 2, 3], 4, lambda x: x)
Expected output: 3
Source Code
def sorted_index_by(
array: List[T], value: T, key: Union[str, Callable[[T], Any]]
) -> int:
if isinstance(key, str):
fn = lambda x: x.get(key) if isinstance(x, dict) else getattr(x, key, None) # noqa: E731
else:
fn = key # type: ignore
keys = [fn(x) for x in array]
return bisect.bisect_left(keys, fn(value)) # type: ignore
concat()
Flattens an array of arrays or values into a single array.
Implementation
Args: *arrays: The arrays or values to flatten.
Returns:
A flattened list.
Example
concat([1, 2, 3], [4, [5, 6]], 7, 8)
Expected output: [1, 2, 3, 4, 5, 6, 7, 8]
Source Code
def concat(*arrays: Union[List[T], T]) -> List[T]:
result: List[T] = []
for arr in arrays:
if isinstance(arr, (list, tuple)):
result.extend(arr) # type: ignore
else:
result.append(arr) # type: ignore
return result
zip_object_deep()
Creates a nested object from the given keys and values. If the values list is not provided, the keys list is treated as a list of key-value pairs.
Implementation
Args: keys: A list of keys or key-value pairs. values: A list of values to pair with the keys.
Returns:
A nested object with the key-value pairs.
Example
zip_object_deep(["a.b.c", "a.b.d"], [1, 2])
Expected output: {"a": {"b": {"c": 1, "d": 2}}}
Source Code
def zip_object_deep(
keys: List[Any], values: Optional[List[Any]] = None
) -> Dict[Any, Any]:
result: Dict[Any, Any] = {}
# Build key-value pairs
if values is None:
pairs = keys # type: ignore
else:
pairs = builtins.zip(keys, values) # type: ignore
for k, v in pairs:
# parse path
parts = re.findall(r"[^.\[\]]+", k) # type: ignore
node = result
for i, part in enumerate(parts):
is_last = i == len(parts) - 1
# next part type
if part.isdigit():
idx = int(part)
if not isinstance(node, list):
raise TypeError("Expected list at part %r" % part)
while len(node) <= idx:
node.append({})
if is_last:
node[idx] = v
else:
if not isinstance(node[idx], dict):
node[idx] = {}
node = node[idx]
else:
if is_last:
node[part] = v # type: ignore
else:
# determine if next is index
nxt = parts[i + 1]
if nxt.isdigit():
if part not in node or not isinstance(node[part], list):
node[part] = []
else:
if part not in node or not isinstance(node[part], dict):
node[part] = {}
node = node[part] # type: ignore
return result
zip_object()
Creates an object composed of the given keys and values.
If the values list is not provided, the keys list is treated as a list of key-value pairs.
Implementation
Args: keys: A list of keys or key-value pairs. values: A list of values to pair with the keys.
Returns:
An object with the key-value pairs.
Example
zip_object(["a", "b"], [1, 2])
Expected output: {"a": 1, "b": 2}
Source Code
def zip_object(keys: List[K], values: Optional[List[V]] = None) -> Dict[K, V]:
if values is None:
return {k: v for k, v in keys} # type: ignore
return {k: v for k, v in builtins.zip(keys, values)}
uniq_with()
Creates a duplicate-value-free version of the array. Only the first occurrence of each value is kept. The order of result values is determined by the order they occur in the array.
Implementation
Args: array: List to process. comparator: Function to compare the elements of the arrays.
Returns:
Unique list.
Example
uniq_with([1, 2, 3, 1, 2, 3], lambda a, b: a == b)
Expected output: [1, 2, 3]
Source Code
def uniq_with(array: List[T], comparator: Callable[[T, T], bool]) -> List[T]:
result: List[T] = []
for item in array:
if not any(comparator(item, x) for x in result):
result.append(item)
return result
uniq_by()
Creates a duplicate-value-free version of the array. Only the first occurrence of each value is kept. The order of result values is determined by the order they occur in the array.
Implementation
Args:
array: List to process.
iteratee: Function to transform the elements of the arrays, or a string or a dictionary
that is used to filter the elements of the arrays. If a string is passed, it is used to
access the given key of each element in the arrays. If a dictionary is passed, it is
used to filter the elements of the arrays; the function will return True for
elements that have the properties of the given object, else False.
Returns:
Unique list.
Example
uniq_by([1, 2, 3, 1, 2, 3], lambda val: val % 2)
Expected output: [1, 2]
Source Code
def uniq_by(
array: List[T], iteratee: Union[str, Callable[[T], Any], Dict[str, Any]]
) -> List[T]:
# support dict, str, or callable
if isinstance(iteratee, dict):
pred = lambda x: all(x.get(k) == v for k, v in iteratee.items()) # noqa: E731
key_fn = lambda x: bool(pred(x)) # noqa: E731
elif isinstance(iteratee, str):
def key_fn(x):
return (
x.get(iteratee) if isinstance(x, dict) else getattr(x, iteratee, None)
)
else:
key_fn = iteratee # type: ignore
seen = set()
result: List[T] = []
for x in array:
k = key_fn(x)
if k not in seen:
seen.add(k)
result.append(x)
return result
union_with()
Creates a new list that contains unique elements from all provided arrays, determined by the comparator function.
Implementation
Args: arrays: Variable number of lists from which to compute the union. comparator: Optional function that is applied to compare the elements of the arrays.
Returns:
A list of unique elements present in any of the input arrays based on the comparator.
Example
union_with([1, 2, 3], [2, 3, 4], lambda a, b: a == b)
Expected output: [1, 2, 3, 4]
Source Code
def union_with(array: List[T], *args) -> List[T]:
comparator = None
rest_arrays: List[List[T]] = []
if args and callable(args[-1]):
comparator = args[-1]
rest_arrays = list(args[:-1]) # type: ignore
else:
rest_arrays = list(args) # type: ignore
result: List[T] = []
cmp = comparator if callable(comparator) else (lambda a, b: a == b)
for x in concat(array, *rest_arrays):
if not any(cmp(x, y) for y in result):
result.append(x)
return result
union_by()
Creates a new list that contains unique elements from all provided arrays, determined by the result of running each element through the iteratee function.
Implementation
Args: arrays: Variable number of lists from which to compute the union. iteratee: An optional function that is applied to each element to generate the criterion by which uniqueness is computed.
Returns:
A list of unique elements present in any of the input arrays based on the iteratee.
Example
union_by([1, 2, 3], [2, 3, 4], lambda x: x % 2)
Expected output: [1, 2]
Source Code
def union_by(
*arrays: List[T], iteratee: Optional[Callable[[T], Any]] = None
) -> List[T]:
args = list(arrays)
if not arrays:
return []
# if last positional is callable and iteratee not provided
if iteratee is None and callable(arrays[-1]):
iteratee = arrays[-1] # type: ignore
args = args[:-1]
fn = iteratee if callable(iteratee) else (lambda x: x) # type: ignore
seen = set()
result: List[T] = []
for arr in args:
for x in arr:
k = fn(x)
if k not in seen:
seen.add(k)
result.append(x)
return result
take_right_while()
Creates a slice of array with elements taken from the end. Elements are taken until predicate returns falsey. The predicate is invoked with one argument: (value).
Implementation
Args: array: List to process. predicate: Function invoked per iteration.
Returns:
Taken list.
Example
take_right_while([1, 2, 3, 4], lambda x: x >= 3)
Expected output: [3, 4]
Source Code
def take_right_while(array: List[T], predicate: Callable[[T], bool]) -> List[T]:
result: List[T] = []
for x in reversed(array):
if predicate(x):
result.insert(0, x)
else:
break
return result
take_while()
Creates a slice of array with elements taken from the beginning. Elements are taken until predicate returns falsey. The predicate is invoked with one argument: (value).
Implementation
Args: array: List to process. predicate: Function invoked per iteration.
Returns:
Taken list.
Example
take_while([1, 2, 3, 4], lambda x: x < 3)
Expected output: [1, 2]
Source Code
def take_while(array: List[T], predicate: Callable[[T], bool]) -> List[T]:
result: List[T] = []
for x in array:
if predicate(x):
result.append(x)
else:
break
return result
take_right()
Creates a slice of array with n elements taken from the end.
Implementation
Args:
array: List to process.
n: Number of elements to take. Defaults to 1.
Returns:
Taken list.
Example
take_right([1, 2, 3, 4], 2)
Expected output: [3, 4]
Source Code
def take_right(array: List[T], n: int = 1) -> List[T]:
return array[-n:] if n else []
take()
Creates a slice of array with n elements taken from the beginning.
Implementation
Args:
array: List to process.
n: Number of elements to take. Defaults to 1.
Returns:
Taken list.
Example
take([1, 2, 3, 4], 2)
Expected output: [1, 2]
Source Code
def take(array: List[T], n: int = 1) -> List[T]:
return array[:n]
tail()
Returns all but the first element of array.
Implementation
Args: array: List from which to retrieve all but the first element.
Returns:
A new list containing all but the first element of `array`.
Example
tail([1, 2, 3])
Expected output: [2, 3]
Source Code
def tail(array: List[T]) -> List[T]:
return array[1:]
split_at()
Splits an array into two sub-arrays at a specified index.
Implementation
Args: array: The list to split. index: The index at which to split the array.
Returns:
A list containing two sub-arrays. The first sub-array contains elements
from the start of the array up to, but not including, the specified
index. The second sub-array contains elements from the specified index
to the end of the array.
Example
split_at([1, 2, 3, 4], 2)
Expected output: [[1, 2], [3, 4]]
Source Code
def split_at(array: List[T], index: int) -> List[List[T]]:
return [array[:index], array[index:]]
union()
Combines arrays and removes duplicates
Implementation
Uses set union operations
Example
union = UniCoreFW.union([1, 2], [2, 3], [3, 4])
Expected output: [1, 2, 3, 4]
Source Code
def union(*arrays):
return list(set().union(*arrays))
last_index_of()
Returns the last index of a value in an array
Implementation
Iterates from the end of the array to find the first occurrence
Example
idx = UniCoreFW.last_index_of([1, 2, 3, 2, 1], 2)
Expected output: 3
Source Code
def last_index_of(array, value):
for i in range(len(array) - 1, -1, -1):
if array[i] == value:
return i
return -1
index_by()
Indexes an array by a key or key function
Implementation
Creates a dictionary with keys determined by the key function
Example
indexed = UniCoreFW.index_by([{"id": 1, "name": "John"}, {"id": 2, "name": "Jane"}], "id")
Expected output: {1: {"id": 1, "name": "John"}, 2: {"id": 2, "name": "Jane"}}
Source Code
def index_by(array, key_func):
if isinstance(key_func, str):
return {item[key_func]: item for item in array if key_func in item}
else:
return {key_func(item): item for item in array}