Codercise I.14.2 - Quantum Multiplexer

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

# State of first 2 qubits
state = [0, 1]

@qml.qnode(device=dev)
def apply_control_sequence(state):
    # Set up initial state of the first two qubits
    if state[0] == 1:
        qml.PauliX(wires=0)
    if state[1] == 1:
        qml.PauliX(wires=1)

    # Set up initial state of the third qubit - use |->
    # so we can see the effect on the output
    qml.PauliX(wires=2)
    qml.Hadamard(wires=2)

    # IMPLEMENT THE MULTIPLEXER
    # IF STATE OF FIRST TWO QUBITS IS 01, APPLY X TO THIRD QUBIT
    qml.MultiControlledX(control_wires = [0,1], wires = 2, control_values = "01")
    
    # IF STATE OF FIRST TWO QUBITS IS 10, APPLY Z TO THIRD QUBIT
    qml.ControlledQubitUnitary(Z, control_wires = [0,1], wires = 2, control_values = "10")

    
    # IF STATE OF FIRST TWO QUBITS IS 11, APPLY Y TO THIRD QUBIT
    qml.ControlledQubitUnitary(Y, control_wires = [0,1], wires = 2, control_values = "11")
    
    return qml.state()
    return qml.state()


print(apply_control_sequence(state))


###

Why do I get an error saying name “Z” is not defined.

Since PennyLane doesn’t have an operator named ‘Z’, you can use ‘qml.PauliZ(any int)’ or ‘qml.Z(any int)’ instead.

2 Likes

Welcome to the forum @jasonmao0702 !

Great answer @Mayu :star2:

Just one small clarification here: PennyLane does have an operator named ‘Z’, which is why ‘qml.Z(any int)’ indeed works. The issue here was that you were calling ‘Z’ (instead of ‘qml.Z’), which Python interpreted as a new (undefined) variable.

Keep enjoying the Codebook and thanks Mayu for providing an answer!

1 Like