-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathcommon.py
More file actions
42 lines (33 loc) · 1 KB
/
Copy pathcommon.py
File metadata and controls
42 lines (33 loc) · 1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
from typing import List, Tuple
import re
import itertools
class Instruction:
address: int
value: int
mask: str
def __init__(self, instruction: str, mask: str):
if mask is None:
raise ValueError(f"bad mask")
m = re.match(r"mem\[(\d+)\] ?= ?(\d+)", instruction)
if m is None:
raise ValueError(f"unable to parse input instruction '{instruction}'")
self.mask = mask
self.address = int(m.group(1))
self.value = int(m.group(2))
def parse(instr: str) -> List[Instruction]:
retval = []
current_mask = None
for line in instr.strip().split("\n"):
if "mask" in line:
current_mask = line.split("=")[-1].strip()
else:
retval.append(Instruction(line, current_mask))
return retval
def number_to_base(n: int, b: int) -> str:
if n == 0:
return "0"
digits = []
while n:
digits.append(int(n % b))
n //= b
return "".join([str(x) for x in digits[::-1]])