Last active
January 6, 2021 12:47
-
-
Save hosjiu1702/033229283233e89bd6780a6ed23a34d6 to your computer and use it in GitHub Desktop.
Solution for problem 2 (FTech Interview)
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
""" | |
Author: hosjiu | |
Email: hosjiu1702@gmail.com | |
This python script is tested on Python 3.6.10 (on my local machine) | |
but it can still works for another python version >3.6 | |
""" | |
from typing import List | |
from collections import namedtuple | |
def solve(arr: List) -> List: | |
""" For much more clarification | |
We use namedtuple instead of original tuple | |
""" | |
Blob = namedtuple('NamedArray', ['value', 'index', 'result'] ) | |
""" Add Index and a 'placeholder' with | |
pre-defined value None to each of element in the List | |
""" | |
for idx, _ in enumerate(arr): | |
t = [arr[idx], idx, None] | |
arr[idx] = Blob(*t) # Unpacking? | |
# Sort Array In-Place based on Value | |
arr = sorted(arr, key=lambda x: x.value) | |
# Compute and add Result | |
for idx, x in enumerate(arr): | |
# It's a very bad workaround I think | |
# Just should use List instead of Tuple from the beginning | |
x = list(x) | |
x[2] = idx | |
x = Blob(*x) | |
arr[idx] = x | |
# Re-sort Array again based on Index | |
arr = sorted(arr, key=lambda x: x.index) | |
return [x.result for x in arr] | |
if __name__ == '__main__': | |
# Pre-defined test case for debugging | |
test_case = [8, 1, 2, 3, 4] | |
print(solve(test_case)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment