Created
July 19, 2022 18:45
-
-
Save realFranco/370e6f002fae2cd42f21f747768b8b91 to your computer and use it in GitHub Desktop.
After watching a live coding interview experience I decided to develop the solution for the problem. #python #pyton3 #codinginterview #coding #interview #test
This file contains 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
""" | |
Write a function that perform as an SQL-join. | |
""" | |
BRAND = [ | |
{'id': 0, 'name': 'Ferrari', 'year': 1998}, | |
{'id': 1, 'name': 'Red Bull'}, | |
{'id': 2, 'name': 'Mclaren'} | |
] | |
ENGINE = [ | |
{'id': 2, 'engine': 'Mercedes', 'year': 1998} | |
] | |
# Big O complexity: | |
# best case: O(Nx1) -> O(N) | |
# worst case: O(N^3) | |
def join_python(left_data: list, right_data: list, key: str) -> list: | |
cache = {} | |
seek_at = set() | |
out_data = [] | |
for obj in left_data: | |
if key in obj: | |
indexable_key = obj[key] | |
seek_at.add(indexable_key) | |
cache[ indexable_key ] = obj | |
for row in right_data: | |
if key in row and row[key] in seek_at: # This line could be O(N) | |
cache[ row[key] ].update(row) | |
out_data.append( cache[row[key]] ) # This bould be O(N) | |
return out_data | |
if __name__ == '__main__': | |
out = join_python( | |
left_data=BRAND, | |
right_data=ENGINE, | |
# key='id', | |
key='year' | |
) | |
print(out) | |
""" | |
out: [{'id': 2, 'name': 'Ferrari', 'year': 1998, 'engine': 'Mercedes'} | |
""" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment