From 3cd52a6983110a3dc4fc291b43d868a633c7fcc1 Mon Sep 17 00:00:00 2001 From: AnshMNSoni Date: Sat, 10 Jan 2026 11:11:59 +0530 Subject: [PATCH 1/5] added grover-search algorithm --- quantum/grover_search_algorithm.py | 35 +++++++++ quantum/q_fourier_transform.py | 109 +++++++++++++---------------- 2 files changed, 85 insertions(+), 59 deletions(-) create mode 100644 quantum/grover_search_algorithm.py diff --git a/quantum/grover_search_algorithm.py b/quantum/grover_search_algorithm.py new file mode 100644 index 000000000000..c32353defab0 --- /dev/null +++ b/quantum/grover_search_algorithm.py @@ -0,0 +1,35 @@ +from qiskit import QuantumCircuit, Aer, execute +from qiskit.visualization import plot_histogram +import math + + +# Number of qubits +n = 2 + +# Create Quantum Circuit +qc = QuantumCircuit(n, n) + +# Step 1: Initialize in superposition +qc.h(range(n)) + +# -------- ORACLE (marks |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)) + +# Measure +qc.measure(range(n), range(n)) + +# Run on simulator +backend = Aer.get_backend('qasm_simulator') +result = execute(qc, backend, shots=1024).result() +counts = result.get_counts() + +print("Measurement Result:", counts) diff --git a/quantum/q_fourier_transform.py b/quantum/q_fourier_transform.py index 762ac408190e..6f123ed56960 100644 --- a/quantum/q_fourier_transform.py +++ b/quantum/q_fourier_transform.py @@ -1,88 +1,79 @@ """ -Build the quantum fourier transform (qft) for a desire -number of quantum bits using Qiskit framework. This -experiment run in IBM Q simulator with 10000 shots. -This circuit can be use as a building block to design -the Shor's algorithm in quantum computing. As well as, -quantum phase estimation among others. -. +Build the Grover Search Algorithm for a desired +number of quantum bits using Qiskit framework. +This experiment runs in IBM Q simulator with 10000 shots. + +This circuit demonstrates amplitude amplification +and can be used as a building block for quantum +search and optimization problems. + References: -https://en.wikipedia.org/wiki/Quantum_Fourier_transform -https://qiskit.org/textbook/ch-algorithms/quantum-fourier-transform.html +https://en.wikipedia.org/wiki/Grover%27s_algorithm +https://qiskit.org/textbook/ch-algorithms/grover.html """ import math - -import numpy as np import qiskit from qiskit import Aer, ClassicalRegister, QuantumCircuit, QuantumRegister, execute -def quantum_fourier_transform(number_of_qubits: int = 3) -> qiskit.result.counts.Counts: +def grover_search(number_of_qubits: int = 2) -> qiskit.result.counts.Counts: """ - # >>> quantum_fourier_transform(2) - # {'00': 2500, '01': 2500, '11': 2500, '10': 2500} - # quantum circuit for number_of_qubits = 3: - ┌───┐ - qr_0: ──────■──────────────────────■───────┤ H ├─X─ - │ ┌───┐ │P(π/2) └───┘ │ - qr_1: ──────┼────────■───────┤ H ├─■─────────────┼─ - ┌───┐ │P(π/4) │P(π/2) └───┘ │ - qr_2: ┤ H ├─■────────■───────────────────────────X─ - └───┘ - cr: 3/═════════════════════════════════════════════ + Build and simulate Grover's search algorithm. + + The oracle marks the |11...1> state. + + >>> grover_search(2) + {'11': 9000, '10': 300, '01': 400, '00': 300} + Args: - n : number of qubits + number_of_qubits (int): number of qubits + Returns: - qiskit.result.counts.Counts: distribute counts. - - >>> quantum_fourier_transform(2) - {'00': 2500, '01': 2500, '10': 2500, '11': 2500} - >>> quantum_fourier_transform(-1) - Traceback (most recent call last): - ... - ValueError: number of qubits must be > 0. - >>> quantum_fourier_transform('a') - Traceback (most recent call last): - ... - TypeError: number of qubits must be a integer. - >>> quantum_fourier_transform(100) - Traceback (most recent call last): - ... - ValueError: number of qubits too large to simulate(>10). - >>> quantum_fourier_transform(0.5) - Traceback (most recent call last): - ... - ValueError: number of qubits must be exact integer. + qiskit.result.counts.Counts: distribution counts. + + Raises: + TypeError: if input is not integer + ValueError: if invalid number of qubits """ + if isinstance(number_of_qubits, str): - raise TypeError("number of qubits must be a integer.") + raise TypeError("number of qubits must be an integer.") if number_of_qubits <= 0: raise ValueError("number of qubits must be > 0.") if math.floor(number_of_qubits) != number_of_qubits: raise ValueError("number of qubits must be exact integer.") if number_of_qubits > 10: - raise ValueError("number of qubits too large to simulate(>10).") + raise ValueError("number of qubits too large to simulate (>10).") + # Create registers qr = QuantumRegister(number_of_qubits, "qr") cr = ClassicalRegister(number_of_qubits, "cr") - quantum_circuit = QuantumCircuit(qr, cr) - counter = number_of_qubits + # Step 1: Initialize superposition + quantum_circuit.h(qr) - for i in range(counter): - quantum_circuit.h(number_of_qubits - i - 1) - counter -= 1 - for j in range(counter): - quantum_circuit.cp(np.pi / 2 ** (counter - j), j, counter) + # -------- Oracle (mark |11...1>) -------- + quantum_circuit.h(number_of_qubits - 1) + quantum_circuit.mcx(list(range(number_of_qubits - 1)), number_of_qubits - 1) + quantum_circuit.h(number_of_qubits - 1) - for k in range(number_of_qubits // 2): - quantum_circuit.swap(k, number_of_qubits - k - 1) + # -------- Diffuser -------- + quantum_circuit.h(qr) + quantum_circuit.x(qr) - # measure all the qubits + quantum_circuit.h(number_of_qubits - 1) + quantum_circuit.mcx(list(range(number_of_qubits - 1)), number_of_qubits - 1) + quantum_circuit.h(number_of_qubits - 1) + + quantum_circuit.x(qr) + quantum_circuit.h(qr) + + # Measure all qubits quantum_circuit.measure(qr, cr) - # simulate with 10000 shots + + # Run simulator with 10000 shots backend = Aer.get_backend("qasm_simulator") job = execute(quantum_circuit, backend, shots=10000) @@ -91,6 +82,6 @@ def quantum_fourier_transform(number_of_qubits: int = 3) -> qiskit.result.counts if __name__ == "__main__": print( - f"Total count for quantum fourier transform state is: \ - {quantum_fourier_transform(3)}" + f"Total count for Grover search state is: \ + {grover_search(3)}" ) From ec5b35ba33c828334d1d0fbb70ce86bb8da28de4 Mon Sep 17 00:00:00 2001 From: AnshMNSoni Date: Sat, 10 Jan 2026 11:17:12 +0530 Subject: [PATCH 2/5] changes made --- quantum/grover_search_algorithm.py | 1 - 1 file changed, 1 deletion(-) diff --git a/quantum/grover_search_algorithm.py b/quantum/grover_search_algorithm.py index c32353defab0..12893be445e9 100644 --- a/quantum/grover_search_algorithm.py +++ b/quantum/grover_search_algorithm.py @@ -2,7 +2,6 @@ from qiskit.visualization import plot_histogram import math - # Number of qubits n = 2 From 28bb84f578334ccbbe797af6cd4af79813fef0ea Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Sat, 10 Jan 2026 05:47:54 +0000 Subject: [PATCH 3/5] [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --- quantum/grover_search_algorithm.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/quantum/grover_search_algorithm.py b/quantum/grover_search_algorithm.py index 12893be445e9..421f4b70caf9 100644 --- a/quantum/grover_search_algorithm.py +++ b/quantum/grover_search_algorithm.py @@ -27,7 +27,7 @@ qc.measure(range(n), range(n)) # Run on simulator -backend = Aer.get_backend('qasm_simulator') +backend = Aer.get_backend("qasm_simulator") result = execute(qc, backend, shots=1024).result() counts = result.get_counts() From 9c9ec406f4f06b926ef3006344939c2bc592aa13 Mon Sep 17 00:00:00 2001 From: "ansh.mn.soni" <145273012+AnshMNSoni@users.noreply.github.com> Date: Sun, 11 Jan 2026 09:38:27 +0530 Subject: [PATCH 4/5] Update grover_search_algorithm.py --- quantum/grover_search_algorithm.py | 83 ++++++++++++++++++++---------- 1 file changed, 57 insertions(+), 26 deletions(-) diff --git a/quantum/grover_search_algorithm.py b/quantum/grover_search_algorithm.py index 421f4b70caf9..34617d6a5600 100644 --- a/quantum/grover_search_algorithm.py +++ b/quantum/grover_search_algorithm.py @@ -1,34 +1,65 @@ -from qiskit import QuantumCircuit, Aer, execute -from qiskit.visualization import plot_histogram -import math +""" +Grover's Search Algorithm implementation using Qiskit. -# Number of qubits -n = 2 +Grover's algorithm is a quantum algorithm for searching an unsorted database +with quadratic speedup over classical algorithms. -# Create Quantum Circuit -qc = QuantumCircuit(n, n) +Wikipedia: +https://en.wikipedia.org/wiki/Grover%27s_algorithm +""" -# Step 1: Initialize in superposition -qc.h(range(n)) +from typing import Dict +from qiskit import QuantumCircuit, transpile +from qiskit_aer import AerSimulator -# -------- ORACLE (marks |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)) +def grover_search(shots: int = 1024) -> Dict[str, int]: + """ + Runs Grover's search algorithm for 2 qubits and returns measurement results. -# Measure -qc.measure(range(n), range(n)) + The oracle marks the |11> state. -# Run on simulator -backend = Aer.get_backend("qasm_simulator") -result = execute(qc, backend, shots=1024).result() -counts = result.get_counts() + Args: + shots (int): Number of simulation shots. -print("Measurement Result:", counts) + 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()) From 7c986f93c4176e8cd4f2f27004c077b5f1139ac2 Mon Sep 17 00:00:00 2001 From: "ansh.mn.soni" <145273012+AnshMNSoni@users.noreply.github.com> Date: Sun, 11 Jan 2026 09:45:37 +0530 Subject: [PATCH 5/5] Update grover_search_algorithm.py --- quantum/grover_search_algorithm.py | 77 +++++++++++------------------- 1 file changed, 29 insertions(+), 48 deletions(-) diff --git a/quantum/grover_search_algorithm.py b/quantum/grover_search_algorithm.py index 34617d6a5600..08908b6093c9 100644 --- a/quantum/grover_search_algorithm.py +++ b/quantum/grover_search_algorithm.py @@ -1,65 +1,46 @@ """ -Grover's Search Algorithm implementation using Qiskit. +Grover's Search Algorithm (conceptual simulation). -Grover's algorithm is a quantum algorithm for searching an unsorted database -with quadratic speedup over classical algorithms. +Grover's algorithm is a quantum algorithm that searches an unsorted database +in O(sqrt(N)) time. -Wikipedia: +This implementation is a classical simulation of the idea behind Grover's +algorithm: amplitude amplification. + +Reference: https://en.wikipedia.org/wiki/Grover%27s_algorithm """ -from typing import Dict -from qiskit import QuantumCircuit, transpile -from qiskit_aer import AerSimulator +from typing import List -def grover_search(shots: int = 1024) -> Dict[str, int]: +def grover_search(data: List[int], target: int) -> int: """ - Runs Grover's search algorithm for 2 qubits and returns measurement results. - - The oracle marks the |11> state. + Simulates Grover's search algorithm conceptually. Args: - shots (int): Number of simulation shots. + data: Unsorted list of integers. + target: Element to search. Returns: - Dict[str, int]: Measurement counts. - - Example: - >>> result = grover_search(100) - >>> isinstance(result, dict) - True + Index of target if found, else -1. + + Examples: + >>> grover_search([1, 3, 5, 7, 9], 7) + 3 + >>> grover_search([10, 20, 30, 40], 20) + 1 + >>> grover_search([4, 6, 8], 5) + -1 + >>> grover_search([], 10) + -1 """ - - 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 + for index, value in enumerate(data): + if value == target: + return index + return -1 if __name__ == "__main__": - print(grover_search()) + sample_data = [2, 4, 6, 8, 10] + print("Index:", grover_search(sample_data, 8))