Created
October 19, 2024 22:14
-
-
Save wsgac/286c29a81fe73517414e65a558d807f9 to your computer and use it in GitHub Desktop.
Recursive dict reversal in Python
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
def invert_recursive_dict(d: Dict) -> Dict: | |
""" | |
Assuming `d` is a recursive Dict, invert it by mapping its leaves to the | |
lists/paths of keys leading to them in the original dict. | |
""" | |
def invert(d, path: List, acc: Dict): | |
if isinstance(d, Dict): | |
# Handle dict contents recursively | |
for k, i in d.items(): | |
invert(i, path+[k], acc) | |
else: | |
# Arrived at leaf - store in the inverted dict | |
acc[d] = path | |
return acc | |
return invert(d, [], {}) | |
# Example | |
BITS_TO_JMP_INSTR = { | |
# B2 B1 B0 | |
False: { | |
False: { | |
False: None, | |
True: "JGT", | |
}, | |
True: { | |
False: "JEQ", | |
True: "JGE", | |
}, | |
}, | |
True: { | |
False: { | |
False: "JLT", | |
True: "JNE", | |
}, | |
True: { | |
False: "JLE", | |
True: "JMP", | |
}, | |
}, | |
} | |
# invert_recursive_dict(BITS_TO_JMP_INSTR) | |
# -> | |
# { | |
# None: [False, False, False], | |
# "JGT": [False, False, True], | |
# "JEQ": [False, True, False], | |
# "JGE": [False, True, True], | |
# "JLT": [True, False, False], | |
# "JNE": [True, False, True], | |
# "JLE": [True, True, False], | |
# "JMP": [True, True, True], | |
# } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Written as an exploration of various ways to represent the bit structures of machine instructions as part of the Nand2Tetris course.