Advertisement
Guest User

Untitled

a guest
Dec 15th, 2021
244
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.73 KB | None | 0 0
  1. #!/usr/bin/python3
  2. import sys
  3.  
  4. def get_bit(data, pos):
  5. char = int(pos / 4)
  6. bit = 3 - (pos % 4)
  7. n = int(data[char], 16)
  8. b = (n & (1 << bit)) >> bit
  9. return b
  10.  
  11. def read_bits(data, pos, num):
  12. n = 0
  13. for i in range(num):
  14. n *= 2
  15. b = get_bit(data, pos + i)
  16. n += b
  17. return (n, pos + num)
  18.  
  19. def get_version(data, pos):
  20. return read_bits(data, pos, 3)
  21.  
  22. def get_type(data, pos):
  23. return read_bits(data, pos, 3)
  24.  
  25. def get_literal(data, pos):
  26. l = 0
  27. while True:
  28. g, pos = read_bits(data, pos, 5)
  29. l = l << 4
  30. # Not last.
  31. if g & (1 << 4):
  32. g &= ~(1<<4)
  33. l += g
  34. else:
  35. l += g
  36. return (l, pos)
  37.  
  38. class Packet:
  39. def __init__(self):
  40. self.version = None
  41. self.type = None
  42. self.literal = None
  43. self.length_type = None
  44. self.subpackets = []
  45.  
  46. def parse_packet(data, pos):
  47. p = Packet()
  48. p.version, pos = get_version(data, pos)
  49. p.type, pos = get_type(data, pos)
  50. # Literal.
  51. if p.type == 4:
  52. p.literal, pos = get_literal(data, pos)
  53. else:
  54. p.length_type, pos = read_bits(data, pos, 1)
  55. if p.length_type == 0:
  56. packets_length, pos = read_bits(data, pos, 15)
  57. cur_pos = pos
  58. while pos < cur_pos + packets_length:
  59. np, pos = parse_packet(data, pos)
  60. p.subpackets.append(np)
  61. else:
  62. subpackets, pos = read_bits(data, pos, 11)
  63. for i in range(subpackets):
  64. np, pos = parse_packet(data, pos)
  65. p.subpackets.append(np)
  66. return p, pos
  67.  
  68. def add_versions(packet):
  69. return packet.version + sum([add_versions(p) for p in packet.subpackets])
  70.  
  71. def calculate_value(packet):
  72. if packet.type == 4:
  73. print(packet.literal)
  74. return packet.literal
  75. else:
  76. subvalues = [calculate_value(p) for p in packet.subpackets]
  77. if packet.type == 0:
  78. return sum(subvalues)
  79. elif packet.type == 1:
  80. product = 1
  81. for v in subvalues:
  82. product *= v
  83. return product
  84. elif packet.type == 2:
  85. return min(subvalues)
  86. elif packet.type == 3:
  87. return max(subvalues)
  88. elif packet.type == 5:
  89. return subvalues[0] > subvalues[1]
  90. elif packet.type == 6:
  91. return subvalues[0] < subvalues[1]
  92. elif packet.type == 7:
  93. return subvalues[0] == subvalues[1]
  94.  
  95. def main():
  96. board = []
  97. line = sys.stdin.readline().strip()
  98. p, pos = parse_packet(line, 0)
  99.  
  100. print(calculate_value(p))
  101.  
  102. if __name__ == "__main__":
  103. main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement