# quantum-algorithms

git clone git://git.codymlewis.com/quantum-algorithms.git
Log | Files | Refs | README

swap (2432B)

```      1 #!/usr/bin/env python3
2
3 '''
4 A simple quantum circuit that swaps qubits sequentially
5
6 Copyright (C) 2020 Cody Lewis
7
8 This program is free software: you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation, either version 3 of the License, or
11 (at your option) any later version.
12
13 This program is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 GNU General Public License for more details.
17
18 You should have received a copy of the GNU General Public License
19 along with this program.  If not, see <https://www.gnu.org/licenses/>.
20 '''
21
22 import argparse
23
24 from qiskit import QuantumCircuit, execute
25 from qiskit.providers.aer import Aer
26
27 def swap_qubits(qcircuit, i, j):
28     '''Performs that transform swapping the value in q_i with q_j'''
29     qcircuit.cnot(i, j)
30     qcircuit.cnot(j, i)
31     qcircuit.cnot(i, j)
32
33 def to_statevector(a):
34     '''Convert a binary string into its representative qubit statevector'''
35     if a == "0":
36         return [1, 0]
37     return [0, 1]
38
39 def create_circuit(in_states):
40     '''Construct the circuit with the input states set'''
41     n = len(in_states)
42     qcircuit = QuantumCircuit(n)
43     for i in range(n):
44         qcircuit.initialize(to_statevector(in_states[i]), i)
45     for i in range(n - 1):
46         swap_qubits(qcircuit, i, i + 1)
47     meas = QuantumCircuit(n, n)
48     meas.barrier(range(n))
49     meas.measure(range(n), range(n))
50     return qcircuit + meas
51
52
53 if __name__ == '__main__':
54     print(
55         "swap  Copyright (C) 2020  Cody Lewis\n" +
56         "This program comes with ABSOLUTELY NO WARRANTY.\n" +
57         "This is free software, and you are welcome to redistribute it under certain conditions.\n"
58     )
59     PARSER = argparse.ArgumentParser(
60         description="A simple quantum circuit that swaps qubits sequentially"
61     )