Qiskit/qiskit_humaneval huggingface dataset:
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit_aer import AerSimulator
from qiskit_ibm_runtime import Sampler
def and_gate(a: int, b: int)->dict:
    """ Given two 3-bit integers a and b, design a quantum circuit that acts as a classical AND gate. Simulate the circuit on using Qiskit Sampler with the Aer simulator as backend and return the counts of the result.
    """
    qr_a = QuantumRegister(3, "qr_a")
    qr_b = QuantumRegister(3, "qr_b")
    ancillary = QuantumRegister(3, "ancillary")
    measure = ClassicalRegister(3, "measure")
    circuit = QuantumCircuit(qr_a, qr_b, ancillary, measure)
    a = format(a, '03b')
    b = format(b, '03b')
    for i in range(3):
        if a[2-i] == '1':
            circuit.x(qr_a[i])
        if b[2-i] == '1':
            circuit.x(qr_b[i])
    for i in range(3):
        circuit.ccx(qr_a[i], qr_b[i], ancillary[i])
    circuit.measure(ancillary, measure)
    backend = AerSimulator()
    sampler = Sampler(mode=backend)
    result = sampler.run([circuit]).result()
    return result[0].data.measure.get_counts()


def check(candidate):
    assert candidate(1, 2) == {'000': 1024}
    assert candidate(6, 7) == {'110': 1024}
    assert candidate(3, 5) == {'001': 1024}
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit_aer import AerSimulator
from qiskit_ibm_runtime import Sampler
def or_gate(a: int, b: int)->dict:
    """ Given two 3-bit integers a and b, design a quantum circuit that acts as a classical OR gate. Simulate the circuit using Qiskit Sampler with the Aer simulator as backend and return the counts of the result.
    """
    qr_a = QuantumRegister(3, "qr_a")
    qr_b = QuantumRegister(3, "qr_b")
    ancillary = QuantumRegister(3, "ancillary")
    measure = ClassicalRegister(3, "measure")
    circuit = QuantumCircuit(qr_a, qr_b, ancillary, measure)
    a = format(a, '03b')
    b = format(b, '03b')
    for i in range(3):
        if a[2-i] == '0':
            circuit.x(qr_a[i])
        if b[2-i] == '0':
            circuit.x(qr_b[i])
    for i in range(3):
        circuit.ccx(qr_a[i], qr_b[i], ancillary[i])
    circuit.x(ancillary)
    circuit.measure(ancillary, measure)
    backend = AerSimulator()
    sampler = Sampler(mode=backend)
    result = sampler.run([circuit]).result()
    return result[0].data.measure.get_counts()


def check(candidate):
    assert candidate(1, 2) == {"011": 1024}
    assert candidate(6, 7) == {"111": 1024}
    assert candidate(0, 5) == {"101": 1024}
from qiskit import QuantumCircuit
from qiskit_aer import AerSimulator
from qiskit_ibm_runtime import Sampler
def not_gate(a: int)->dict:
    """ Given two 8-bit integers, design a quantum circuit that acts as a classical NOT gate. Simulate the circuit Qiskit Sampler with the Aer simulator as backend and return the counts of the result.
    """
    circuit = QuantumCircuit(8)
    a = format(a, "08b")
    for i in range(8):
        if a[7-i] == "0":
            circuit.x(i)
    circuit.measure_all()
    backend = AerSimulator()
    sampler = Sampler(mode=backend)
    result = sampler.run([circuit]).result()
    return result[0].data.meas.get_counts()


def check(candidate):
    assert candidate(0) == {"11111111": 1024}
    assert candidate(238) == {"00010001": 1024}
    assert candidate(59) == {"11000100": 1024}
from qiskit import QuantumCircuit
def create_swap_gate()->QuantumCircuit:
    """ Design a SWAP gate using only CX gates.
    """
    circuit = QuantumCircuit(2)
    circuit.cx(0,1)
    circuit.cx(1,0)
    circuit.cx(0,1)
    return circuit


def check(candidate):
    from qiskit.circuit.library import SwapGate
    from qiskit.quantum_info.operators import Operator
    result = candidate()
    assert isinstance(result, QuantumCircuit)
    assert result.num_qubits == 2
    assert dict(result.count_ops()) == {'cx': 3}
    assert Operator(result) == Operator(SwapGate())
from qiskit import QuantumCircuit
from numpy import pi
def create_ch_gate()->QuantumCircuit:
    """ Design a CH gate using CX and RY gates.
    """
    circuit = QuantumCircuit(2)
    circuit.ry(pi/4, 1)
    circuit.cx(0,1)
    circuit.ry(-pi/4, 1)
    return circuit


def check(candidate):
    from qiskit.circuit.library import CHGate
    from qiskit.quantum_info.operators import Operator
    result = candidate()
    assert isinstance(result, QuantumCircuit)
    assert result.num_qubits == 2
    assert dict(result.count_ops()) == {'ry': 2, 'cx': 1}
    assert Operator(result) == Operator(CHGate())
from qiskit import QuantumCircuit
def create_cz_gate()->QuantumCircuit:
    """ Design a CZ gate using only H and CNOT gates and return the quantum circuit.
    """
    circuit = QuantumCircuit(2)
    circuit.h(1)
    circuit.cx(0,1)
    circuit.h(1)
    return circuit


def check(candidate):
    from qiskit.circuit.library import CZGate
    from qiskit.quantum_info.operators import Operator
    result = candidate()
    assert isinstance(result, QuantumCircuit)
    assert result.num_qubits == 2
    assert dict(result.count_ops()) == {'h': 2, 'cx': 1}
    assert Operator(result) == Operator(CZGate())
from qiskit import QuantumCircuit
def create_cy_gate()->QuantumCircuit:
    """ Design a CY gate using only one CX gate and any other single qubit gates.
    """
    circuit = QuantumCircuit(2)
    circuit.sdg(1)
    circuit.cx(0,1)
    circuit.s(1)
    return circuit


def check(candidate):
    from qiskit.circuit.library import CYGate
    from qiskit.quantum_info.operators import Operator
    result = candidate()
    assert isinstance(result, QuantumCircuit)
    assert result.num_qubits == 2
    assert 'cx' in result.count_ops()
    for gate in result.data:
        op = gate.operation
        assert op.num_qubits == 1 or op.name == 'cx' or op.name == 'barrier'
    assert Operator(result) == Operator(CYGate())
from qiskit import QuantumRegister, QuantumCircuit, ClassicalRegister
def create_quantum_circuit_with_one_qubit_and_measure():
    """ Build a Quantum Circuit by first creating one Quantum Register and one Classical Register and then perform measurement on it.
    """
    q = QuantumRegister(1, 'q')
    c = ClassicalRegister(1, 'c')
    qc = QuantumCircuit(q, c)
    qc.measure(q, c)
    return qc


def check(candidate):
    result = candidate()
    assert result.depth() == 1
    assert result.width() == 2
    assert dict(result.count_ops()) == {'measure': 1}
from qiskit import QuantumCircuit
def bb84_senders_circuit(state: [int], basis: [int])->QuantumCircuit:
    """ Construct a BB84 protocol circuit for the sender, inputting both the states and the measured bases.
    """
    num_qubits = len(state)
    circuit = QuantumCircuit(num_qubits)
    for i in range(len(basis)):
        if state[i] == 1:
            circuit.x(i)
        if basis[i] == 1:
            circuit.h(i)
    return circuit


def check(candidate):
    from qiskit.quantum_info import Statevector
    from numpy.random import randint, seed
    seed(12345)
    qubits = 5
    state = randint(2, size=qubits)
    basis = randint(2, size=qubits)
    result = candidate(state, basis)
    assert isinstance(result, QuantumCircuit)
    assert result.num_qubits == qubits
    assert result.count_ops()['h'] == sum(basis)
    assert result.count_ops()['x'] == sum(state)
    solution = QuantumCircuit(5)
    solution.x([1,2,3])
    solution.h([0,3])
    assert Statevector.from_instruction(result).equiv(Statevector.from_instruction(solution))
from qiskit import QuantumCircuit
from qiskit_aer import AerSimulator
from qiskit_ibm_runtime import Sampler
from numpy.random import randint
def bb84_circuit_generate_key(senders_basis: [int], circuit: QuantumCircuit)->str:
    """ Write a function to generate the key from the circuit and the sender's basis generated by the sender using BB84 protocol.
    """
    n = len(senders_basis)
    receivers_basis = randint(2, size=n)
    for i in range(n):
        if receivers_basis[i]:
            circuit.h(i)
    circuit.measure_all()
    backend = AerSimulator()
    sampler = Sampler(mode=backend)
    result = sampler.run([circuit.reverse_bits()], shots=1).result()
    count= result[0].data.meas.get_counts()
    key = next(iter(count))
    encryption_key = ''
    for i in range(n):
        if senders_basis[i] == receivers_basis[i]:
             encryption_key += str(key[i])
    return encryption_key


def check(candidate):
    from numpy.random import seed
    seed(12345)
    basis = [1, 0, 0, 1, 1]
    circuit = QuantumCircuit(5)
    circuit.x([3, 4])
    circuit.h([0, 3, 4])
    result = candidate(basis, circuit)
    assert result == "1"
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
def simons_algorithm(s: str)->QuantumCircuit:
    """ 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'.
    """
    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


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
from qiskit import QuantumCircuit
from numpy import pi
def QFT(n: int)->QuantumCircuit:
    """ Design a Quantum Fourier Transform circuit for n qubits using basic Quantum gates.
    """
    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


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))
from qiskit import QuantumCircuit
from numpy import arccos, sqrt
def w_state()->QuantumCircuit:
    """ Generate a Quantum Circuit for a W state and measure it.
    """
    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


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
from qiskit import QuantumCircuit
from numpy import pi
def chsh_circuit(alice: int, bob: int)->QuantumCircuit:
    """ Design a CHSH circuit that takes bits of Alice and Bob as input and return the Quantum Circuit after measuring.
    """
    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


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()))
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: bool)->(float, float, float):
    """ 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.
    """
    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)


def check(candidate):
    result = candidate(True)
    assert isinstance(result, tuple) and len(result) == 3
    assert result[0] >= 0.85 and result[1] <= 0.03 and result[2] <= 0.12
    assert candidate(False) == (0.0, 1.0, 0.0)
from qiskit import QuantumCircuit
def create_quantum_circuit_based_h0_cs01_h1_csdg10():
    """ 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.
    """
    qc = QuantumCircuit(2)
    qc.h(0)
    qc.cs(0,1)
    qc.h(1)
    qc.csdg(1,0)
    return qc


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}
from qiskit import QuantumCircuit
def create_quantum_circuit_based_h0_cswap012_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.
    """
    qc = QuantumCircuit(3)
    qc.h(0)
    qc.cswap(0,1,2)
    qc.h(1)
    qc.csdg(1,0)
    return qc


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}
from qiskit import QuantumCircuit
def create_quantum_circuit_based_h0_csx01_h1():
    """ 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.
    """
    qc = QuantumCircuit(3)
    qc.h(0)
    qc.csx(0,1)
    qc.h(1)
    return qc


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}
import contextlib
from qiskit import QuantumCircuit
from qiskit.circuit import Gate
def gate_if_clbits(
    circuit: QuantumCircuit, gate: Gate, qubits: list[int], condition_clbits: list[int]
) -> None:
    """ Apply `gate` to qubits with indices `qubits`, conditioned on all `condition_clbits` being 1.
    """
    with contextlib.ExitStack() as stack:
        for index in condition_clbits:
            stack.enter_context(circuit.if_test((index, 1)))
        circuit.append(gate, qubits)


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
from qiskit import QuantumCircuit
def x_measurement(circuit: QuantumCircuit, qubit: int, clbit: int) -> None:
    """ Add an X-basis measurement on qubit at index `qubit`, storing the result to classical bit `clbit`.
    """
    circuit.h(qubit)
    circuit.measure(qubit, clbit)


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
from qiskit import QuantumCircuit
from qiskit.circuit.library import Barrier
def split_circuit_at_barriers(circuit: QuantumCircuit) -> list[QuantumCircuit]:
    """ Split `circuit` at each barrier operation. Do not include barriers in the output circuits.
    """
    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


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
from qiskit import QuantumCircuit
from qiskit.primitives import StatevectorSampler
def circuit_to_bools(circuit: QuantumCircuit) -> list[bool]:
    """ 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.
    """
    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


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
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() -> TransformationPass:
    """ Return a transpiler pass that replaces all non-controlled Z-gates with H-X-H-gate sequences.
    """
    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()


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"]
import math
from qiskit import QuantumCircuit
def circuit_from_probability_dist(probability_dist: dict[int, float]) -> QuantumCircuit:
    """ Given a distribution as a dictionary of the form { measurement: probability }, return a quantum circuit that produces that distribution.
    """
    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


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)
from qiskit import QuantumCircuit
from qiskit.circuit.library import QFT


def qft_no_swaps(num_qubits: int) -> QuantumCircuit:
    """ Return an inverse quantum Fourier transform circuit without the swap gates.
    """
    qft = QFT(num_qubits=num_qubits, do_swaps=False, inverse=True)
    return 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)