DEV Community

Cover image for Quantum Python. A secret in one query: the Bernstein–Vazirani algorithm
Programming Central
Programming Central

Posted on

Quantum Python. A secret in one query: the Bernstein–Vazirani algorithm

Recover a hidden bit string in one circuit, in Python, on IBM's free quantum plan.

A program is given a function that takes a bit string and returns one bit. Somewhere in that function is a secret string, and the function's answer is the parity of the bits where the secret has a 1. Classically you ask one question per bit: for a three-bit secret, three calls. The Bernstein–Vazirani quantum algorithm needs one!

The trick is not magic and it is not a speedup you can feel at three bits. It is two ideas from the first chapters of the book: a qubit is a vector of two amplitudes, and a CNOT can write a parity into a sign instead of into a bit. A final Hadamard turns the sign back into a readable string.

You do not need physics to follow this. You need Python, six lines of linear algebra you can read as a table, and — if you want the device run — a free IBM Quantum account. The repository has the circuit, the harness and the recorded job; this article walks the small version.

Repo: github.com/edgarmilvus/quantum-python
Ebook: Quantum Python
GitHub: @edgarmilvus

What you need

Python 3.11 or 3.12, a terminal, and the repository. Nothing else for the first half. For the second half, an IBM Quantum account on the Open Plan, which gives ten minutes of QPU time every 28 days and is free.

git clone https://github.com/edgarmilvus/quantum-python.git
cd quantum-python
python3.11 -m venv .venv
source .venv/bin/activate
python -m pip install -r requirements.txt
Enter fullscreen mode Exit fullscreen mode

A qubit is two numbers

A qubit's state is a list of two complex numbers, [a, b]. The probability of reading 0 is |a|², the probability of reading 1 is |b|², and the two add to one. The states [1, 0] and [0, 1] are written |0⟩ and |1⟩.

[1/√2, 1/√2] is a superposition: half the shots read 0, half read 1. That is all a superposition is at this level — a list whose squared entries are probabilities.

Two gates

The Hadamard gate is a 2×2 matrix:

H = 1/√2 · [ 1   1 ]
           [ 1  -1 ]
Enter fullscreen mode Exit fullscreen mode

Applied to [1, 0] it gives [1/√2, 1/√2]; applied again it gives [1, 0] back. On a qubit already in a superposition it can turn a difference of signs into a difference of bits.

The CNOT is a two-qubit gate: it flips the second qubit when the first is 1, and does nothing otherwise. It is the gate that copies a parity — but only in a basis where the target is a bit.

The trick: a sign is information

Put the target qubit in [1/√2, -1/√2], written |−⟩. A CNOT from a data qubit to that target does not change the target's bits. It multiplies the whole state by −1 when the control is 1, and by +1 when it is 0.

That minus sign is the function's answer. It is invisible in a bit, and perfectly visible to a Hadamard: the final Hadamard on the data qubits turns the accumulated signs into a string that a measurement can read.

This is the phase kickback the book derives in chapter 6; here it is enough to know that a CNOT can write into a sign, and a Hadamard can read it.

The circuit for 101

One ancilla, three data qubits, one CNOT per 1 in the secret:

q0: ─H──■──────────H──M
q1: ─H──│──────────H──M
q2: ─H──│──────■───H──M
a : ─X──H──────⊕───⊕───
Enter fullscreen mode Exit fullscreen mode

The X and H on the ancilla prepare |−⟩; each ⊕ is a CNOT; the three Hs and three measurements on the data qubits read the secret. The circuit has no knowledge of 101 beyond which wires carry a CNOT, and that is the point: the answer comes back all at once.

The code

The repository's demo builds the same circuit for every secret up to four bits and prints the most likely outcome. It is short, and it is the file the article quotes:

"""Demo 04: Bernstein-Vazirani, one query per bit of the secret.

Run: python3 chapters/chapter06/files/04_bv.py
"""

from algorithms import bernstein_vazirani, classical_queries_bernstein_vazirani, most_likely

print(f"{'n':>2s}{'secret':>8s}{'returned':>10s}{'P(returned)':>13s}{'classical queries':>18s}")
for n in (1, 2, 3, 4):
    for secret in (1, 3, 5):
        if secret >= (1 << n):
            continue
        distribution = bernstein_vazirani(secret, n)
        label, probability = most_likely(distribution)
        print(f"{n:2d}{format(secret, f'0{n}b'):>8s}{label:>10s}{probability:13.4f}"
              f"{classical_queries_bernstein_vazirani(secret, n):18d}")

print()
print("the returned string is the secret, and it comes back with probability one")
print("the classical program needs one query per bit: query 1, 2, 4, ... and read the answers")
Enter fullscreen mode Exit fullscreen mode

Run it locally

cd chapters/chapter06/files
python3 04_bv.py
Enter fullscreen mode Exit fullscreen mode
 n  secret  returned  P(returned) classical queries
 1       1         1       1.0000                 1
 2      01        01       1.0000                 2
 2      11        11       1.0000                 2
 3     001       001       1.0000                 3
 3     011       011       1.0000                 3
 3     101       101       1.0000                 3
 4    0001      0001       1.0000                 4
 4    0011      0011       1.0000                 4
 4    0101      0101       1.0000                 4

the returned string is the secret, and it comes back with probability one
the classical program needs one query per bit: query 1, 2, 4, ... and read the answers
Enter fullscreen mode Exit fullscreen mode

Every row returns the secret with probability 1.0000, and the last column is the classical cost: one query per bit. At four bits that is four calls against one circuit.

Run it on IBM's free quantum computer

Create an IBM Quantum account, copy the API key from the IAM page, and copy the CRN of the Open Plan instance. Both URLs are in the repository's README, in the live-runs section.

cp .env.example .env
Enter fullscreen mode Exit fullscreen mode

Fill QISKIT_IBM_TOKEN and QISKIT_IBM_INSTANCE. Then:

python live_scripts/check_providers.py
python live_scripts/chapter06/submit_bv.py
Enter fullscreen mode Exit fullscreen mode

The script submits one circuit at 1,024 shots and writes runs/chapter06/0011-bv-101-1024-ibm/result.json. The recorded job in the book used ibm_marrakesh, depth 9, and the secret 101. Reading it back:

cd chapters/chapter06/files
python3 05_hardware.py
Enter fullscreen mode Exit fullscreen mode
backend: ibm_marrakesh, depth 9, job dbu6v28vv3fc73c0t14g
secret submitted: 101
shots: 1024

outcome      count   frequency
101            965      0.9424
100             27      0.0264
001             25      0.0244
000              5      0.0049
111              2      0.0020

the secret came back 965 times out of 1024: 0.9424
correct: True

outcomes seen: 5 of the 8 possible
error rate on this run: 0.0576
Enter fullscreen mode Exit fullscreen mode

The device returns the secret 965 times out of 1,024 — 0.9424. The other 59 shots are readout errors and gate errors, not a wrong algorithm: the wrong outcomes are one bit away from 101, which is what a misread qubit looks like. Chapter 12 fits exactly this kind of error, and chapter 19 corrects it.

What the numbers mean

Three classical questions become one circuit. The circuit itself is not free — it uses four qubits, seven Hadamards, two CNOTs, and it ran at depth 9 — but the query count is the resource the algorithm improves, and it improves it from n to 1.

The 0.0576 error rate is not the algorithm failing. It is a 2026 device misreading about one shot in seventeen; the book's whole argument is that a result is a distribution, not a bit, and that the distance from the ideal is the number to report.

What this does not prove

It does not prove a speed advantage you can measure in seconds: at three bits the classical program is instantaneous, and the quantum job waits in a queue. It does not factor anything, and it does not survive without error correction at larger sizes.

What it does prove is the structure: a function, an oracle, a phase, a measurement, and a secret that arrives in one shot. That structure is the first four sections of chapter 6, and the same shape returns in Grover in chapter 7 and in Shor-lite in chapter 9.

Where to read more

  • Chapter 6 derives the circuit, the oracle and the promise, and runs the device job quoted above.
  • Chapter 11 is the interface used by submit_bv.py: one API over seven providers, with a replay that runs without an account.
  • Chapter 12 fits the readout and gate errors behind the 0.0576, and chapter 19 puts the correction in a pipeline.
  • The repository's README has the setup, the offline suite and every live command.

Repo: github.com/edgarmilvus/quantum-python
Ebook: Quantum Python
GitHub: @edgarmilvus

Top comments (0)