function
stringlengths 18
3.86k
| intent_category
stringlengths 5
24
|
---|---|
def tree_sort(arr):
# Build BST
if len(arr) == 0:
return arr
root = Node(arr[0])
for i in range(1, len(arr)):
root.insert(arr[i])
# Traverse BST in order.
res = []
inorder(root, res)
return res | sorts |
def wiggle_sort(nums: list) -> list:
for i, _ in enumerate(nums):
if (i % 2 == 1) == (nums[i - 1] > nums[i]):
nums[i - 1], nums[i] = nums[i], nums[i - 1]
return nums | sorts |
def bubble_sort(list_data: list, length: int = 0) -> list:
length = length or len(list_data)
swapped = False
for i in range(length - 1):
if list_data[i] > list_data[i + 1]:
list_data[i], list_data[i + 1] = list_data[i + 1], list_data[i]
swapped = True
return list_data if not swapped else bubble_sort(list_data, length - 1) | sorts |
def slowsort(sequence: list, start: int | None = None, end: int | None = None) -> None:
if start is None:
start = 0
if end is None:
end = len(sequence) - 1
if start >= end:
return
mid = (start + end) // 2
slowsort(sequence, start, mid)
slowsort(sequence, mid + 1, end)
if sequence[end] < sequence[mid]:
sequence[end], sequence[mid] = sequence[mid], sequence[end]
slowsort(sequence, start, end - 1) | sorts |
def __init__(self, filename):
self.filename = filename
self.block_filenames = [] | sorts |
def write_block(self, data, block_number):
filename = self.BLOCK_FILENAME_FORMAT.format(block_number)
with open(filename, "w") as file:
file.write(data)
self.block_filenames.append(filename) | sorts |
def get_block_filenames(self):
return self.block_filenames | sorts |
def split(self, block_size, sort_key=None):
i = 0
with open(self.filename) as file:
while True:
lines = file.readlines(block_size)
if lines == []:
break
if sort_key is None:
lines.sort()
else:
lines.sort(key=sort_key)
self.write_block("".join(lines), i)
i += 1 | sorts |
def cleanup(self):
map(os.remove, self.block_filenames) | sorts |
def select(self, choices):
min_index = -1
min_str = None
for i in range(len(choices)):
if min_str is None or choices[i] < min_str:
min_index = i
return min_index | sorts |
def __init__(self, files):
self.files = files
self.empty = set()
self.num_buffers = len(files)
self.buffers = {i: None for i in range(self.num_buffers)} | sorts |
def get_dict(self):
return {
i: self.buffers[i] for i in range(self.num_buffers) if i not in self.empty
} | sorts |
def refresh(self):
for i in range(self.num_buffers):
if self.buffers[i] is None and i not in self.empty:
self.buffers[i] = self.files[i].readline()
if self.buffers[i] == "":
self.empty.add(i)
self.files[i].close()
if len(self.empty) == self.num_buffers:
return False
return True | sorts |
def unshift(self, index):
value = self.buffers[index]
self.buffers[index] = None
return value | sorts |
def __init__(self, merge_strategy):
self.merge_strategy = merge_strategy | sorts |
def merge(self, filenames, outfilename, buffer_size):
buffers = FilesArray(self.get_file_handles(filenames, buffer_size))
with open(outfilename, "w", buffer_size) as outfile:
while buffers.refresh():
min_index = self.merge_strategy.select(buffers.get_dict())
outfile.write(buffers.unshift(min_index)) | sorts |
def get_file_handles(self, filenames, buffer_size):
files = {}
for i in range(len(filenames)):
files[i] = open(filenames[i], "r", buffer_size)
return files | sorts |
def __init__(self, block_size):
self.block_size = block_size | sorts |
def sort(self, filename, sort_key=None):
num_blocks = self.get_number_blocks(filename, self.block_size)
splitter = FileSplitter(filename)
splitter.split(self.block_size, sort_key)
merger = FileMerger(NWayMerge())
buffer_size = self.block_size / (num_blocks + 1)
merger.merge(splitter.get_block_filenames(), filename + ".out", buffer_size)
splitter.cleanup() | sorts |
def get_number_blocks(self, filename, block_size):
return (os.stat(filename).st_size / block_size) + 1 | sorts |
def parse_memory(string):
if string[-1].lower() == "k":
return int(string[:-1]) * 1024
elif string[-1].lower() == "m":
return int(string[:-1]) * 1024 * 1024
elif string[-1].lower() == "g":
return int(string[:-1]) * 1024 * 1024 * 1024
else:
return int(string) | sorts |
def main():
parser = argparse.ArgumentParser()
parser.add_argument(
"-m", "--mem", help="amount of memory to use for sorting", default="100M"
)
parser.add_argument(
"filename", metavar="<filename>", nargs=1, help="name of file to sort"
)
args = parser.parse_args()
sorter = ExternalSort(parse_memory(args.mem))
sorter.sort(args.filename[0]) | sorts |
def heapify(unsorted, index, heap_size):
largest = index
left_index = 2 * index + 1
right_index = 2 * index + 2
if left_index < heap_size and unsorted[left_index] > unsorted[largest]:
largest = left_index
if right_index < heap_size and unsorted[right_index] > unsorted[largest]:
largest = right_index
if largest != index:
unsorted[largest], unsorted[index] = unsorted[index], unsorted[largest]
heapify(unsorted, largest, heap_size) | sorts |
def heap_sort(unsorted):
n = len(unsorted)
for i in range(n // 2 - 1, -1, -1):
heapify(unsorted, i, n)
for i in range(n - 1, 0, -1):
unsorted[0], unsorted[i] = unsorted[i], unsorted[0]
heapify(unsorted, 0, i)
return unsorted | sorts |
def exchange_sort(numbers: list[int]) -> list[int]:
numbers_length = len(numbers)
for i in range(numbers_length):
for j in range(i + 1, numbers_length):
if numbers[j] < numbers[i]:
numbers[i], numbers[j] = numbers[j], numbers[i]
return numbers | sorts |
def strand_sort(arr: list, reverse: bool = False, solution: list | None = None) -> list:
_operator = operator.lt if reverse else operator.gt
solution = solution or []
if not arr:
return solution
sublist = [arr.pop(0)]
for i, item in enumerate(arr):
if _operator(item, sublist[-1]):
sublist.append(item)
arr.pop(i)
# merging sublist into solution list
if not solution:
solution.extend(sublist)
else:
while sublist:
item = sublist.pop(0)
for i, xx in enumerate(solution):
if not _operator(item, xx):
solution.insert(i, item)
break
else:
solution.append(item)
strand_sort(arr, reverse, solution)
return solution | sorts |
def quick_sort(data: list) -> list:
if len(data) <= 1:
return data
else:
return [
*quick_sort([e for e in data[1:] if e <= data[0]]),
data[0],
*quick_sort([e for e in data[1:] if e > data[0]]),
] | sorts |
def __lt__(self, other):
return self[-1] < other[-1] | sorts |
def __eq__(self, other):
return self[-1] == other[-1] | sorts |
def patience_sort(collection: list) -> list:
stacks: list[Stack] = []
# sort into stacks
for element in collection:
new_stacks = Stack([element])
i = bisect_left(stacks, new_stacks)
if i != len(stacks):
stacks[i].append(element)
else:
stacks.append(new_stacks)
# use a heap-based merge to merge stack efficiently
collection[:] = merge(*(reversed(stack) for stack in stacks))
return collection | sorts |
def partition(a, left_index, right_index):
pivot = a[left_index]
i = left_index + 1
for j in range(left_index + 1, right_index):
if a[j] < pivot:
a[j], a[i] = a[i], a[j]
i += 1
a[left_index], a[i - 1] = a[i - 1], a[left_index]
return i - 1 | sorts |
def quick_sort_random(a, left, right):
if left < right:
pivot = random.randint(left, right - 1)
a[pivot], a[left] = (
a[left],
a[pivot],
) # switches the pivot with the left most bound
pivot_index = partition(a, left, right)
quick_sort_random(
a, left, pivot_index
) # recursive quicksort to the left of the pivot point
quick_sort_random(
a, pivot_index + 1, right
) # recursive quicksort to the right of the pivot point | sorts |
def main():
user_input = input("Enter numbers separated by a comma:\n").strip()
arr = [int(item) for item in user_input.split(",")]
quick_sort_random(arr, 0, len(arr))
print(arr) | sorts |
def bead_sort(sequence: list) -> list:
if any(not isinstance(x, int) or x < 0 for x in sequence):
raise TypeError("Sequence must be list of non-negative integers")
for _ in range(len(sequence)):
for i, (rod_upper, rod_lower) in enumerate(zip(sequence, sequence[1:])):
if rod_upper > rod_lower:
sequence[i] -= rod_upper - rod_lower
sequence[i + 1] += rod_upper - rod_lower
return sequence | sorts |
def comb_sort(data: list) -> list:
shrink_factor = 1.3
gap = len(data)
completed = False
while not completed:
# Update the gap value for a next comb
gap = int(gap / shrink_factor)
if gap <= 1:
completed = True
index = 0
while index + gap < len(data):
if data[index] > data[index + gap]:
# Swap values
data[index], data[index + gap] = data[index + gap], data[index]
completed = False
index += 1
return data | sorts |
def pigeon_sort(array: list[int]) -> list[int]:
if len(array) == 0:
return array
_min, _max = min(array), max(array)
# Compute the variables
holes_range = _max - _min + 1
holes, holes_repeat = [0] * holes_range, [0] * holes_range
# Make the sorting.
for i in array:
index = i - _min
holes[index] = i
holes_repeat[index] += 1
# Makes the array back by replacing the numbers.
index = 0
for i in range(holes_range):
while holes_repeat[i] > 0:
array[index] = holes[i]
index += 1
holes_repeat[i] -= 1
# Returns the sorted array.
return array | sorts |
def comp_and_swap(array: list[int], index1: int, index2: int, direction: int) -> None:
if (direction == 1 and array[index1] > array[index2]) or (
direction == 0 and array[index1] < array[index2]
):
array[index1], array[index2] = array[index2], array[index1] | sorts |
def bitonic_merge(array: list[int], low: int, length: int, direction: int) -> None:
if length > 1:
middle = int(length / 2)
for i in range(low, low + middle):
comp_and_swap(array, i, i + middle, direction)
bitonic_merge(array, low, middle, direction)
bitonic_merge(array, low + middle, middle, direction) | sorts |
def bitonic_sort(array: list[int], low: int, length: int, direction: int) -> None:
if length > 1:
middle = int(length / 2)
bitonic_sort(array, low, middle, 1)
bitonic_sort(array, low + middle, middle, 0)
bitonic_merge(array, low, length, direction) | sorts |
def alphanum_key(key):
return [int(s) if s.isdigit() else s.lower() for s in re.split("([0-9]+)", key)] | sorts |
def double_sort(lst):
no_of_elements = len(lst)
for _ in range(
0, int(((no_of_elements - 1) / 2) + 1)
): # we don't need to traverse to end of list as
for j in range(0, no_of_elements - 1):
if (
lst[j + 1] < lst[j]
): # applying bubble sort algorithm from left to right (or forwards)
temp = lst[j + 1]
lst[j + 1] = lst[j]
lst[j] = temp
if (
lst[no_of_elements - 1 - j] < lst[no_of_elements - 2 - j]
): # applying bubble sort algorithm from right to left (or backwards)
temp = lst[no_of_elements - 1 - j]
lst[no_of_elements - 1 - j] = lst[no_of_elements - 2 - j]
lst[no_of_elements - 2 - j] = temp
return lst | sorts |
def __init__(self, order: int) -> None:
self.order = order
# a_{0} ... a_{k}
self.a_coeffs = [1.0] + [0.0] * order
# b_{0} ... b_{k}
self.b_coeffs = [1.0] + [0.0] * order
# x[n-1] ... x[n-k]
self.input_history = [0.0] * self.order
# y[n-1] ... y[n-k]
self.output_history = [0.0] * self.order | audio_filters |
def set_coefficients(self, a_coeffs: list[float], b_coeffs: list[float]) -> None:
if len(a_coeffs) < self.order:
a_coeffs = [1.0, *a_coeffs]
if len(a_coeffs) != self.order + 1:
raise ValueError(
f"Expected a_coeffs to have {self.order + 1} elements for {self.order}"
f"-order filter, got {len(a_coeffs)}"
)
if len(b_coeffs) != self.order + 1:
raise ValueError(
f"Expected b_coeffs to have {self.order + 1} elements for {self.order}"
f"-order filter, got {len(a_coeffs)}"
)
self.a_coeffs = a_coeffs
self.b_coeffs = b_coeffs | audio_filters |
def process(self, sample: float) -> float:
return 0.0 | audio_filters |
def get_bounds(
fft_results: np.ndarray, samplerate: int
) -> tuple[int | float, int | float]:
lowest = min([-20, np.min(fft_results[1 : samplerate // 2 - 1])])
highest = max([20, np.max(fft_results[1 : samplerate // 2 - 1])])
return lowest, highest | audio_filters |
def show_frequency_response(filter_type: FilterType, samplerate: int) -> None:
size = 512
inputs = [1] + [0] * (size - 1)
outputs = [filter_type.process(item) for item in inputs]
filler = [0] * (samplerate - size) # zero-padding
outputs += filler
fft_out = np.abs(np.fft.fft(outputs))
fft_db = 20 * np.log10(fft_out)
# Frequencies on log scale from 24 to nyquist frequency
plt.xlim(24, samplerate / 2 - 1)
plt.xlabel("Frequency (Hz)")
plt.xscale("log")
# Display within reasonable bounds
bounds = get_bounds(fft_db, samplerate)
plt.ylim(max([-80, bounds[0]]), min([80, bounds[1]]))
plt.ylabel("Gain (dB)")
plt.plot(fft_db)
plt.show() | audio_filters |
def make_lowpass(
frequency: int, samplerate: int, q_factor: float = 1 / sqrt(2) # noqa: B008 | audio_filters |
def make_highpass(
frequency: int, samplerate: int, q_factor: float = 1 / sqrt(2) # noqa: B008 | audio_filters |
def make_bandpass(
frequency: int, samplerate: int, q_factor: float = 1 / sqrt(2) # noqa: B008 | audio_filters |
def make_allpass(
frequency: int, samplerate: int, q_factor: float = 1 / sqrt(2) # noqa: B008 | audio_filters |
def make_peak(
frequency: int,
samplerate: int,
gain_db: float,
q_factor: float = 1 / sqrt(2), # noqa: B008 | audio_filters |
def make_lowshelf(
frequency: int,
samplerate: int,
gain_db: float,
q_factor: float = 1 / sqrt(2), # noqa: B008 | audio_filters |
def make_highshelf(
frequency: int,
samplerate: int,
gain_db: float,
q_factor: float = 1 / sqrt(2), # noqa: B008 | audio_filters |
def bb84(key_len: int = 8, seed: int | None = None) -> str:
# Set up the random number generator.
rng = np.random.default_rng(seed=seed)
# Roughly 25% of the qubits will contribute to the key.
# So we take more than we need.
num_qubits = 6 * key_len
# Measurement basis for Alice's qubits.
alice_basis = rng.integers(2, size=num_qubits)
# The set of states Alice will prepare.
alice_state = rng.integers(2, size=num_qubits)
# Measurement basis for Bob's qubits.
bob_basis = rng.integers(2, size=num_qubits)
# Quantum Circuit to simulate BB84
bb84_circ = qiskit.QuantumCircuit(num_qubits, name="BB84")
# Alice prepares her qubits according to rules above.
for index, _ in enumerate(alice_basis):
if alice_state[index] == 1:
bb84_circ.x(index)
if alice_basis[index] == 1:
bb84_circ.h(index)
bb84_circ.barrier()
# Bob measures the received qubits according to rules above.
for index, _ in enumerate(bob_basis):
if bob_basis[index] == 1:
bb84_circ.h(index)
bb84_circ.barrier()
bb84_circ.measure_all()
# Simulate the quantum circuit.
sim = qiskit.Aer.get_backend("aer_simulator")
# We only need to run one shot because the key is unique.
# Multiple shots will produce the same key.
job = qiskit.execute(bb84_circ, sim, shots=1, seed_simulator=seed)
# Returns the result of measurement.
result = job.result().get_counts(bb84_circ).most_frequent()
# Extracting the generated key from the simulation results.
# Only keep measurement results where Alice and Bob chose the same basis.
gen_key = "".join(
[
result_bit
for alice_basis_bit, bob_basis_bit, result_bit in zip(
alice_basis, bob_basis, result
)
if alice_basis_bit == bob_basis_bit
]
)
# Get final key. Pad with 0 if too short, otherwise truncate.
key = gen_key[:key_len] if len(gen_key) >= key_len else gen_key.ljust(key_len, "0")
return key | quantum |
def store_two_classics(val1: int, val2: int) -> tuple[qiskit.QuantumCircuit, str, str]:
x, y = bin(val1)[2:], bin(val2)[2:] # Remove leading '0b'
# Ensure that both strings are of the same length
if len(x) > len(y):
y = y.zfill(len(x))
else:
x = x.zfill(len(y))
# We need (3 * number of bits in the larger number)+1 qBits
# The second parameter is the number of classical registers, to measure the result
circuit = qiskit.QuantumCircuit((len(x) * 3) + 1, len(x) + 1)
# We are essentially "not-ing" the bits that are 1
# Reversed because it's easier to perform ops on more significant bits
for i in range(len(x)):
if x[::-1][i] == "1":
circuit.x(i)
for j in range(len(y)):
if y[::-1][j] == "1":
circuit.x(len(x) + j)
return circuit, x, y | quantum |
def full_adder(
circuit: qiskit.QuantumCircuit,
input1_loc: int,
input2_loc: int,
carry_in: int,
carry_out: int,
):
circuit.ccx(input1_loc, input2_loc, carry_out)
circuit.cx(input1_loc, input2_loc)
circuit.ccx(input2_loc, carry_in, carry_out)
circuit.cx(input2_loc, carry_in)
circuit.cx(input1_loc, input2_loc) | quantum |
def ripple_adder(
val1: int,
val2: int,
backend: Backend = qiskit.Aer.get_backend("aer_simulator"), # noqa: B008 | quantum |
def quantum_entanglement(qubits: int = 2) -> qiskit.result.counts.Counts:
classical_bits = qubits
# Using Aer's simulator
simulator = qiskit.Aer.get_backend("aer_simulator")
# Creating a Quantum Circuit acting on the q register
circuit = qiskit.QuantumCircuit(qubits, classical_bits)
# Adding a H gate on qubit 0 (now q0 in superposition)
circuit.h(0)
for i in range(1, qubits):
# Adding CX (CNOT) gate
circuit.cx(i - 1, i)
# Mapping the quantum measurement to the classical bits
circuit.measure(list(range(qubits)), list(range(classical_bits)))
# Now measuring any one qubit would affect other qubits to collapse
# their super position and have same state as the measured one.
# Executing the circuit on the simulator
job = qiskit.execute(circuit, simulator, shots=1000)
return job.result().get_counts(circuit) | quantum |
def single_qubit_measure(
qubits: int, classical_bits: int
) -> qiskit.result.counts.Counts:
# Use Aer's simulator
simulator = qiskit.Aer.get_backend("aer_simulator")
# Create a Quantum Circuit acting on the q register
circuit = qiskit.QuantumCircuit(qubits, classical_bits)
# Map the quantum measurement to the classical bits
circuit.measure([0], [0])
# Execute the circuit on the simulator
job = qiskit.execute(circuit, simulator, shots=1000)
# Return the histogram data of the results of the experiment.
return job.result().get_counts(circuit) | quantum |
def quantum_fourier_transform(number_of_qubits: int = 3) -> qiskit.result.counts.Counts:
if isinstance(number_of_qubits, str):
raise TypeError("number of qubits must be a integer.")
if number_of_qubits <= 0:
raise ValueError("number of qubits must be > 0.")
if math.floor(number_of_qubits) != number_of_qubits:
raise ValueError("number of qubits must be exact integer.")
if number_of_qubits > 10:
raise ValueError("number of qubits too large to simulate(>10).")
qr = QuantumRegister(number_of_qubits, "qr")
cr = ClassicalRegister(number_of_qubits, "cr")
quantum_circuit = QuantumCircuit(qr, cr)
counter = number_of_qubits
for i in range(counter):
quantum_circuit.h(number_of_qubits - i - 1)
counter -= 1
for j in range(counter):
quantum_circuit.cp(np.pi / 2 ** (counter - j), j, counter)
for k in range(number_of_qubits // 2):
quantum_circuit.swap(k, number_of_qubits - k - 1)
# measure all the qubits
quantum_circuit.measure(qr, cr)
# simulate with 10000 shots
backend = Aer.get_backend("qasm_simulator")
job = execute(quantum_circuit, backend, shots=10000)
return job.result().get_counts(quantum_circuit) | quantum |
def superdense_coding(bit_1: int = 1, bit_2: int = 1) -> qiskit.result.counts.Counts:
if isinstance(bit_1, str) or isinstance(bit_2, str):
raise TypeError("inputs must be integers.")
if (bit_1 < 0) or (bit_2 < 0):
raise ValueError("inputs must be positive.")
if (math.floor(bit_1) != bit_1) or (math.floor(bit_2) != bit_2):
raise ValueError("inputs must be exact integers.")
if (bit_1 > 1) or (bit_2 > 1):
raise ValueError("inputs must be less or equal to 1.")
# build registers
qr = QuantumRegister(2, "qr")
cr = ClassicalRegister(2, "cr")
quantum_circuit = QuantumCircuit(qr, cr)
# entanglement the qubits
quantum_circuit.h(1)
quantum_circuit.cx(1, 0)
# send the information
c_information = str(bit_1) + str(bit_2)
if c_information == "11":
quantum_circuit.x(1)
quantum_circuit.z(1)
elif c_information == "10":
quantum_circuit.z(1)
elif c_information == "01":
quantum_circuit.x(1)
else:
quantum_circuit.i(1)
# unentangled the circuit
quantum_circuit.cx(1, 0)
quantum_circuit.h(1)
# measure the circuit
quantum_circuit.measure(qr, cr)
backend = Aer.get_backend("aer_simulator")
job = execute(quantum_circuit, backend, shots=1000)
return job.result().get_counts(quantum_circuit) | quantum |
def single_qubit_measure(
qubits: int, classical_bits: int
) -> qiskit.result.counts.Counts:
# Use Aer's simulator
simulator = qiskit.Aer.get_backend("aer_simulator")
# Create a Quantum Circuit acting on the q register
circuit = qiskit.QuantumCircuit(qubits, classical_bits)
# Apply X (NOT) Gate to Qubits 0 & 1
circuit.x(0)
circuit.x(1)
# Map the quantum measurement to the classical bits
circuit.measure([0, 1], [0, 1])
# Execute the circuit on the qasm simulator
job = qiskit.execute(circuit, simulator, shots=1000)
# Return the histogram data of the results of the experiment.
return job.result().get_counts(circuit) | quantum |
def half_adder(bit0: int, bit1: int) -> qiskit.result.counts.Counts:
# Use Aer's simulator
simulator = qiskit.Aer.get_backend("aer_simulator")
qc_ha = qiskit.QuantumCircuit(4, 2)
# encode inputs in qubits 0 and 1
if bit0 == 1:
qc_ha.x(0)
if bit1 == 1:
qc_ha.x(1)
qc_ha.barrier()
# use cnots to write XOR of the inputs on qubit2
qc_ha.cx(0, 2)
qc_ha.cx(1, 2)
# use ccx / toffoli gate to write AND of the inputs on qubit3
qc_ha.ccx(0, 1, 3)
qc_ha.barrier()
# extract outputs
qc_ha.measure(2, 0) # extract XOR value
qc_ha.measure(3, 1) # extract AND value
# Execute the circuit on the qasm simulator
job = qiskit.execute(qc_ha, simulator, shots=1000)
# Return the histogram data of the results of the experiment
return job.result().get_counts(qc_ha) | quantum |
def dj_oracle(case: str, num_qubits: int) -> qiskit.QuantumCircuit:
# This circuit has num_qubits+1 qubits: the size of the input,
# plus one output qubit
oracle_qc = qiskit.QuantumCircuit(num_qubits + 1)
# First, let's deal with the case in which oracle is balanced
if case == "balanced":
# First generate a random number that tells us which CNOTs to
# wrap in X-gates:
b = np.random.randint(1, 2**num_qubits)
# Next, format 'b' as a binary string of length 'n', padded with zeros:
b_str = format(b, f"0{num_qubits}b")
# Next, we place the first X-gates. Each digit in our binary string
# corresponds to a qubit, if the digit is 0, we do nothing, if it's 1
# we apply an X-gate to that qubit:
for index, bit in enumerate(b_str):
if bit == "1":
oracle_qc.x(index)
# Do the controlled-NOT gates for each qubit, using the output qubit
# as the target:
for index in range(num_qubits):
oracle_qc.cx(index, num_qubits)
# Next, place the final X-gates
for index, bit in enumerate(b_str):
if bit == "1":
oracle_qc.x(index)
# Case in which oracle is constant
if case == "constant":
# First decide what the fixed output of the oracle will be
# (either always 0 or always 1)
output = np.random.randint(2)
if output == 1:
oracle_qc.x(num_qubits)
oracle_gate = oracle_qc.to_gate()
oracle_gate.name = "Oracle" # To show when we display the circuit
return oracle_gate | quantum |
def dj_algorithm(
oracle: qiskit.QuantumCircuit, num_qubits: int
) -> qiskit.QuantumCircuit:
dj_circuit = qiskit.QuantumCircuit(num_qubits + 1, num_qubits)
# Set up the output qubit:
dj_circuit.x(num_qubits)
dj_circuit.h(num_qubits)
# And set up the input register:
for qubit in range(num_qubits):
dj_circuit.h(qubit)
# Let's append the oracle gate to our circuit:
dj_circuit.append(oracle, range(num_qubits + 1))
# Finally, perform the H-gates again and measure:
for qubit in range(num_qubits):
dj_circuit.h(qubit)
for i in range(num_qubits):
dj_circuit.measure(i, i)
return dj_circuit | quantum |
def deutsch_jozsa(case: str, num_qubits: int) -> qiskit.result.counts.Counts:
# Use Aer's simulator
simulator = qiskit.Aer.get_backend("aer_simulator")
oracle_gate = dj_oracle(case, num_qubits)
dj_circuit = dj_algorithm(oracle_gate, num_qubits)
# Execute the circuit on the simulator
job = qiskit.execute(dj_circuit, simulator, shots=1000)
# Return the histogram data of the results of the experiment.
return job.result().get_counts(dj_circuit) | quantum |
def quantum_teleportation(
theta: float = np.pi / 2, phi: float = np.pi / 2, lam: float = np.pi / 2
) -> qiskit.result.counts.Counts:
qr = QuantumRegister(3, "qr") # Define the number of quantum bits
cr = ClassicalRegister(1, "cr") # Define the number of classical bits
quantum_circuit = QuantumCircuit(qr, cr) # Define the quantum circuit.
# Build the circuit
quantum_circuit.u(theta, phi, lam, 0) # Quantum State to teleport
quantum_circuit.h(1) # add hadamard gate
quantum_circuit.cx(
1, 2
) # add control gate with qubit 1 as control and 2 as target.
quantum_circuit.cx(0, 1)
quantum_circuit.h(0)
quantum_circuit.cz(0, 2) # add control z gate.
quantum_circuit.cx(1, 2)
quantum_circuit.measure([2], [0]) # measure the qubit.
# Simulate the circuit using qasm simulator
backend = Aer.get_backend("aer_simulator")
job = execute(quantum_circuit, backend, shots=1000)
return job.result().get_counts(quantum_circuit) | quantum |
def quantum_full_adder(
input_1: int = 1, input_2: int = 1, carry_in: int = 1
) -> qiskit.result.counts.Counts:
if (
isinstance(input_1, str)
or isinstance(input_2, str)
or isinstance(carry_in, str)
):
raise TypeError("inputs must be integers.")
if (input_1 < 0) or (input_2 < 0) or (carry_in < 0):
raise ValueError("inputs must be positive.")
if (
(math.floor(input_1) != input_1)
or (math.floor(input_2) != input_2)
or (math.floor(carry_in) != carry_in)
):
raise ValueError("inputs must be exact integers.")
if (input_1 > 2) or (input_2 > 2) or (carry_in > 2):
raise ValueError("inputs must be less or equal to 2.")
# build registers
qr = qiskit.QuantumRegister(4, "qr")
cr = qiskit.ClassicalRegister(2, "cr")
# list the entries
entry = [input_1, input_2, carry_in]
quantum_circuit = qiskit.QuantumCircuit(qr, cr)
for i in range(0, 3):
if entry[i] == 2:
quantum_circuit.h(i) # for hadamard entries
elif entry[i] == 1:
quantum_circuit.x(i) # for 1 entries
elif entry[i] == 0:
quantum_circuit.i(i) # for 0 entries
# build the circuit
quantum_circuit.ccx(0, 1, 3) # ccx = toffoli gate
quantum_circuit.cx(0, 1)
quantum_circuit.ccx(1, 2, 3)
quantum_circuit.cx(1, 2)
quantum_circuit.cx(0, 1)
quantum_circuit.measure([2, 3], cr) # measure the last two qbits
backend = qiskit.Aer.get_backend("aer_simulator")
job = qiskit.execute(quantum_circuit, backend, shots=1000)
return job.result().get_counts(quantum_circuit) | quantum |