Skip to content

Commit 035a5be

Browse files
committed
modify the format of the file
1 parent 3556a5c commit 035a5be

File tree

1 file changed

+55
-24
lines changed

1 file changed

+55
-24
lines changed

quantum/grover_search_algorithm.py

Lines changed: 55 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -1,34 +1,65 @@
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
112
from qiskit import QuantumCircuit, transpile
213
from qiskit_aer import AerSimulator
314

4-
# Number of qubits
5-
n = 2
615

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)
942

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))
1251

13-
# -------- ORACLE (marks |11>) --------
14-
qc.cz(0, 1)
52+
# Measurement
53+
qc.measure(range(n), range(n))
1554

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()
2460

25-
# Measure
26-
qc.measure(range(n), range(n))
61+
return counts
2762

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()
3363

34-
print("Measurement Result:", counts)
64+
if __name__ == "__main__":
65+
print(grover_search())

0 commit comments

Comments
 (0)