In [1]:
from qiskit import *
from qiskit.visualization import plot_histogram
%matplotlib inline
In [2]:
secretNumber = '10001011'
In [3]:
circuit = QuantumCircuit(len(secretNumber) + 1, len(secretNumber)) # n+1 qubits and n classical bits
In [4]:
# Bernstein-Vazirani: Put H on all qubits, put CNOT on the ones that are 1
circuit.h(range(len(secretNumber))) # apply H to qubits
circuit.x(len(secretNumber)) # Before applying H to the helper qubit, first apply a NOT gate
circuit.h(len(secretNumber)) # If you don't apply NOT and H gates to this qubit, you would get the result right half of the time (50%)
# You would get 0000000 from the results by applying these gates

circuit.barrier()

# Check if bit is 1 then apply CNOT, otherwise don't apply
# Ordering of the qubits are in a reverse way of indexes in Qiskit
# So make sure we reverse the secret number before we apply CNOT gates
#for index, one in enumerate(secretNumber[::-1]): # reverse the secret number, can also use reversed(secretNumber)
for index, one in enumerate(reversed(secretNumber)):
    print(f"index {index} is {one}")
    if one=="1":
        circuit.cx(index, len(secretNumber))

circuit.barrier()

circuit.h(range(len(secretNumber))) # We will not measure the helper qubit so don't apply H to it

circuit.barrier()

circuit.measure(range(len(secretNumber)),range(len(secretNumber)))
index 0 is 1
index 1 is 1
index 2 is 0
index 3 is 1
index 4 is 0
index 5 is 0
index 6 is 0
index 7 is 1
Out[4]:
<qiskit.circuit.instructionset.InstructionSet at 0x7fe85d8456a0>
In [5]:
circuit.draw(output='mpl')
Out[5]:
No description has been provided for this image
In [6]:
from qiskit_aer import Aer
simulator = Aer.get_backend("qasm_simulator")
result = simulator.run(circuit, shots=1).result()
counts = result.get_counts()
print(counts)
{'10001011': 1}