|
| 1 | +""" |
| 2 | +Grover's Search Algorithm implementation using Qiskit. |
| 3 | +
|
| 4 | +Grover's algorithm is a quantum algorithm for searching an unsorted database |
| 5 | +with quadratic speedup over classical algorithms. |
| 6 | +
|
| 7 | +Wikipedia: |
| 8 | +https://en.wikipedia.org/wiki/Grover%27s_algorithm |
| 9 | +""" |
| 10 | + |
| 11 | +from typing import Dict |
1 | 12 | from qiskit import QuantumCircuit, transpile |
2 | 13 | from qiskit_aer import AerSimulator |
3 | 14 |
|
4 | | -# Number of qubits |
5 | | -n = 2 |
6 | 15 |
|
7 | | -# Create Quantum Circuit |
8 | | -qc = QuantumCircuit(n, n) |
| 16 | +def grover_search(shots: int = 1024) -> Dict[str, int]: |
| 17 | + """ |
| 18 | + Runs Grover's search algorithm for 2 qubits and returns measurement results. |
| 19 | +
|
| 20 | + The oracle marks the |11> state. |
| 21 | +
|
| 22 | + Args: |
| 23 | + shots (int): Number of simulation shots. |
| 24 | +
|
| 25 | + Returns: |
| 26 | + Dict[str, int]: Measurement counts. |
| 27 | +
|
| 28 | + Example: |
| 29 | + >>> result = grover_search(100) |
| 30 | + >>> isinstance(result, dict) |
| 31 | + True |
| 32 | + """ |
| 33 | + |
| 34 | + n = 2 |
| 35 | + qc = QuantumCircuit(n, n) |
| 36 | + |
| 37 | + # Initialize superposition |
| 38 | + qc.h(range(n)) |
| 39 | + |
| 40 | + # Oracle marking |11> |
| 41 | + qc.cz(0, 1) |
9 | 42 |
|
10 | | -# Step 1: Initialize in superposition |
11 | | -qc.h(range(n)) |
| 43 | + # Diffuser |
| 44 | + qc.h(range(n)) |
| 45 | + qc.x(range(n)) |
| 46 | + qc.h(1) |
| 47 | + qc.cx(0, 1) |
| 48 | + qc.h(1) |
| 49 | + qc.x(range(n)) |
| 50 | + qc.h(range(n)) |
12 | 51 |
|
13 | | -# -------- ORACLE (marks |11>) -------- |
14 | | -qc.cz(0, 1) |
| 52 | + # Measurement |
| 53 | + qc.measure(range(n), range(n)) |
15 | 54 |
|
16 | | -# -------- DIFFUSER -------- |
17 | | -qc.h(range(n)) |
18 | | -qc.x(range(n)) |
19 | | -qc.h(1) |
20 | | -qc.cx(0, 1) |
21 | | -qc.h(1) |
22 | | -qc.x(range(n)) |
23 | | -qc.h(range(n)) |
| 55 | + # Run on simulator |
| 56 | + backend = AerSimulator() |
| 57 | + compiled = transpile(qc, backend) |
| 58 | + result = backend.run(compiled, shots=shots).result() |
| 59 | + counts = result.get_counts() |
24 | 60 |
|
25 | | -# Measure |
26 | | -qc.measure(range(n), range(n)) |
| 61 | + return counts |
27 | 62 |
|
28 | | -# Run on simulator |
29 | | -backend = AerSimulator() |
30 | | -compiled_circuit = transpile(qc, backend) |
31 | | -result = backend.run(compiled_circuit, shots=1024).result() |
32 | | -counts = result.get_counts() |
33 | 63 |
|
34 | | -print("Measurement Result:", counts) |
| 64 | +if __name__ == "__main__": |
| 65 | + print(grover_search()) |
0 commit comments