from projectq import MainEngine from projectq.ops import H, CNOT, Measure # Initialize the MainEngine eng = MainEngine() # Create two qubits qubit1 = eng.allocate_qubit() qubit2 = eng.allocate_qubit() # Apply the Hadamard gate to the first qubit H | qubit1 # Apply the CNOT gate between the first and second qubits CNOT | (qubit1, qubit2) # Measure the two qubits Measure | qubit1 Measure | qubit2 # Flush the MainEngine eng.flush() # Print the result of the measurements print("Results: Qubit 1 = {}, Qubit 2 = {}".format(int(qubit1), int(qubit2)))
from projectq import MainEngine from projectq.ops import All, X, H, Measure from projectq.meta import Loop, Compute, Uncompute # Initialize the MainEngine eng = MainEngine() # Allocate four qubits and apply the X gate to initialize to the state |1111> qubits = eng.allocate_qureg(4) All(X) | qubits # Define the oracle function which zeroes out the marked state |1010> def oracle(qubits): with Compute(eng): X | qubits[0] X | qubits[2] with Control(eng, qubits[:-1]): X | qubits[-1] with Uncompute(eng): X | qubits[0] X | qubits[2] # Apply the Grover diffusion operator def grover(oracle): n = len(oracle) with Loop(eng, int(n**0.5)): oracle(qubits) with Compute(eng): All(H) | qubits All(X) | qubits with Control(eng, qubits[:-1]): X | qubits[-1] with Uncompute(eng): All(X) | qubits All(H) | qubits # Implement Grover's search algorithm grover(oracle) # Measure the four qubits All(Measure) | qubits # Flush the MainEngine eng.flush() # Print the result of the measurements print("Results: Qubits = {}".format([int(q) for q in qubits]))Package library: ProjectQ is available as a package on PyPI (Python Package Index). The MainEngine class is part of the projectq.cengines module.