Last active
December 3, 2023 18:45
-
-
Save stephane-segning/d7147ee103bc48b5eeb6d6e56b3ac14a to your computer and use it in GitHub Desktop.
Check if a is contained in b
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from typing import TypeVar, List, Callable | |
Ta = TypeVar('Ta') | |
Tb = TypeVar('Tb') | |
def check_if_contained( | |
a: List[Ta], | |
b: List[Tb], | |
compare: Callable[[Ta, Tb], bool] = lambda x, y: x == y, | |
get_b_key: Callable[[Tb], str] = lambda x: x | |
) -> bool: | |
""" | |
Check if a is contained in b | |
:param a: | |
:param b: | |
:param compare: | |
:param get_b_key: | |
:return: | |
""" | |
alter_register: dict[str] = {} | |
y = 0 | |
for i in range(len(a)): | |
found = False | |
# If a[i] is already in the register, skip it | |
if a[i] in alter_register: | |
continue | |
# Search for a[i] in b | |
for j in range(y, len(b)): | |
b_key = get_b_key(b[j]) | |
alter_register[b_key] = b[j] | |
if compare(a[i], b[j]): | |
found = True | |
y = j + 1 | |
continue | |
if not found: | |
return False | |
return True | |
if __name__ == '__main__': | |
_a = [1, 2, 7, 8, 9] | |
_b = [{'id': 1}, {'id': 2}, {'id': 3}, {'id': 4}, {'id': 5}, {'id': 6}, {'id': 7}, {'id': 8}, {'id': 9}] | |
print(check_if_contained(_a, _b, lambda x, y: x == y['id'], lambda x: x['id'])) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment