Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- def process1(s, part2=False):
- s = ''.join(f'{int(nibble, 16):04b}' for nibble in s.strip())
- operation_for_id = {
- 0: lambda *operands: sum(operands),
- 1: lambda *operands: np.prod(operands),
- 2: lambda *operands: min(operands),
- 3: lambda *operands: max(operands),
- 5: lambda operand1, operand2: int(operand1 > operand2),
- 6: lambda operand1, operand2: int(operand1 < operand2),
- 7: lambda operand1, operand2: int(operand1 == operand2),
- }
- sum_versions = 0
- def read_bits(n):
- nonlocal s
- value = int(s[:n], 2)
- s = s[n:]
- return value
- def parse():
- nonlocal sum_versions
- version = read_bits(3)
- sum_versions += version
- id = read_bits(3)
- if id == 4:
- number = 0
- more = True
- while more:
- more = read_bits(1)
- number = number * 16 + read_bits(4)
- return number
- operands = []
- length_type = read_bits(1)
- if length_type == 0:
- num_bits = read_bits(15)
- len0 = len(s)
- while len0 - len(s) != num_bits:
- operands.append(parse())
- else:
- num_packets = read_bits(11)
- for _ in range(num_packets):
- operands.append(parse())
- return operation_for_id[id](*operands)
- result = parse()
- return result if part2 else sum_versions
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement