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