|
1 | | -from qiskit import QuantumCircuit, Aer, execute |
2 | | -from qiskit.visualization import plot_histogram |
3 | | -import math |
| 1 | +""" |
| 2 | +Grover's Search Algorithm implementation using Qiskit. |
4 | 3 |
|
5 | | -# Number of qubits |
6 | | -n = 2 |
| 4 | +Grover's algorithm is a quantum algorithm for searching an unsorted database |
| 5 | +with quadratic speedup over classical algorithms. |
7 | 6 |
|
8 | | -# Create Quantum Circuit |
9 | | -qc = QuantumCircuit(n, n) |
| 7 | +Wikipedia: |
| 8 | +https://en.wikipedia.org/wiki/Grover%27s_algorithm |
| 9 | +""" |
10 | 10 |
|
11 | | -# Step 1: Initialize in superposition |
12 | | -qc.h(range(n)) |
| 11 | +from typing import Dict |
| 12 | +from qiskit import QuantumCircuit, transpile |
| 13 | +from qiskit_aer import AerSimulator |
13 | 14 |
|
14 | | -# -------- ORACLE (marks |11>) -------- |
15 | | -qc.cz(0, 1) |
16 | 15 |
|
17 | | -# -------- DIFFUSER -------- |
18 | | -qc.h(range(n)) |
19 | | -qc.x(range(n)) |
20 | | -qc.h(1) |
21 | | -qc.cx(0, 1) |
22 | | -qc.h(1) |
23 | | -qc.x(range(n)) |
24 | | -qc.h(range(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. |
25 | 19 |
|
26 | | -# Measure |
27 | | -qc.measure(range(n), range(n)) |
| 20 | + The oracle marks the |11> state. |
28 | 21 |
|
29 | | -# Run on simulator |
30 | | -backend = Aer.get_backend("qasm_simulator") |
31 | | -result = execute(qc, backend, shots=1024).result() |
32 | | -counts = result.get_counts() |
| 22 | + Args: |
| 23 | + shots (int): Number of simulation shots. |
33 | 24 |
|
34 | | -print("Measurement Result:", counts) |
| 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) |
| 42 | + |
| 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)) |
| 51 | + |
| 52 | + # Measurement |
| 53 | + qc.measure(range(n), range(n)) |
| 54 | + |
| 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() |
| 60 | + |
| 61 | + return counts |
| 62 | + |
| 63 | + |
| 64 | +if __name__ == "__main__": |
| 65 | + print(grover_search()) |
0 commit comments