Create a circuit which runs some specified number of times, and manually set the step number my_steps. The results in the two-dimensional geometry will be displayed for combo = [0, 0, 0, 0, 0]. The oracle and diffusion matrices are defined below, and available by calling oracle_matrix(combo) and diffusion_matrix(). From the plots, confirm that applying the Grover operator rotates the state vector, and determine the optimal number of Grover steps for .

You should observe that, for , four steps are optimal. After that, more Grover steps rotate us away from the solution.

n_bits = 5
dev = qml.device("default.qubit", wires=n_bits)


def oracle_matrix(combo):
"""Return the oracle matrix for a secret combination.

Args:
combo (list[int]): A list of bits representing a secret combination.

Returns:
array[float]: The matrix representation of the oracle.
"""
index = np.ravel_multi_index(combo, [2] * len(combo)) # Index of solution
my_array = np.identity(2 ** len(combo)) # Create the identity matrix
my_array[index, index] = -1
return my_array


def diffusion_matrix():
"""Return the diffusion matrix.

Returns:
array[float]: The matrix representation of the diffusion operator.
"""
psi_piece = (1 / 2**n_bits) * np.ones(2**n_bits)
ident_piece = np.eye(2**n_bits)
return 2 * psi_piece - ident_piece


@qml.qnode(dev)
def grover_circuit(combo, num_steps):
"""Apply the Grover operator num_steps times to the uniform superposition
and return the state.

Args:

or to submit your code

To interact with codercises, please switch to a larger screen size.

Learning Objectives:

  • Describe and manipulate the geometry of Grover search.