Qiskit/qiskit_humaneval_hard huggingface dataset:
Write a function that takes the bitstring 's' as the input and builds a Quantum Circuit such that the output when xor-ed with the input 's' is same as the 's'. When building the quantum circuit make sure the classical registers is named 'c'.
You must implement this using a function named `simons_algorithm` with the following arguments: s.

Solution:
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister

def simons_algorithm(s):
    n = len(s)
    s = s[::-1]
    q_reg1 = QuantumRegister(n,"reg1")
    q_reg2 = QuantumRegister(n,"reg2")
    c_reg = ClassicalRegister(n, "c")
    circuit = QuantumCircuit (q_reg1, q_reg2, c_reg)
    circuit.h(q_reg1)
    circuit.barrier()
    circuit.cx(q_reg1, q_reg2)
    if "1" in s:
        i = s.find("1")
        for j in range(n):
            if s[j] == "1":
                circuit.cx(i, q_reg2[j])
        circuit.barrier()
        circuit.h(q_reg1)
    circuit.measure(q_reg1, c_reg)
    return circuit


Test:
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
def check(candidate):
    from qiskit_aer import AerSimulator
    from qiskit_ibm_runtime import Sampler
    result = candidate('1010')
    assert isinstance(result, QuantumCircuit)
    assert result.num_qubits == 8
    def dpm2(vec1, vec2):
        return sum(int(a) * int(b) for a, b in zip(vec1, vec2)) % 2
    backend = AerSimulator()
    sampler = Sampler(mode=backend)
    job = sampler.run([result]).result()
    data = job[0].data
    counts= data.c.get_counts()
    for key in counts:
        assert dpm2(key, "1010") == 0

check(simons_algorithm)
Design a Quantum Fourier Transform circuit for n qubits using basic Quantum gates.
You must implement this using a function named `QFT` with the following arguments: n.

Solution:
from qiskit import QuantumCircuit
from numpy import pi

def QFT(n):
    circuit = QuantumCircuit(n)
    def swap_registers(circuit, n):
        for qubit in range(n//2):
            circuit.swap(qubit, n-qubit-1)
        return circuit
    def qft_rotations(circuit, n):
        """Performs qft on the first n qubits in circuit (without swaps)"""
        if n == 0:
            return circuit
        n -= 1
        circuit.h(n)
        for qubit in range(n):
            circuit.cp(pi/2**(n-qubit), qubit, n)
        qft_rotations(circuit, n)
    
    qft_rotations(circuit, n)
    swap_registers(circuit, n)
    return circuit


Test:
from qiskit import QuantumCircuit
from numpy import pi
def check(candidate):
    from qiskit.circuit.library import QFT as QiskitQFT
    from qiskit.quantum_info.operators import Operator
    result = candidate(3)
    assert isinstance(result, QuantumCircuit)
    assert result.num_qubits == 3
    for gate in result.data:
        op = gate.operation
        assert op.num_qubits <= 2 or op.name == 'barrier'
    solution = QiskitQFT(3)
    assert Operator(result).equiv(Operator(solution))

check(QFT)
Generate a Quantum Circuit for a W state and measure it.
You must implement this using a function named `w_state` with no arguments.

Solution:
from qiskit import QuantumCircuit
from numpy import arccos, sqrt

def w_state():
    circuit = QuantumCircuit(3)
    circuit.ry(2*arccos(1/sqrt(3)), 0)
    circuit.ch(0,1)
    circuit.cx(1,2)
    circuit.cx(0,1)
    circuit.x(0)
    circuit.measure_all()
    return circuit


Test:
from qiskit import QuantumCircuit
from numpy import arccos, sqrt
def check(candidate):
    from qiskit_aer import AerSimulator
    from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager
    from qiskit_ibm_runtime import Sampler
    result = candidate()
    assert isinstance(result, QuantumCircuit)
    assert result.num_qubits == 3
    backend = AerSimulator()
    sampler = Sampler(mode=backend)
    pass_manager = generate_preset_pass_manager(optimization_level=1, backend=backend)
    isa_circuit = pass_manager.run(result)
    job = sampler.run([isa_circuit]).result()
    counts= job[0].data.meas.get_counts()
    assert counts.keys() == {'001', '010' , '100'}
    assert counts['001'] >= 300 and counts['001'] <= 400
    assert counts['010'] >= 300 and counts['010'] <= 400
    assert counts['100'] >= 300 and counts['100'] <= 400
    assert counts['001'] + counts['010'] + counts['100'] == 1024

check(w_state)
Design a CHSH circuit that takes bits of Alice and Bob as input and return the Quantum Circuit after measuring.
You must implement this using a function named `chsh_circuit` with the following arguments: alice, bob.

Solution:
from qiskit import QuantumCircuit
from numpy import pi

def chsh_circuit(alice, bob):
    qc = QuantumCircuit(2,  2)
    qc.h(0)
    qc.cx(0, 1)
    qc.barrier()
    if alice == 0:
        qc.ry(0, 0)
    else:
        qc.ry(-pi / 2, 0)
    qc.measure(0, 0)
    if bob == 0:
        qc.ry(-pi / 4, 1)
    else:
        qc.ry(pi / 4, 1)
    qc.measure(1, 1)
    return qc


Test:
from qiskit import QuantumCircuit
from numpy import pi
def check(candidate):
    result = candidate(0,1)
    assert isinstance(result, QuantumCircuit)
    assert result.num_qubits == 2
    assert result.width() == 4
    assert result.depth() == 4
    assert set({'ry': 2, 'measure': 2, 'h': 1, 'cx': 1}.items()).issubset(set(result.count_ops().items()))

check(chsh_circuit)
Design a Zeno Elitzur Vaidman Bomb Tester circuit which takes the boolean if the bomb is live and outputs the percentage of successful live bomb predictions, dud bomb predictions and bombs that detonated. Use 25 cycles to increase the efficiency of the circuit.
You must implement this using a function named `zeno_elitzur_vaidman_bomb_tester` with the following arguments: bomb_live.

Solution:
from qiskit import QuantumCircuit
from qiskit_aer import AerSimulator
from qiskit_ibm_runtime import Sampler
from numpy import pi

def zeno_elitzur_vaidman_bomb_tester(bomb_live):
    live_predictions = dud_predictions = detonations = 0
    shots = 1024
    cycles = 25
    e = pi/cycles
    measurements = cycles + 1 if bomb_live else 1
    circuit = QuantumCircuit(1, measurements)
    for i in range(cycles):
        circuit.ry(e, 0)
        if bomb_live:
            circuit.measure(0, i)
    circuit.measure(0, measurements - 1)
    backend = AerSimulator()
    sampler = Sampler(mode=backend)
    job = sampler.run([circuit],shots=shots).result()
    counts= job[0].data.c.get_counts()
    if bomb_live:
        for key, value in counts.items():
            if key[0] == '1':
                detonations += value
            elif '1' in key[1:]:
                dud_predictions += value
            else:
                live_predictions += value
    else:
        live_predictions = counts['0'] if '0' in counts else 0
        dud_predictions = counts['1']
        detonations = 0
    return (live_predictions/shots, dud_predictions/shots, detonations/shots)


Test:
from qiskit import QuantumCircuit
from qiskit_aer import AerSimulator
from qiskit_ibm_runtime import Sampler
from numpy import pi
import numpy as np
def check(candidate):
    # Check output structure
    result_live = candidate(True)
    result_dud = candidate(False)
    assert isinstance(result_live, tuple) and len(result_live) == 3, "Output format incorrect"
    assert isinstance(result_dud, tuple) and len(result_dud) == 3, "Output format incorrect"

    # Live bomb case (probabilities should sum to ~1)
    assert 0.85 <= result_live[0] <= 1.0, "Live bomb predictions should be high"
    assert 0.0 <= result_live[1] <= 0.05, "Dud predictions should be minimal"
    assert 0.0 <= result_live[2] <= 0.15, "Detonations should be low"
    # Dud bomb case
    assert np.isclose(result_dud, (0.0, 1.0, 0.0), atol=0.01).all(), "Dud bomb should always return (0.0, 1.0, 0.0)"
    # Consistency check (running multiple times should yield similar results)
    results = [candidate(True) for _ in range(5)]
    means = np.mean(results, axis=0)
    assert 0.85 <= means[0] <= 1.0, "Average live prediction should be high"
    assert 0.0 <= means[1] <= 0.05, "Average dud prediction should be minimal"
    assert 0.0 <= means[2] <= 0.15, "Average detonation rate should be low"
    print("All tests passed successfully!")

check(zeno_elitzur_vaidman_bomb_tester)
Build a Quantum Circuit composed by the gates H in Quantum register 0, Controlled-S gate in quantum register 0 1, H gate in quantum register 1 and Controlled-S dagger gate in quantum register 1 0.
You must implement this using a function named `create_quantum_circuit_based_h0_cs01_h1_csdg10` with no arguments.

Solution:
from qiskit import QuantumCircuit

def create_quantum_circuit_based_h0_cs01_h1_csdg10():
    qc = QuantumCircuit(2)
    qc.h(0)
    qc.cs(0,1)
    qc.h(1)
    qc.csdg(1,0)
    return qc


Test:
from qiskit import QuantumCircuit
def check(candidate):
    result = candidate()
    assert isinstance(result, QuantumCircuit)
    assert result.num_qubits == 2
    assert result.depth() == 4
    assert dict(result.count_ops()) == {'h': 2, 'cs': 1, 'csdg': 1}

check(create_quantum_circuit_based_h0_cs01_h1_csdg10)
Build a Quantum Circuit composed by the gates H in Quantum register 0, Controlled-SWAP gate, also known as the Fredkin gate in quantum register 0 1 2, H gate in quantum register 1 and Controlled-S dagger gate in quantum register 1 0.
You must implement this using a function named `create_quantum_circuit_based_h0_cswap012_h1_csdg10` with no arguments.

Solution:
from qiskit import QuantumCircuit

def create_quantum_circuit_based_h0_cswap012_h1_csdg10():
    qc = QuantumCircuit(3)
    qc.h(0)
    qc.cswap(0,1,2)
    qc.h(1)
    qc.csdg(1,0)
    return qc


Test:
from qiskit import QuantumCircuit
def check(candidate):
    result = candidate()
    assert isinstance(result, QuantumCircuit)
    assert result.num_qubits == 3
    assert result.depth() == 4
    assert dict(result.count_ops()) == {"h": 2, "cswap": 1, "csdg": 1}

check(create_quantum_circuit_based_h0_cswap012_h1_csdg10)
Build a Quantum Circuit composed by the gates H in Quantum register 0, Controlled-√X gate in quantum register 0 1, and H gate in quantum register 1.
You must implement this using a function named `create_quantum_circuit_based_h0_csx01_h1` with no arguments.

Solution:
from qiskit import QuantumCircuit

def create_quantum_circuit_based_h0_csx01_h1():
    qc = QuantumCircuit(3)
    qc.h(0)
    qc.csx(0,1)
    qc.h(1)
    return qc


Test:
from qiskit import QuantumCircuit
def check(candidate):
    result = candidate()
    assert isinstance(result, QuantumCircuit)
    assert result.num_qubits == 3
    assert result.depth() == 3
    assert dict(result.count_ops()) == {"h": 2, "csx": 1}

check(create_quantum_circuit_based_h0_csx01_h1)
Apply `gate` to qubits with indices `qubits`, conditioned on all `condition_clbits` being 1.
You must implement this using a function named `gate_if_clbits` with the following arguments: circuit, gate, qubits, condition_clbits.

Solution:
import contextlib
from qiskit import QuantumCircuit
from qiskit.circuit import Gate

def gate_if_clbits(circuit, gate, qubits, condition_clbits):
    with contextlib.ExitStack() as stack:
        for index in condition_clbits:
            stack.enter_context(circuit.if_test((index, 1)))
        circuit.append(gate, qubits)


Test:
import contextlib
from qiskit import QuantumCircuit
from qiskit.circuit import Gate
def check(candidate):
    from qiskit.circuit.library import CXGate
    from qiskit_aer import AerSimulator
    from qiskit_ibm_runtime import Sampler
    qc = QuantumCircuit(2, 3)
    qc.x(0)
    candidate(qc, CXGate(), [0, 1], [0, 2])
    qc.measure_all()
    sampler = Sampler(mode=AerSimulator())
    result = sampler.run([qc]).result()[0].data.meas.get_counts()
    assert result.get("01") == 1024

    qc = QuantumCircuit(2, 3)
    qc.x([0, 1])
    qc.measure([0, 1], [0, 2])
    qc.x(1)
    candidate(qc, CXGate(), [0, 1], [0, 2])
    qc.measure_all()

    result = sampler.run([qc]).result()[0].data.meas.get_counts()
    assert result.get("11") == 1024

check(gate_if_clbits)
Add an X-basis measurement on qubit at index `qubit`, storing the result to classical bit `clbit`.
You must implement this using a function named `x_measurement` with the following arguments: circuit, qubit, clbit.

Solution:
from qiskit import QuantumCircuit

def x_measurement(circuit, qubit, clbit):
    circuit.h(qubit)
    circuit.measure(qubit, clbit)


Test:
from qiskit import QuantumCircuit
def check(candidate):
    from qiskit.primitives import StatevectorSampler
    qc = QuantumCircuit(3, 2)
    qc.x(1)
    qc.h(1)
    candidate(qc, 1, 0)

    result = StatevectorSampler().run([qc]).result()[0].data.c.get_counts()
    assert result.get('01') == 1024

check(x_measurement)
Split `circuit` at each barrier operation. Do not include barriers in the output circuits.
You must implement this using a function named `split_circuit_at_barriers` with the following arguments: circuit.

Solution:
from qiskit import QuantumCircuit
from qiskit.circuit.library import Barrier

def split_circuit_at_barriers(circuit):
    output = []
    new_circuit = circuit.copy_empty_like()
    for inst in circuit.data:
        if isinstance(inst.operation, Barrier):
            output.append(new_circuit)
            new_circuit = circuit.copy_empty_like()
            continue
        new_circuit.data.append(inst)
    output.append(new_circuit)
    return output


Test:
from qiskit import QuantumCircuit
from qiskit.circuit.library import Barrier
def check(candidate):
    qc = QuantumCircuit(3)
    qc.x(0)
    qc.barrier()
    qc.cx(0, 1)
    qc.h([0, 1])
    qc.z(1)
    qc.barrier()
    qc.barrier()
    qc.tdg(0)

    circuits = candidate(qc)
    assert len(circuits) == 4
    for circuit, expected_length in zip(circuits, [1, 4, 0, 1]):
        assert len(circuit.data) == expected_length

check(split_circuit_at_barriers)
Given a QuantumCircuit, sample it once and convert the measurement result to a list of bools, where the 0th bool is the result of the 0th classical bit.
You must implement this using a function named `circuit_to_bools` with the following arguments: circuit.

Solution:
from qiskit import QuantumCircuit
from qiskit.primitives import StatevectorSampler

def circuit_to_bools(circuit):
    result = StatevectorSampler().run([circuit], shots=1).result()[0].data.meas.get_counts()
    measurement_int = int(list(result.keys())[0], 2)
    output = []
    for bit_index in range(circuit.num_clbits):
        # Use bit-masking to get bits from `int`
        bit = bool(2 ** (bit_index) & measurement_int)
        output.append(bit)
    return output


Test:
from qiskit import QuantumCircuit
from qiskit.primitives import StatevectorSampler
def check(candidate):
    # 101
    qc = QuantumCircuit(3)
    qc.x([0, 2])
    qc.measure_all()
    assert candidate(qc) == [True, False, True]

    # 00011
    qc = QuantumCircuit(5)
    qc.x([3, 4])
    qc.measure_all()
    assert candidate(qc) == [False] * 3 + [True] * 2

    # 111011111
    qc = QuantumCircuit(9)
    qc.x(range(9))
    qc.x(3)
    qc.measure_all()
    assert candidate(qc) == [True] * 3 + [False] + [True] * 5

check(circuit_to_bools)
Return a transpiler pass that replaces all non-controlled Z-gates with H-X-H-gate sequences.
You must implement this using a function named `create_hxh_pass` with no arguments.

Solution:
from qiskit import QuantumRegister
from qiskit.transpiler.basepasses import TransformationPass
from qiskit.dagcircuit import DAGCircuit
from qiskit.circuit.library import ZGate, HGate, XGate

def create_hxh_pass():
    class HXHPass(TransformationPass):
        def run(
            self,
            dag: DAGCircuit,
        ) -> DAGCircuit:
            for node in dag.op_nodes():
                if not isinstance(node.op, ZGate):
                    continue
                # Create HXH gate sequence
                hxh_dag = DAGCircuit()
                register = QuantumRegister(1)
                hxh_dag.add_qreg(register)

                hxh_dag.apply_operation_back(HGate(), [register[0]])
                hxh_dag.apply_operation_back(XGate(), [register[0]])
                hxh_dag.apply_operation_back(HGate(), [register[0]])

                dag.substitute_node_with_dag(node, hxh_dag)

            return dag

    return HXHPass()


Test:
from qiskit import QuantumRegister
from qiskit.transpiler.basepasses import TransformationPass
from qiskit.dagcircuit import DAGCircuit
from qiskit.circuit.library import ZGate, HGate, XGate
def check(candidate):
    from qiskit.transpiler import PassManager
    from qiskit import QuantumCircuit
    hxh_pass = candidate()
    # Be lenient and accept both class and instance of class
    if not isinstance(hxh_pass, TransformationPass):
        hxh_pass = hxh_pass()
    assert isinstance(hxh_pass, TransformationPass)
    passmanager = PassManager(hxh_pass)
    qc = QuantumCircuit(1)
    qc.x(0)
    qc.z(0)
    result = passmanager.run(qc)
    result_op_strings = list(
        map(lambda circuit_inst: circuit_inst.operation.name, result.data)
    )
    assert result_op_strings == ["x", "h", "x", "h"]
    qc = QuantumCircuit(3)
    qc.h(1)
    qc.z(1)
    qc.cz(0, 1)
    qc.cx(1, 2)
    result = passmanager.run(qc)
    result_op_strings = list(
        map(lambda circuit_inst: circuit_inst.operation.name, result.data)
    )
    assert result_op_strings == ["h", "h", "x", "h", "cz", "cx"]

check(create_hxh_pass)
Given a distribution as a dictionary of the form { measurement: probability }, return a quantum circuit that produces that distribution.
You must implement this using a function named `circuit_from_probability_dist` with the following arguments: probability_dist.

Solution:
import math
from qiskit import QuantumCircuit

def circuit_from_probability_dist(probability_dist):
    num_qubits = math.ceil(math.log2(max(probability_dist.keys()) + 1)) or 1
    amplitudes = []
    for basis_state in range(2**num_qubits):
        prob = probability_dist.get(basis_state, 0)
        amplitudes.append(math.sqrt(prob))

    qc = QuantumCircuit(num_qubits)
    qc.prepare_state(amplitudes, range(num_qubits))
    return qc


Test:
import math
from qiskit import QuantumCircuit
def check(candidate):
    from qiskit.quantum_info import Statevector
    def _check(input_dist):
        circuit = candidate(input_dist)
        # allow circuits with or without final measurements
        circuit.remove_final_measurements()
        probability_dist = Statevector(circuit).probabilities()
        for basis_state, target_probability in input_dist.items():
            assert math.isclose(
                target_probability, probability_dist[basis_state], abs_tol=0.05
            )

    for input_dist in [
        {0: 1},
        {0: 0.1, 1: 0.1, 2: 0.7, 3: 0.1},
        {0: 0.5, 3: 0.5},
        {1: 0.5, 2: 0.5},
    ]:
        _check(input_dist)

check(circuit_from_probability_dist)
Return an inverse quantum Fourier transform circuit without the swap gates.
You must implement this using a function named `qft_no_swaps` with the following arguments: num_qubits.

Solution:
from qiskit import QuantumCircuit
from qiskit.circuit.library import QFT

def qft_no_swaps(num_qubits):
    qft = QFT(num_qubits=num_qubits, do_swaps=False, inverse=True)
    return qft


Test:
from qiskit import QuantumCircuit
from qiskit.circuit.library import QFT
def check(candidate):
    from qiskit.quantum_info import Operator
    for num_qubits in [1, 3, 8]:
        qft = QFT(num_qubits=num_qubits, do_swaps=False, inverse=True)
        response = candidate(num_qubits)
        assert Operator(qft) == Operator(response)

check(qft_no_swaps)
Return the total number of instructions in the circuit.
You must implement this using a function named `count_instructions` with the following arguments: circuit.

Solution:
from qiskit import QuantumCircuit

def count_instructions(circuit):
    return len(circuit.data)


Test:
from qiskit import QuantumCircuit
def check(candidate):
    qc = QuantumCircuit(4)
    qc.x(0)
    assert candidate(qc) == 1

    qc.cx(0, [1, 2])
    assert candidate(qc) == 3

    qc.measure_all()
    assert candidate(qc) == 8

check(count_instructions)
Return the total number of unitary gates in the circuit.
You must implement this using a function named `count_gates` with the following arguments: circuit.

Solution:
from qiskit import QuantumCircuit
from qiskit.circuit import Gate

def count_gates(circuit):
    count = 0
    for inst in circuit.data:
        if isinstance(inst.operation, Gate):
            count += 1
    return count


Test:
from qiskit import QuantumCircuit
from qiskit.circuit import Gate
def check(candidate):
    qc = QuantumCircuit(4)
    qc.reset(0)
    qc.tdg(0)
    assert candidate(qc) == 1

    qc.cx(0, [1, 2])
    assert candidate(qc) == 3

    qc.measure_all()
    assert candidate(qc) == 3

check(count_gates)
Generate a QASM 2 string representing a Phi plus Bell state quantum circuit. Then, convert this QASM 2 string into a Quantum Circuit object and return the resulting circuit.
You must implement this using a function named `convert_qasm_string_to_quantum_circuit` with no arguments.

Solution:
from qiskit import QuantumCircuit

def convert_qasm_string_to_quantum_circuit():
    qasm_string="""OPENQASM 2.0;
    include "qelib1.inc";
    qreg q[2];
    creg c[2];
    h q[0];
    cx q[0],q[1];"""
    qc = QuantumCircuit.from_qasm_str(qasm_string)
    return qc


Test:
from qiskit import QuantumCircuit
def check(candidate):
    from qiskit.quantum_info import Statevector
    from math import sqrt
    data = candidate()
    bell_state = (Statevector.from_label("11") + Statevector.from_label("00"))/sqrt(2)
    assert Statevector.from_instruction(data) == bell_state

check(convert_qasm_string_to_quantum_circuit)
Create a file containing the binary serialization of a Phi plus Bell state quantum circuit and write it as 'bell.qpy' in binary mode.
You must implement this using a function named `create_binary_serialization` with no arguments.

Solution:
from qiskit import QuantumCircuit
from qiskit import qpy

def create_binary_serialization():
    qc = QuantumCircuit(2, name='Bell', metadata={'test': True})
    qc.h(0)
    qc.cx(0, 1)
    with open('bell.qpy', 'wb') as fd:
        qpy.dump(qc, fd)


Test:
from qiskit import QuantumCircuit
from qiskit import qpy
def check(candidate):
    from qiskit.quantum_info import Statevector
    from math import sqrt
    candidate()
    with open('bell.qpy', 'rb') as fd:
        data = qpy.load(fd)[0]
    bell_state = (Statevector.from_label("11") + Statevector.from_label("00"))/sqrt(2)
    assert Statevector.from_instruction(data) == bell_state

check(create_binary_serialization)
Construct a Phi plus Bell state quantum circuit, compute its Density Matrix and Concurrence, and return these results in a tuple in the same order.
You must implement this using a function named `calculate_bell_state_properties` with no arguments.

Solution:
from qiskit import QuantumCircuit
from qiskit.quantum_info import DensityMatrix, concurrence

def calculate_bell_state_properties():
    qc = QuantumCircuit(2, name='Bell')
    qc.h(0)
    qc.cx(0, 1)
    rho = DensityMatrix.from_instruction(qc)
    concur = concurrence(rho)
    return rho, concur


Test:
from qiskit import QuantumCircuit
from qiskit.quantum_info import DensityMatrix, concurrence
def check(candidate):
    import numpy as np
    DensityMatrix, concurrence = candidate()
    assert round(concurrence,1) == 1
    expected_rho = np.array([[0.5, 0, 0, 0.5], [0, 0, 0, 0], [0, 0, 0, 0], [0.5, 0, 0, 0.5]])
    np.testing.assert_array_almost_equal(DensityMatrix, expected_rho, decimal=5, err_msg='Density matrix does not match the expected Bell state density matrix')

check(calculate_bell_state_properties)