1
$\begingroup$

I have a simple implementation of Grover's algorithm. As depicted in the results below, the oracle function marks the state |111>. How can I change the Oracle function to mark |010>?

    import cirq
    from cirq import H, Z, X
    
    qq = cirq.LineQubit.range(3)
    circuit = cirq.Circuit()
    circuit.append(H.on_each(*qq))
    
    def oracle():
        yield Z(qq[2]).controlled_by(*(qq[0:2]))
    
    def grover_diffusion():
        yield H.on_each(*qq)
        yield X.on_each(*qq)
        yield Z(qq[2]).controlled_by(*(qq[0:2]))
        yield X.on_each(*qq)
        yield H.on_each(*qq)
    
    for i in range(2):
        circuit.append(oracle())
        circuit.append(grover_diffusion())
    
    circuit.append(cirq.measure(*qq, key='result'))
        
    # determine the statistics of the measurements
    s = cirq.Simulator() 
    trials_number = 1000
    samples = s.run(circuit, repetitions=trials_number)
    
    def bitstring(bits):
        return "".join(str(int(b)) for b in bits)
    
    counts = samples.histogram(key = "result", fold_func = bitstring)
    
    print("Measurement output: ", counts)
    # Output is something like 
    # Measurement output:  Counter({'111': 953, '001': 10, '000': 9, '110': 9, '010': 9, '101': 4, '100': 4, '011': 2})
```
$\endgroup$

1 Answer 1

0
$\begingroup$
def oracle():
    yield X(qq[0])
    yield X(qq[2])
    yield Z(qq[2]).controlled_by(*(qq[0:2]))
    yield X(qq[0])
    yield X(qq[2])

For a general Grover oracle to find a specific 3-qubit computational basis state, flanking the CCZ with $X$ gates on the qubits that need to be zero will work. A CCZ only causes the phase to be reversed if all 3 qubits are 1 (for the CCZ gate there's no actual difference between control and target unlike CCX, so it doesn't matter which one of the three that the Z gate is applied to). By doing the $X$ on a qubit before that causes the phase reverse to occur if that input is 0 instead, and the $X$s after the CCZ return the relevant qubits back to 0 while keeping the phase reversal if it occurred.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.