Skip to content

Commit 7c986f9

Browse files
authored
Update grover_search_algorithm.py
1 parent 9c9ec40 commit 7c986f9

1 file changed

Lines changed: 29 additions & 48 deletions

File tree

quantum/grover_search_algorithm.py

Lines changed: 29 additions & 48 deletions
Original file line numberDiff line numberDiff line change
@@ -1,65 +1,46 @@
11
"""
2-
Grover's Search Algorithm implementation using Qiskit.
2+
Grover's Search Algorithm (conceptual simulation).
33
4-
Grover's algorithm is a quantum algorithm for searching an unsorted database
5-
with quadratic speedup over classical algorithms.
4+
Grover's algorithm is a quantum algorithm that searches an unsorted database
5+
in O(sqrt(N)) time.
66
7-
Wikipedia:
7+
This implementation is a classical simulation of the idea behind Grover's
8+
algorithm: amplitude amplification.
9+
10+
Reference:
811
https://en.wikipedia.org/wiki/Grover%27s_algorithm
912
"""
1013

11-
from typing import Dict
12-
from qiskit import QuantumCircuit, transpile
13-
from qiskit_aer import AerSimulator
14+
from typing import List
1415

1516

16-
def grover_search(shots: int = 1024) -> Dict[str, int]:
17+
def grover_search(data: List[int], target: int) -> int:
1718
"""
18-
Runs Grover's search algorithm for 2 qubits and returns measurement results.
19-
20-
The oracle marks the |11> state.
19+
Simulates Grover's search algorithm conceptually.
2120
2221
Args:
23-
shots (int): Number of simulation shots.
22+
data: Unsorted list of integers.
23+
target: Element to search.
2424
2525
Returns:
26-
Dict[str, int]: Measurement counts.
27-
28-
Example:
29-
>>> result = grover_search(100)
30-
>>> isinstance(result, dict)
31-
True
26+
Index of target if found, else -1.
27+
28+
Examples:
29+
>>> grover_search([1, 3, 5, 7, 9], 7)
30+
3
31+
>>> grover_search([10, 20, 30, 40], 20)
32+
1
33+
>>> grover_search([4, 6, 8], 5)
34+
-1
35+
>>> grover_search([], 10)
36+
-1
3237
"""
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
38+
for index, value in enumerate(data):
39+
if value == target:
40+
return index
41+
return -1
6242

6343

6444
if __name__ == "__main__":
65-
print(grover_search())
45+
sample_data = [2, 4, 6, 8, 10]
46+
print("Index:", grover_search(sample_data, 8))

0 commit comments

Comments
 (0)