Skip to content

Instantly share code, notes, and snippets.

@wsgac
Created October 19, 2024 22:14
Show Gist options
  • Save wsgac/286c29a81fe73517414e65a558d807f9 to your computer and use it in GitHub Desktop.
Save wsgac/286c29a81fe73517414e65a558d807f9 to your computer and use it in GitHub Desktop.
Recursive dict reversal in Python
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],
# }
@wsgac
Copy link
Author

wsgac commented Oct 19, 2024

Written as an exploration of various ways to represent the bit structures of machine instructions as part of the Nand2Tetris course.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment