<jupyter_start><jupyter_text>Quantum Algorithms (Intro) in Qiskit (Deutsch's)A real algorithm, one of the first ever created, will be implemented in Qiskit.Start by some typical setup and definition of useful functions, which you are encouraged to look at.Then, head to the [exercises start](Exercises-Start-Here) to start coding!![Matrix Oracle](oracle.jpg)<jupyter_code>from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister
from qiskit import execute
# Choose the drawer you like best:
from qiskit.tools.visualization import matplotlib_circuit_drawer as draw
#from qiskit.tools.visualization import circuit_drawer as draw
from qiskit import IBMQ
IBMQ.load_account() # make sure you have setup your token locally to use this
%matplotlib inline<jupyter_output><empty_output><jupyter_text>Utils for visualizing experimental results<jupyter_code>import matplotlib.pyplot as plt

def show_results(D):
    # D is a dictionary with classical bits as keys and count as value
    # example: D = {'000': 497, '001': 527}
    plt.bar(range(len(D)), list(D.values()), align='center')
    plt.xticks(range(len(D)), list(D.keys()))
    plt.show()<jupyter_output><empty_output><jupyter_text>Utils for executing circuits<jupyter_code>from qiskit import Aer
# See a list of available local simulators
print("Aer backends: ", Aer.backends())
# see a list of available remote backends (these are freely given by IBM)
print("IBMQ Backends: ", IBMQ.backends())<jupyter_output><empty_output><jupyter_text>Execute locally<jupyter_code># execute circuit and either display a histogram of the results
def execute_locally(qc, draw_circuit=False, show_results=False):
    # Compile and run the Quantum circuit on a simulator backend
    backend_sim = Aer.get_backend('qasm_simulator')
    job_sim = execute(qc, backend_sim)
    result_sim = job_sim.result()
    result_counts = result_sim.get_counts(qc)
    
    if draw_circuit or show_results: # Print the results
        print("simulation: ", result_sim, result_counts)
    
    if draw_circuit: # draw the circuit
        draw(qc)
    elif show_results: # or show the results
        show_results(result_counts)
    return result_counts<jupyter_output><empty_output><jupyter_text>Execute remotely<jupyter_code>from qiskit.backends.ibmq import least_busy
import time
# Compile and run on a real device backend
def execute_remotely(qc, draw_circuit=False, show_results=False):
    if draw_circuit: # draw the circuit
        draw(qc)
    try:
        # select least busy available device and execute.
        least_busy_device = least_busy(IBMQ.backends(simulator=False))
        print("Running on current least busy device: ", least_busy_device)

        # running the job
        job_exp = execute(qc, backend=least_busy_device, shots=1024, max_credits=10)

        lapse, interval = 0, 10
        while job_exp.status().name != 'DONE':
            print('Status @ {} seconds'.format(interval * lapse))
            print(job_exp.status())
            time.sleep(interval)
            lapse += 1
        print(job_exp.status())
        exp_result = job_exp.result()
        result_counts = exp_result.get_counts(qc)

        # Show the results
        print("experiment: ", exp_result, result_counts)
        if show_results: # show the results
            show_results(result_counts)
        return result_counts
    except:
        print("All devices are currently unavailable.")
        return {}<jupyter_output><empty_output><jupyter_text>Building the circuit<jupyter_code>def new_circuit(size):
    # Create a Quantum Register with size qubits
    qr = QuantumRegister(size)

    # Create a Classical Register with size bits
    cr = ClassicalRegister(size)

    # Create a Quantum Circuit acting on the qr and cr register
    return qr, cr, QuantumCircuit(qr, cr)<jupyter_output><empty_output><jupyter_text>Our secret Oracles<jupyter_code>ERROR_MESSAGE = "Looks like your Deutsch has a bug"
def quantum_oracle_1(qr, cr, circuit):
    pass
def quantum_oracle_2(qr, cr, circuit):
    circuit.cx(qr[0], qr[1])
def quantum_oracle_3(qr, cr, circuit):
    circuit.cx(qr[0], qr[1])
    circuit.cx(qr[1], qr[0])
    circuit.cx(qr[0], qr[1])
def quantum_oracle_4(qr, cr, circuit):
    circuit.z(qr[1])
    circuit.cx(qr[0], qr[1])<jupyter_output><empty_output><jupyter_text>---Exercises Start HereMake sure you ran all the above cells in order, as the following exercises use functions defined and imported above.  Understanding Deutsch's AlgorithmIf you need go back to the slides, or check other sources, but it is quite important that you get a good grasp on why the algorithm works. Hopefully, these exercises will help achieve that. Firstly, let us look at our goal circuit:![deutsch's circuit](deutsch_algorithm.png)The XOR symbol is meaningful but not realistic, that is actually a measurement, as you may have guessed!!  Your TaskI have defined 4 mysterious **oracles:** `quantum_oracle_1` through `quantum_oracle_4`. (For 2 qubits)You need to find, without looking at their implementation, whether they are **balanced** or **constant** by designing a quantum circuit, just follow the next steps: **TASK:** Create a new circuit with 2 qubits using `new_circuit` (very useful to reconstruct your circuit in Jupyter) **TASK:** Make the necessary modifications on the input qubits (before the Hadamards) **TASK:** Implement the Hadamards on both qubits **TASK:** Call our oracle 1: `quantum_oracle_1(CLASSICAL_REGISTER, QUANTUM_REGISTER, YOUR_CURRENT_CIRCUIT)` **TASK:** Implement the Hadamard on qubit 0 **TASK:** Perform a measurement **TASK:** check the result using `execute_locally` test both `True` and `False` for the `draw_circuit` and `show_results` (4 different combinations) option and save the results!(This function has been updated and now returns a dictionary like: `{'00': 524, '11': 500}`) **TASK:** Now implement a decision mechanism that will print either `"CONSTANT"` or `"BALANCED"`, according to what type of oracle `quantum_oracle_1` is! **TASK:** Take your code and isolate it into a function `get_deutsch_verdict` that has a dictionary with the execution results and returns either `"CONSTANT"` or `"BALANCED"`, accordingly.<jupyter_code>def get_deutsch_verdict(res):
    return "CONSTANT" or "BALANCED"<jupyter_output><empty_output><jupyter_text>**TASK:** Call your function with your previous results and print its return value:<jupyter_code>print(get_deutsch_verdict(results))<jupyter_output><empty_output><jupyter_text>Isolate your code into a function**TASK:** Create a function called `deutsch` which receives a `black_box` as an argument and returns either `"CONSTANT"` or `"BALANCED"` (a stub has already been created for you)<jupyter_code>def deutsch(black_box):
    # ...
    black_box(circuit)
    #...
    return "CONSTANT" or "BALANCED"<jupyter_output><empty_output><jupyter_text>**TASK:** Call `deutsch(quantum_oracle_1)` and a `'CONSTANT'` value should appear: **TASK:** Now that you are confident of your implementation, call it for the following cases to make sure it is! If you have a bug an `AssertionError` will appear Test case 1: `quantum_oracle_1`<jupyter_code>assert deutsch(quantum_oracle_1) == 'CONSTANT', ERROR_MESSAGE<jupyter_output><empty_output><jupyter_text>Test case 2: `quantum_oracle_2`<jupyter_code>assert deutsch(quantum_oracle_2) == 'BALANCED', "Looks like your Deutsch has a bug"<jupyter_output><empty_output><jupyter_text>Test case 3: `quantum_oracle_3`<jupyter_code>assert deutsch(quantum_oracle_3) == 'BALANCED', "Looks like your Deutsch has a bug"<jupyter_output><empty_output><jupyter_text>Test case 4: `quantum_oracle_4`<jupyter_code>assert deutsch(quantum_oracle_4) == 'CONSTANT', "Looks like your Deutsch has a bug"<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.09507858799278536, 'fraction_numerical': 0.009018294254058232, 'mean_word_length': 5.180732484076433, 'pattern_counts': {'":': 0, '<': 57, '<?xml version=': 0, '>': 57, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '14', 'dir': 'jupyter-structured-clean-dedup', 'id': '275301', 'license': 'Apache-2.0', 'n_tokens_mistral': 2493, 'n_tokens_neox': 2334, 'n_words': 774, 'path': 'awards/teach_me_quantum_2018/TeachMeQ/Week_5-Quantum_Algorithms/exercises/w5_01.ipynb', 'repo_name': 'Qiskit/qiskit-edu-tutorials', 'size': '7762'}