Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import sys
- class Gate:
- def __init__(self, index: int, operation: str, input_gates):
- self._index = index
- self._operation = operation
- self._input_gates = input_gates
- def __str__(self):
- if self._operation is None:
- return 'OUTPUT ' + str(self._index) + ' ' + ' '.join([str(item.get_id()) for item in self._input_gates])
- else:
- return 'GATE ' + str(self._index) + ' ' + self._operation + ' ' \
- + ' '.join([str(item.get_id()) for item in self._input_gates])
- def get_id(self):
- return self._index
- class InputGate:
- def __init__(self, index):
- self._index = index
- def get_id(self):
- return self._index
- def create_input(n):
- a = []
- b = []
- c = []
- for idx in range(n):
- a.append(InputGate(idx))
- b.append(InputGate(idx + n))
- c.append(InputGate(idx + 2 * n))
- return a, b, c
- def build_xor_median_block(start_index, a, b, c):
- gate_1 = Gate(start_index, 'AND', [a, b])
- gate_2 = Gate(start_index + 1, 'AND', [a, c])
- gate_3 = Gate(start_index + 2, 'AND', [b, c])
- gate_4 = Gate(start_index + 3, 'OR', [a, b])
- gate_5 = Gate(start_index + 4, 'NOT', [gate_1])
- gate_6 = Gate(start_index + 5, 'AND', [gate_4, gate_5]) # XOR a, b
- gate_7 = Gate(start_index + 6, 'OR', [gate_1, gate_2])
- gate_8 = Gate(start_index + 7, 'OR', [gate_7, gate_3]) # Median(a,b,c)
- gate_9 = Gate(start_index + 8, 'OR', [gate_6, c])
- gate_10 = Gate(start_index + 9, 'AND', [gate_6, c])
- gate_11 = Gate(start_index + 10, 'NOT', [gate_10])
- gate_12 = Gate(start_index + 11, 'AND', [gate_11, gate_9]) # XOR_3(a,b,c)
- gates = [gate_1, gate_2, gate_3, gate_4, gate_5, gate_6, gate_7, gate_8, gate_9, gate_10, gate_11, gate_12]
- return gates, gate_12, gate_8, start_index + 12
- def build_first_block(start_index, a, b, c):
- gates, gate_12, gate_8, start_index = build_xor_median_block(start_index, a, b, c)
- gate_13 = Gate(start_index + 1, 'AND', [gates[0], gates[4]]) # gate_1 & not gate_1
- gates.append(gate_13)
- return gates, gate_12, gate_8, gate_13, start_index + 1
- def read_input():
- n = int(input())
- return n
- def main():
- n = read_input()
- a, b, c = create_input(n)
- x = []
- y = []
- all_gates = []
- zero = None
- index = 3 * n
- for idx in range(n):
- if idx == 0:
- gates, t0, t1, zero, index = build_first_block(index, a[idx], b[idx], c[idx])
- else:
- gates, t0, t1, index = build_xor_median_block(index, a[idx], b[idx], c[idx])
- if idx == 0:
- y.append(Gate(n + 1, None, [zero]))
- x.append(Gate(idx, None, [t0]))
- if idx == n - 1:
- x.append(Gate(idx + 1, None, [zero]))
- y.append(Gate(idx + 1 + n + 1, None, [t1]))
- for gate in gates:
- all_gates.append(gate)
- for gate in all_gates:
- sys.stdout.write(str(gate) + '\n')
- for gate in x:
- sys.stdout.write(str(gate) + '\n')
- for gate in y:
- sys.stdout.write(str(gate) + '\n')
- if __name__ == '__main__':
- main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement