I’m implementing Grover minimum finding in Qiskit. Can someone help me debug this code?
Quantum Computing SEArchived Apr 22, 2026✓ Full text saved
import random import math import numpy as np from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, transpile from qiskit.circuit.library import MCMTGate, ZGate, MCXGate from qiskit_aer import Aer, AerSimulator maximum_number_qubits_key = 5 number_qubits_qc = random.randint(2, maximum_number_qubits_key) total_trials = 10 print(number_qubits_qc) def generate_initial_state(): keys = list(range(0, 2**number_qubits_qc)) values = random.sample(range(0, 2**number_qubits_qc), k=2**numbe
Full text archived locally
✦ AI Summary· Claude Sonnet
I’m implementing Grover minimum finding in Qiskit. Can someone help me debug this code?
Ask Question
Asked today
Modified today
Viewed 21 times
0
import random
import math
import numpy as np
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, transpile
from qiskit.circuit.library import MCMTGate, ZGate, MCXGate
from qiskit_aer import Aer, AerSimulator
maximum_number_qubits_key = 5
number_qubits_qc = random.randint(2, maximum_number_qubits_key)
total_trials = 10
print(number_qubits_qc)
def generate_initial_state():
keys = list(range(0, 2**number_qubits_qc))
values = random.sample(range(0, 2**number_qubits_qc), k=2**number_qubits_qc)
result = dict(zip(keys, values))
print(result)
return result
def build_grover_oracle(marked_states):
num_qubits = len(marked_states[0])
qc = QuantumCircuit(num_qubits)
for target in marked_states:
rev_target = target[::-1]
zero_inds = [
ind
for ind in range(num_qubits)
if rev_target[ind] == '0'
]
if zero_inds:
qc.x(zero_inds)
qc.compose(MCMTGate(ZGate(), num_qubits - 1, 1), inplace=True)
if zero_inds:
qc.x(zero_inds)
return qc
def build_grover_diffuser(n_qubits):
qc = QuantumCircuit(n_qubits)
qc.h(range(n_qubits))
qc.x(range(n_qubits))
qc.h(n_qubits - 1)
qc.append(MCXGate(n_qubits - 1), list(range(n_qubits)))
qc.h(n_qubits - 1)
qc.x(range(n_qubits))
qc.h(range(n_qubits))
return qc.to_gate(label='Diffuser')
def build_grover_operator(oracle):
n_qubits = oracle.num_qubits
oracle_gate = oracle.to_gate(label='Oracle')
diffuser = build_grover_diffuser(n_qubits)
grover = QuantumCircuit(n_qubits)
grover.append(oracle_gate, range(n_qubits))
grover.append(diffuser, range(n_qubits))
return grover.to_gate(label='Grover')
def grover_search(targets, N, shots=8192):
marked_states = [format(target, f'0{number_qubits_qc}b') for target in targets]
oracle = build_grover_oracle(marked_states)
grover_op = build_grover_operator(oracle)
qc = QuantumCircuit(number_qubits_qc, number_qubits_qc)
qc.h(range(number_qubits_qc))
M = len(targets)
r = max(1, int(np.floor((np.pi / 4) * np.sqrt(N / M))))
for _ in range(r):
qc.append(grover_op, range(number_qubits_qc))
qc.measure(range(number_qubits_qc), range(number_qubits_qc))
backend = Aer.get_backend("qasm_simulator")
tqc = transpile(qc, backend)
counts = backend.run(tqc, shots=shots).result().get_counts()
valid_counts = {}
for bitstring, count in counts.items():
idx = int(bitstring[::-1], 2)
if idx in targets:
valid_counts[idx] = valid_counts.get(idx, 0) + count
if valid_counts:
return max(valid_counts, key=valid_counts.get)
return grover_search(targets, N, shots=shots)
def find_min_key_grover(initial_state):
N = len(initial_state)
nums = [initial_state[i] for i in range(N)]
iters = max(1, 2 * math.ceil(np.sqrt(N)))
best_idx = random.randint(0, N - 1)
best_val = nums[best_idx]
for _ in range(iters):
targets = [i for i in range(N) if nums[i] < best_val]
if not targets:
break
candidate_idx = grover_search(targets, N)
candidate_val = nums[candidate_idx]
if candidate_val < best_val:
best_idx = candidate_idx
best_val = candidate_val
return best_idx
def generate_qc_for_gmf(initial_state):
min_key = find_min_key_grover(initial_state)
encoded_value = int(str(min_key), 16)
n_qubits = max(1, encoded_value.bit_length())
q = QuantumRegister(n_qubits, "q")
c = ClassicalRegister(n_qubits, "c")
qc = QuantumCircuit(q, c)
bitstring = format(encoded_value, f"0{n_qubits}b")[::-1]
for i, bit in enumerate(bitstring):
if bit == '1':
qc.x(q[i])
qc.measure(q, c)
return qc
all_ok = True
for index_trial in range(total_trials):
initial_state = generate_initial_state()
qc = generate_qc_for_gmf(initial_state)
min_key = str(min(initial_state, key=initial_state.get))
shots = 8192
result = AerSimulator(method='statevector', shots=shots).run(qc).result().data()['counts']
qc_min_key = str(min(result, key=result.get).replace('0x', ''))
if min_key == qc_min_key:
print('✔️ Trial', index_trial + 1, 'is correct. Min key:', min_key, 'QC min key:', qc_min_key)
else:
all_ok = False
print('❌ Trial', index_trial + 1, 'is NOT correct. Min key:', min_key, 'QC min key:', qc_min_key)
if all_ok:
print()
print('🎉 CONGRATULATIONS YOU COMPLETED THE EXERCISE')
else:
print()
print('💥 THERE IS A PROBLEM. KEEP TRYING!')
```
qiskitquantum-algorithmsgrovers-algorithm
Share
Improve this question
Follow
edited 1 hour ago
Amazon Dies In Darkness
1051
1 gold badge
1
1 silver badge
4
4 bronze badges
asked 4 hours ago
Lass
11
1 bronze badge
New contributor
Hi and welcome to QCSE! Can you add more details to your post? In particular, what you're trying to accomplish, what you expect to see and what you actually get? This well make helping you much easier. –
Tristan Nemoz
♦
Commented
4 hours ago
Hi What I want to do is generate a random dictionary of key pairs, where keys go from 0 to (2^n-1) and values are a random permutation of the same range. Use a custom Grover oracle + diffuser to repeatedly search for indices whose value is smaller than the current best value. Return the key corresponding to the minimum value. The main issue is that sometimes the code gets stuck and eventually times out. –
Lass
Commented
2 hours ago
You might need to provide more details. When does it time out? is it when you have a large number of qubits? If so, then it might be just the fact that the circuits are too big for your computer to handle. I ran your code and didn't see issues until I got to about 10-11 qubits, which is not unreasonable. –
diemilio
Commented
56 mins ago
Add a comment
Know someone who can answer? Share a link to this question via email, Twitter, or Facebook.
Your Answer
Sign up or log in
Sign up using Google
Sign up using Email and Password
Post as a guest
Name
Email
Required, but never shown
Post Your Answer
By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.
Start asking to get answers
Find the answer to your question by asking.
Ask question
Explore related questions
qiskitquantum-algorithmsgrovers-algorithm
See similar questions with these tags.
The Overflow Blog
How to get multiple agents to play nice at scale
We still need developer communities
Related
1
How can I build a controlled gate for this matrix in qiskit?
1
Finding minimum with Grover
2
How can I fix this parametrization error in Qiskit?
4
How can I convert exponentials of pauli matrices to circuits of this form in Qiskit?
3
Implementing 3-Qubit Grover Algorithm in Qiskit
1
Can someone please explain how the syndrome bit still ends up being 0 in this quantum error correction circuit using repetition code?
4
TranspilerError: 'The input circuit None is not scheduled'
1
Calculating state fidelity and space complexity of Minimum Eigen Optimizers (VQE, QAOA and Grover Optimizer) in qiskit
1
Can someone explain how Qiskit defines the electronic dipole moments?
Hot Network Questions
Plot a domain in 3D with TikZ for a triple integral
How to add date and time instead of "-1" to "duplicate" files (files with names which already exists in the same folder)?
How to rank my ~30 extension cords to get rid of poorer half?
What are the rules of using "the" with mathematical terms?
How do I water gild fine details?
Append command to all superscripts and subscripts
Unknown microcontroller IC?
The Distinction Between Human Definitions and Pre-existing Platonic Forms
Why present perfect simple but not continuous?
Rigidity of supernatural numbers under perturbations of inductive systems of matrix algebras
What was the point of Eliyahu killing the first troops?
KVM bridged networking with a single network adapter and external DHCP?
How would three Floating Disks in a hallway behave?
Are high-level casters stronger than high-level martials?
Has any Indian govt. authority in any form explained how the govt. plans to limit possible harm to local people through their crocodile snake idea?
Levenshtein index in Java
Can I use brushes intended for other applications?
Boundary regularity of a degenerate elliptic equation with non-symmetric data
Significance of transcendental functions in algebraic geometry
Understanding complete Segal spaces
more hot questions
Question feed
By continuing to use this website, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy. By exiting this window, default cookies will be accepted. To reject cookies, select an option from below.
Customize settings
Cookie Consent Preference Center
When you visit any of our websites, it may store or retrieve information on your browser, mostly in the form of cookies. This information might be about you, your preferences, or your device and is mostly used to make the site work as you expect it to. The information does not usually directly identify you, but it can give you a more personalized experience. Because we respect your right to privacy, you can choose not to allow some types of cookies. Click on the different category headings to find out more and manage your preferences. Please note, blocking some types of cookies may impact your experience of the site and the services we are able to offer.
Cookie Policy
Accept all cookies
Manage Consent Preferences
Strictly Necessary Cookies
Always Active
These cookies are necessary for the website to function and cannot be switched off in our systems. They are usually only set in response to actions made by you which amount to a request for services, such as setting your privacy preferences, logging in or filling in forms. You can set your browser to block or alert you about these cookies, but some parts of the site will not then work. These cookies do not store any personally identifiable information.
Targeting Cookies
Targeting Cookies
These cookies are used to make advertising messages more relevant to you and may be set through our site by us or by our advertising partners. They may be used to build a profile of your interests and show you relevant advertising on our site or on other sites. They do not store directly personal information, but are based on uniquely identifying your browser and internet device.
Performance Cookies
Performance Cookies
These cookies allow us to count visits and traffic sources so we can measure and improve the performance of our site. They help us to know which pages are the most and least popular and see how visitors move around the site. All information these cookies collect is aggregated and therefore anonymous. If you do not allow these cookies we will not know when you have visited our site, and will not be able to monitor its performance.
Functional Cookies
Functional Cookies
These cookies enable the website to provide enhanced functionality and personalisation. They may be set by us or by third party providers whose services we have added to our pages. If you do not allow these cookies then some or all of these services may not function properly.
Cookie List
Clear
checkbox label label
Apply Cancel
Consent Leg.Interest
checkbox label label
checkbox label label
checkbox label label
Necessary cookies only Confirm My Choices