An example of swapping two bits from input to output in Qiskit.
Demo on IBM Quantum Composer.
[0 0]
X1: [0, 1]
CX1: [1, 2]
CX2: [3, 3]
CX3: [4, 4]
M1: [5,4]
M2: [5,5]
print(swap.depth())
# 5| def swap(b, a): | |
| """ | |
| A quantum circuit that swaps the input bits. | |
| 01 => 10 | |
| """ | |
| swap = QuantumCircuit(2, 2) | |
| if a: | |
| swap.x(0) | |
| if b: | |
| swap.x(1) | |
| swap.cx(0, 1) | |
| swap.cx(1, 0) | |
| swap.cx(0, 1) | |
| swap.measure_all() | |
| job = qiskit.execute(swap, qiskit.BasicAer.get_backend('qasm_simulator')) | |
| return job.result().get_counts() |
| def swap_test(b, a): | |
| # Set our input bits to be swapped. | |
| input = [b, a] | |
| # Create a string version '10'. | |
| input_str = '{}{}'.format(input[0], input[1]) | |
| # Swap the bits. | |
| output = swap(input[0], input[1]) | |
| # Create a string version of the output '01'. | |
| output_str = list(output.keys())[0].split(' ')[0] | |
| # Verify the output. | |
| print('{} => {} ? {}'.format(input_str, output_str, input_str[::-1] == output_str)) | |
| swap_test(0, 0) | |
| swap_test(1, 0) | |
| swap_test(0, 1) | |
| swap_test(1, 1) |
| Note, input/output bits are read from right to left. | |
| 00 => 00 ? True | |
| 10 => 01 ? True | |
| 01 => 10 ? True | |
| 11 => 11 ? True |
An example of swapping two bits from input to output in Qiskit.
Demo on IBM Quantum Composer.
[0 0]
X1: [0, 1]
CX1: [1, 2]
CX2: [3, 3]
CX3: [4, 4]
M1: [5,4]
M2: [5,5]
print(swap.depth())
# 5