Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/python3
- import sys
- def get_bit(data, pos):
- char = int(pos / 4)
- bit = 3 - (pos % 4)
- n = int(data[char], 16)
- b = (n & (1 << bit)) >> bit
- return b
- def read_bits(data, pos, num):
- n = 0
- for i in range(num):
- n *= 2
- b = get_bit(data, pos + i)
- n += b
- return (n, pos + num)
- def get_version(data, pos):
- return read_bits(data, pos, 3)
- def get_type(data, pos):
- return read_bits(data, pos, 3)
- def get_literal(data, pos):
- l = 0
- while True:
- g, pos = read_bits(data, pos, 5)
- l = l << 4
- # Not last.
- if g & (1 << 4):
- g &= ~(1<<4)
- l += g
- else:
- l += g
- return (l, pos)
- class Packet:
- def __init__(self):
- self.version = None
- self.type = None
- self.literal = None
- self.length_type = None
- self.subpackets = []
- def parse_packet(data, pos):
- p = Packet()
- p.version, pos = get_version(data, pos)
- p.type, pos = get_type(data, pos)
- # Literal.
- if p.type == 4:
- p.literal, pos = get_literal(data, pos)
- else:
- p.length_type, pos = read_bits(data, pos, 1)
- if p.length_type == 0:
- packets_length, pos = read_bits(data, pos, 15)
- cur_pos = pos
- while pos < cur_pos + packets_length:
- np, pos = parse_packet(data, pos)
- p.subpackets.append(np)
- else:
- subpackets, pos = read_bits(data, pos, 11)
- for i in range(subpackets):
- np, pos = parse_packet(data, pos)
- p.subpackets.append(np)
- return p, pos
- def add_versions(packet):
- return packet.version + sum([add_versions(p) for p in packet.subpackets])
- def calculate_value(packet):
- if packet.type == 4:
- print(packet.literal)
- return packet.literal
- else:
- subvalues = [calculate_value(p) for p in packet.subpackets]
- if packet.type == 0:
- return sum(subvalues)
- elif packet.type == 1:
- product = 1
- for v in subvalues:
- product *= v
- return product
- elif packet.type == 2:
- return min(subvalues)
- elif packet.type == 3:
- return max(subvalues)
- elif packet.type == 5:
- return subvalues[0] > subvalues[1]
- elif packet.type == 6:
- return subvalues[0] < subvalues[1]
- elif packet.type == 7:
- return subvalues[0] == subvalues[1]
- def main():
- board = []
- line = sys.stdin.readline().strip()
- p, pos = parse_packet(line, 0)
- print(calculate_value(p))
- if __name__ == "__main__":
- main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement