function
stringlengths 18
3.86k
| intent_category
stringlengths 5
24
|
---|---|
def is_square(self) -> bool:
return self.order[0] == self.order[1] | matrix |
def identity(self) -> Matrix:
values = [
[0 if column_num != row_num else 1 for column_num in range(self.num_rows)]
for row_num in range(self.num_rows)
]
return Matrix(values) | matrix |
def determinant(self) -> int:
if not self.is_square:
return 0
if self.order == (0, 0):
return 1
if self.order == (1, 1):
return int(self.rows[0][0])
if self.order == (2, 2):
return int(
(self.rows[0][0] * self.rows[1][1])
- (self.rows[0][1] * self.rows[1][0])
)
else:
return sum(
self.rows[0][column] * self.cofactors().rows[0][column]
for column in range(self.num_columns)
) | matrix |
def is_invertable(self) -> bool:
return bool(self.determinant()) | matrix |
def get_minor(self, row: int, column: int) -> int:
values = [
[
self.rows[other_row][other_column]
for other_column in range(self.num_columns)
if other_column != column
]
for other_row in range(self.num_rows)
if other_row != row
]
return Matrix(values).determinant() | matrix |
def get_cofactor(self, row: int, column: int) -> int:
if (row + column) % 2 == 0:
return self.get_minor(row, column)
return -1 * self.get_minor(row, column) | matrix |
def minors(self) -> Matrix:
return Matrix(
[
[self.get_minor(row, column) for column in range(self.num_columns)]
for row in range(self.num_rows)
]
) | matrix |
def cofactors(self) -> Matrix:
return Matrix(
[
[
self.minors().rows[row][column]
if (row + column) % 2 == 0
else self.minors().rows[row][column] * -1
for column in range(self.minors().num_columns)
]
for row in range(self.minors().num_rows)
]
) | matrix |
def adjugate(self) -> Matrix:
values = [
[self.cofactors().rows[column][row] for column in range(self.num_columns)]
for row in range(self.num_rows)
]
return Matrix(values) | matrix |
def inverse(self) -> Matrix:
determinant = self.determinant()
if not determinant:
raise TypeError("Only matrices with a non-zero determinant have an inverse")
return self.adjugate() * (1 / determinant) | matrix |
def __repr__(self) -> str:
return str(self.rows) | matrix |
def __str__(self) -> str:
if self.num_rows == 0:
return "[]"
if self.num_rows == 1:
return "[[" + ". ".join(str(self.rows[0])) + "]]"
return (
"["
+ "\n ".join(
[
"[" + ". ".join([str(value) for value in row]) + ".]"
for row in self.rows
]
)
+ "]"
) | matrix |
def add_row(self, row: list[int], position: int | None = None) -> None:
type_error = TypeError("Row must be a list containing all ints and/or floats")
if not isinstance(row, list):
raise type_error
for value in row:
if not isinstance(value, (int, float)):
raise type_error
if len(row) != self.num_columns:
raise ValueError(
"Row must be equal in length to the other rows in the matrix"
)
if position is None:
self.rows.append(row)
else:
self.rows = self.rows[0:position] + [row] + self.rows[position:] | matrix |
def add_column(self, column: list[int], position: int | None = None) -> None:
type_error = TypeError(
"Column must be a list containing all ints and/or floats"
)
if not isinstance(column, list):
raise type_error
for value in column:
if not isinstance(value, (int, float)):
raise type_error
if len(column) != self.num_rows:
raise ValueError(
"Column must be equal in length to the other columns in the matrix"
)
if position is None:
self.rows = [self.rows[i] + [column[i]] for i in range(self.num_rows)]
else:
self.rows = [
self.rows[i][0:position] + [column[i]] + self.rows[i][position:]
for i in range(self.num_rows)
] | matrix |
def __eq__(self, other: object) -> bool:
if not isinstance(other, Matrix):
return NotImplemented
return self.rows == other.rows | matrix |
def __ne__(self, other: object) -> bool:
return not self == other | matrix |
def __neg__(self) -> Matrix:
return self * -1 | matrix |
def __add__(self, other: Matrix) -> Matrix:
if self.order != other.order:
raise ValueError("Addition requires matrices of the same order")
return Matrix(
[
[self.rows[i][j] + other.rows[i][j] for j in range(self.num_columns)]
for i in range(self.num_rows)
]
) | matrix |
def __sub__(self, other: Matrix) -> Matrix:
if self.order != other.order:
raise ValueError("Subtraction requires matrices of the same order")
return Matrix(
[
[self.rows[i][j] - other.rows[i][j] for j in range(self.num_columns)]
for i in range(self.num_rows)
]
) | matrix |
def __mul__(self, other: Matrix | int | float) -> Matrix:
if isinstance(other, (int, float)):
return Matrix(
[[int(element * other) for element in row] for row in self.rows]
)
elif isinstance(other, Matrix):
if self.num_columns != other.num_rows:
raise ValueError(
"The number of columns in the first matrix must "
"be equal to the number of rows in the second"
)
return Matrix(
[
[Matrix.dot_product(row, column) for column in other.columns()]
for row in self.rows
]
)
else:
raise TypeError(
"A Matrix can only be multiplied by an int, float, or another matrix"
) | matrix |
def __pow__(self, other: int) -> Matrix:
if not isinstance(other, int):
raise TypeError("A Matrix can only be raised to the power of an int")
if not self.is_square:
raise ValueError("Only square matrices can be raised to a power")
if other == 0:
return self.identity()
if other < 0:
if self.is_invertable():
return self.inverse() ** (-other)
raise ValueError(
"Only invertable matrices can be raised to a negative power"
)
result = self
for _ in range(other - 1):
result *= self
return result | matrix |
def dot_product(cls, row: list[int], column: list[int]) -> int:
return sum(row[i] * column[i] for i in range(len(row))) | matrix |
def print_pascal_triangle(num_rows: int) -> None:
triangle = generate_pascal_triangle(num_rows)
for row_idx in range(num_rows):
# Print left spaces
for _ in range(num_rows - row_idx - 1):
print(end=" ")
# Print row values
for col_idx in range(row_idx + 1):
if col_idx != row_idx:
print(triangle[row_idx][col_idx], end=" ")
else:
print(triangle[row_idx][col_idx], end="")
print() | matrix |
def generate_pascal_triangle(num_rows: int) -> list[list[int]]:
if not isinstance(num_rows, int):
raise TypeError("The input value of 'num_rows' should be 'int'")
if num_rows == 0:
return []
elif num_rows < 0:
raise ValueError(
"The input value of 'num_rows' should be greater than or equal to 0"
)
triangle: list[list[int]] = []
for current_row_idx in range(num_rows):
current_row = populate_current_row(triangle, current_row_idx)
triangle.append(current_row)
return triangle | matrix |
def populate_current_row(triangle: list[list[int]], current_row_idx: int) -> list[int]:
current_row = [-1] * (current_row_idx + 1)
# first and last elements of current row are equal to 1
current_row[0], current_row[-1] = 1, 1
for current_col_idx in range(1, current_row_idx):
calculate_current_element(
triangle, current_row, current_row_idx, current_col_idx
)
return current_row | matrix |
def calculate_current_element(
triangle: list[list[int]],
current_row: list[int],
current_row_idx: int,
current_col_idx: int,
) -> None:
above_to_left_elt = triangle[current_row_idx - 1][current_col_idx - 1]
above_to_right_elt = triangle[current_row_idx - 1][current_col_idx]
current_row[current_col_idx] = above_to_left_elt + above_to_right_elt | matrix |
def generate_pascal_triangle_optimized(num_rows: int) -> list[list[int]]:
if not isinstance(num_rows, int):
raise TypeError("The input value of 'num_rows' should be 'int'")
if num_rows == 0:
return []
elif num_rows < 0:
raise ValueError(
"The input value of 'num_rows' should be greater than or equal to 0"
)
result: list[list[int]] = [[1]]
for row_index in range(1, num_rows):
temp_row = [0] + result[-1] + [0]
row_length = row_index + 1
# Calculate the number of distinct elements in a row
distinct_elements = sum(divmod(row_length, 2))
row_first_half = [
temp_row[i - 1] + temp_row[i] for i in range(1, distinct_elements + 1)
]
row_second_half = row_first_half[: (row_index + 1) // 2]
row_second_half.reverse()
row = row_first_half + row_second_half
result.append(row)
return result | matrix |
def benchmark_a_function(func: Callable, value: int) -> None:
call = f"{func.__name__}({value})"
timing = timeit(f"__main__.{call}", setup="import __main__")
# print(f"{call:38} = {func(value)} -- {timing:.4f} seconds")
print(f"{call:38} -- {timing:.4f} seconds") | matrix |
def search_in_a_sorted_matrix(
mat: list[list[int]], m: int, n: int, key: int | float
) -> None:
i, j = m - 1, 0
while i >= 0 and j < n:
if key == mat[i][j]:
print(f"Key {key} found at row- {i + 1} column- {j + 1}")
return
if key < mat[i][j]:
i -= 1
else:
j += 1
print(f"Key {key} not found") | matrix |
def main() -> None:
mat = [[2, 5, 7], [4, 8, 13], [9, 11, 15], [12, 17, 20]]
x = int(input("Enter the element to be searched:"))
print(mat)
search_in_a_sorted_matrix(mat, len(mat), len(mat[0]), x) | matrix |
def multiply(matrix_a: list[list[int]], matrix_b: list[list[int]]) -> list[list[int]]:
matrix_c = []
n = len(matrix_a)
for i in range(n):
list_1 = []
for j in range(n):
val = 0
for k in range(n):
val = val + matrix_a[i][k] * matrix_b[k][j]
list_1.append(val)
matrix_c.append(list_1)
return matrix_c | matrix |
def identity(n: int) -> list[list[int]]:
return [[int(row == column) for column in range(n)] for row in range(n)] | matrix |
def nth_fibonacci_matrix(n: int) -> int:
if n <= 1:
return n
res_matrix = identity(2)
fibonacci_matrix = [[1, 1], [1, 0]]
n = n - 1
while n > 0:
if n % 2 == 1:
res_matrix = multiply(res_matrix, fibonacci_matrix)
fibonacci_matrix = multiply(fibonacci_matrix, fibonacci_matrix)
n = int(n / 2)
return res_matrix[0][0] | matrix |
def nth_fibonacci_bruteforce(n: int) -> int:
if n <= 1:
return n
fib0 = 0
fib1 = 1
for _ in range(2, n + 1):
fib0, fib1 = fib1, fib0 + fib1
return fib1 | matrix |
def main() -> None:
for ordinal in "0th 1st 2nd 3rd 10th 100th 1000th".split():
n = int("".join(c for c in ordinal if c in "0123456789")) # 1000th --> 1000
print(
f"{ordinal} fibonacci number using matrix exponentiation is "
f"{nth_fibonacci_matrix(n)} and using bruteforce is "
f"{nth_fibonacci_bruteforce(n)}\n"
)
# from timeit import timeit
# print(timeit("nth_fibonacci_matrix(1000000)",
# "from main import nth_fibonacci_matrix", number=5))
# print(timeit("nth_fibonacci_bruteforce(1000000)",
# "from main import nth_fibonacci_bruteforce", number=5))
# 2.3342058970001744
# 57.256506615000035 | matrix |
def test_addition(mat1, mat2):
if (np.array(mat1)).shape < (2, 2) or (np.array(mat2)).shape < (2, 2):
with pytest.raises(TypeError):
logger.info(f"\n\t{test_addition.__name__} returned integer")
matop.add(mat1, mat2)
elif (np.array(mat1)).shape == (np.array(mat2)).shape:
logger.info(f"\n\t{test_addition.__name__} with same matrix dims")
act = (np.array(mat1) + np.array(mat2)).tolist()
theo = matop.add(mat1, mat2)
assert theo == act
else:
with pytest.raises(ValueError):
logger.info(f"\n\t{test_addition.__name__} with different matrix dims")
matop.add(mat1, mat2) | matrix |
def test_subtraction(mat1, mat2):
if (np.array(mat1)).shape < (2, 2) or (np.array(mat2)).shape < (2, 2):
with pytest.raises(TypeError):
logger.info(f"\n\t{test_subtraction.__name__} returned integer")
matop.subtract(mat1, mat2)
elif (np.array(mat1)).shape == (np.array(mat2)).shape:
logger.info(f"\n\t{test_subtraction.__name__} with same matrix dims")
act = (np.array(mat1) - np.array(mat2)).tolist()
theo = matop.subtract(mat1, mat2)
assert theo == act
else:
with pytest.raises(ValueError):
logger.info(f"\n\t{test_subtraction.__name__} with different matrix dims")
assert matop.subtract(mat1, mat2) | matrix |
def test_multiplication(mat1, mat2):
if (np.array(mat1)).shape < (2, 2) or (np.array(mat2)).shape < (2, 2):
logger.info(f"\n\t{test_multiplication.__name__} returned integer")
with pytest.raises(TypeError):
matop.add(mat1, mat2)
elif (np.array(mat1)).shape == (np.array(mat2)).shape:
logger.info(f"\n\t{test_multiplication.__name__} meets dim requirements")
act = (np.matmul(mat1, mat2)).tolist()
theo = matop.multiply(mat1, mat2)
assert theo == act
else:
with pytest.raises(ValueError):
logger.info(
f"\n\t{test_multiplication.__name__} does not meet dim requirements"
)
assert matop.subtract(mat1, mat2) | matrix |
def test_scalar_multiply():
act = (3.5 * np.array(mat_a)).tolist()
theo = matop.scalar_multiply(mat_a, 3.5)
assert theo == act | matrix |
def test_identity():
act = (np.identity(5)).tolist()
theo = matop.identity(5)
assert theo == act | matrix |
def shell_sort(collection):
# Marcin Ciura's gap sequence
gaps = [701, 301, 132, 57, 23, 10, 4, 1]
for gap in gaps:
for i in range(gap, len(collection)):
insert_value = collection[i]
j = i
while j >= gap and collection[j - gap] > insert_value:
collection[j] = collection[j - gap]
j -= gap
if j != i:
collection[j] = insert_value
return collection | sorts |
def quick_sort_3partition(sorting: list, left: int, right: int) -> None:
if right <= left:
return
a = i = left
b = right
pivot = sorting[left]
while i <= b:
if sorting[i] < pivot:
sorting[a], sorting[i] = sorting[i], sorting[a]
a += 1
i += 1
elif sorting[i] > pivot:
sorting[b], sorting[i] = sorting[i], sorting[b]
b -= 1
else:
i += 1
quick_sort_3partition(sorting, left, a - 1)
quick_sort_3partition(sorting, b + 1, right) | sorts |
def quick_sort_lomuto_partition(sorting: list, left: int, right: int) -> None:
if left < right:
pivot_index = lomuto_partition(sorting, left, right)
quick_sort_lomuto_partition(sorting, left, pivot_index - 1)
quick_sort_lomuto_partition(sorting, pivot_index + 1, right) | sorts |
def lomuto_partition(sorting: list, left: int, right: int) -> int:
pivot = sorting[right]
store_index = left
for i in range(left, right):
if sorting[i] < pivot:
sorting[store_index], sorting[i] = sorting[i], sorting[store_index]
store_index += 1
sorting[right], sorting[store_index] = sorting[store_index], sorting[right]
return store_index | sorts |
def three_way_radix_quicksort(sorting: list) -> list:
if len(sorting) <= 1:
return sorting
return (
three_way_radix_quicksort([i for i in sorting if i < sorting[0]])
+ [i for i in sorting if i == sorting[0]]
+ three_way_radix_quicksort([i for i in sorting if i > sorting[0]])
) | sorts |
def bucket_sort(my_list: list) -> list:
if len(my_list) == 0:
return []
min_value, max_value = min(my_list), max(my_list)
bucket_count = int(max_value - min_value) + 1
buckets: list[list] = [[] for _ in range(bucket_count)]
for i in my_list:
buckets[int(i - min_value)].append(i)
return [v for bucket in buckets for v in sorted(bucket)] | sorts |
def oe_process(position, value, l_send, r_send, lr_cv, rr_cv, result_pipe):
global process_lock
# we perform n swaps since after n swaps we know we are sorted
# we *could* stop early if we are sorted already, but it takes as long to
# find out we are sorted as it does to sort the list with this algorithm
for i in range(0, 10):
if (i + position) % 2 == 0 and r_send is not None:
# send your value to your right neighbor
process_lock.acquire()
r_send[1].send(value)
process_lock.release()
# receive your right neighbor's value
process_lock.acquire()
temp = rr_cv[0].recv()
process_lock.release()
# take the lower value since you are on the left
value = min(value, temp)
elif (i + position) % 2 != 0 and l_send is not None:
# send your value to your left neighbor
process_lock.acquire()
l_send[1].send(value)
process_lock.release()
# receive your left neighbor's value
process_lock.acquire()
temp = lr_cv[0].recv()
process_lock.release()
# take the higher value since you are on the right
value = max(value, temp)
# after all swaps are performed, send the values back to main
result_pipe[1].send(value) | sorts |
def odd_even_transposition(arr):
process_array_ = []
result_pipe = []
# initialize the list of pipes where the values will be retrieved
for _ in arr:
result_pipe.append(Pipe())
# creates the processes
# the first and last process only have one neighbor so they are made outside
# of the loop
temp_rs = Pipe()
temp_rr = Pipe()
process_array_.append(
Process(
target=oe_process,
args=(0, arr[0], None, temp_rs, None, temp_rr, result_pipe[0]),
)
)
temp_lr = temp_rs
temp_ls = temp_rr
for i in range(1, len(arr) - 1):
temp_rs = Pipe()
temp_rr = Pipe()
process_array_.append(
Process(
target=oe_process,
args=(i, arr[i], temp_ls, temp_rs, temp_lr, temp_rr, result_pipe[i]),
)
)
temp_lr = temp_rs
temp_ls = temp_rr
process_array_.append(
Process(
target=oe_process,
args=(
len(arr) - 1,
arr[len(arr) - 1],
temp_ls,
None,
temp_lr,
None,
result_pipe[len(arr) - 1],
),
)
)
# start the processes
for p in process_array_:
p.start()
# wait for the processes to end and write their values to the list
for p in range(0, len(result_pipe)):
arr[p] = result_pipe[p][0].recv()
process_array_[p].join()
return arr | sorts |
def main():
arr = list(range(10, 0, -1))
print("Initial List")
print(*arr)
arr = odd_even_transposition(arr)
print("Sorted List\n")
print(*arr) | sorts |
def quick_sort(collection: list) -> list:
if len(collection) < 2:
return collection
pivot_index = randrange(len(collection)) # Use random element as pivot
pivot = collection[pivot_index]
greater: list[int] = [] # All elements greater than pivot
lesser: list[int] = [] # All elements less than or equal to pivot
for element in collection[:pivot_index]:
(greater if element > pivot else lesser).append(element)
for element in collection[pivot_index + 1 :]:
(greater if element > pivot else lesser).append(element)
return [*quick_sort(lesser), pivot, *quick_sort(greater)] | sorts |
def _merge():
while left and right:
yield (left if left[0] <= right[0] else right).pop(0)
yield from left
yield from right | sorts |
def merge_sort(collection):
start, end = [], []
while len(collection) > 1:
min_one, max_one = min(collection), max(collection)
start.append(min_one)
end.append(max_one)
collection.remove(min_one)
collection.remove(max_one)
end.reverse()
return start + collection + end | sorts |
def insertion_sort(array: list, start: int = 0, end: int = 0) -> list:
end = end or len(array)
for i in range(start, end):
temp_index = i
temp_index_value = array[i]
while temp_index != start and temp_index_value < array[temp_index - 1]:
array[temp_index] = array[temp_index - 1]
temp_index -= 1
array[temp_index] = temp_index_value
return array | sorts |
def heapify(array: list, index: int, heap_size: int) -> None: # Max Heap
largest = index
left_index = 2 * index + 1 # Left Node
right_index = 2 * index + 2 # Right Node
if left_index < heap_size and array[largest] < array[left_index]:
largest = left_index
if right_index < heap_size and array[largest] < array[right_index]:
largest = right_index
if largest != index:
array[index], array[largest] = array[largest], array[index]
heapify(array, largest, heap_size) | sorts |
def heap_sort(array: list) -> list:
n = len(array)
for i in range(n // 2, -1, -1):
heapify(array, i, n)
for i in range(n - 1, 0, -1):
array[i], array[0] = array[0], array[i]
heapify(array, 0, i)
return array | sorts |
def median_of_3(
array: list, first_index: int, middle_index: int, last_index: int
) -> int:
if (array[first_index] > array[middle_index]) != (
array[first_index] > array[last_index]
):
return array[first_index]
elif (array[middle_index] > array[first_index]) != (
array[middle_index] > array[last_index]
):
return array[middle_index]
else:
return array[last_index] | sorts |
def partition(array: list, low: int, high: int, pivot: int) -> int:
i = low
j = high
while True:
while array[i] < pivot:
i += 1
j -= 1
while pivot < array[j]:
j -= 1
if i >= j:
return i
array[i], array[j] = array[j], array[i]
i += 1 | sorts |
def sort(array: list) -> list:
if len(array) == 0:
return array
max_depth = 2 * math.ceil(math.log2(len(array)))
size_threshold = 16
return intro_sort(array, 0, len(array), size_threshold, max_depth) | sorts |
def intro_sort(
array: list, start: int, end: int, size_threshold: int, max_depth: int
) -> list:
while end - start > size_threshold:
if max_depth == 0:
return heap_sort(array)
max_depth -= 1
pivot = median_of_3(array, start, start + ((end - start) // 2) + 1, end - 1)
p = partition(array, start, end, pivot)
intro_sort(array, p, end, size_threshold, max_depth)
end = p
return insertion_sort(array, start, end) | sorts |
def cycle_sort(array: list) -> list:
array_len = len(array)
for cycle_start in range(0, array_len - 1):
item = array[cycle_start]
pos = cycle_start
for i in range(cycle_start + 1, array_len):
if array[i] < item:
pos += 1
if pos == cycle_start:
continue
while item == array[pos]:
pos += 1
array[pos], item = item, array[pos]
while pos != cycle_start:
pos = cycle_start
for i in range(cycle_start + 1, array_len):
if array[i] < item:
pos += 1
while item == array[pos]:
pos += 1
array[pos], item = item, array[pos]
return array | sorts |
def pigeonhole_sort(a):
# size of range of values in the list (ie, number of pigeonholes we need)
min_val = min(a) # min() finds the minimum value
max_val = max(a) # max() finds the maximum value
size = max_val - min_val + 1 # size is difference of max and min values plus one
# list of pigeonholes of size equal to the variable size
holes = [0] * size
# Populate the pigeonholes.
for x in a:
assert isinstance(x, int), "integers only please"
holes[x - min_val] += 1
# Putting the elements back into the array in an order.
i = 0
for count in range(size):
while holes[count] > 0:
holes[count] -= 1
a[i] = count + min_val
i += 1 | sorts |
def main():
a = [8, 3, 2, 7, 4, 6, 8]
pigeonhole_sort(a)
print("Sorted order is:", " ".join(a)) | sorts |
def rec_insertion_sort(collection: list, n: int):
# Checks if the entire collection has been sorted
if len(collection) <= 1 or n <= 1:
return
insert_next(collection, n - 1)
rec_insertion_sort(collection, n - 1) | sorts |
def insert_next(collection: list, index: int):
# Checks order between adjacent elements
if index >= len(collection) or collection[index - 1] <= collection[index]:
return
# Swaps adjacent elements since they are not in ascending order
collection[index - 1], collection[index] = (
collection[index],
collection[index - 1],
)
insert_next(collection, index + 1) | sorts |
def odd_even_transposition(arr: list) -> list:
arr_size = len(arr)
for _ in range(arr_size):
for i in range(_ % 2, arr_size - 1, 2):
if arr[i + 1] < arr[i]:
arr[i], arr[i + 1] = arr[i + 1], arr[i]
return arr | sorts |
def dutch_national_flag_sort(sequence: list) -> list:
if not sequence:
return []
if len(sequence) == 1:
return list(sequence)
low = 0
high = len(sequence) - 1
mid = 0
while mid <= high:
if sequence[mid] == colors[0]:
sequence[low], sequence[mid] = sequence[mid], sequence[low]
low += 1
mid += 1
elif sequence[mid] == colors[1]:
mid += 1
elif sequence[mid] == colors[2]:
sequence[mid], sequence[high] = sequence[high], sequence[mid]
high -= 1
else:
raise ValueError(
f"The elements inside the sequence must contains only {colors} values"
)
return sequence | sorts |
def pancake_sort(arr):
cur = len(arr)
while cur > 1:
# Find the maximum number in arr
mi = arr.index(max(arr[0:cur]))
# Reverse from 0 to mi
arr = arr[mi::-1] + arr[mi + 1 : len(arr)]
# Reverse whole list
arr = arr[cur - 1 :: -1] + arr[cur : len(arr)]
cur -= 1
return arr | sorts |
def shell_sort(collection: list) -> list:
# Choose an initial gap value
gap = len(collection)
# Set the gap value to be decreased by a factor of 1.3
# after each iteration
shrink = 1.3
# Continue sorting until the gap is 1
while gap > 1:
# Decrease the gap value
gap = int(gap / shrink)
# Sort the elements using insertion sort
for i in range(gap, len(collection)):
temp = collection[i]
j = i
while j >= gap and collection[j - gap] > temp:
collection[j] = collection[j - gap]
j -= gap
collection[j] = temp
return collection | sorts |
def merge(input_list: list, low: int, mid: int, high: int) -> list:
result = []
left, right = input_list[low:mid], input_list[mid : high + 1]
while left and right:
result.append((left if left[0] <= right[0] else right).pop(0))
input_list[low : high + 1] = result + left + right
return input_list | sorts |
def iter_merge_sort(input_list: list) -> list:
if len(input_list) <= 1:
return input_list
input_list = list(input_list)
# iteration for two-way merging
p = 2
while p <= len(input_list):
# getting low, high and middle value for merge-sort of single list
for i in range(0, len(input_list), p):
low = i
high = i + p - 1
mid = (low + high + 1) // 2
input_list = merge(input_list, low, mid, high)
# final merge of last two parts
if p * 2 >= len(input_list):
mid = i
input_list = merge(input_list, 0, mid, len(input_list) - 1)
break
p *= 2
return input_list | sorts |
def insertion_sort(collection: list) -> list:
for insert_index, insert_value in enumerate(collection[1:]):
temp_index = insert_index
while insert_index >= 0 and insert_value < collection[insert_index]:
collection[insert_index + 1] = collection[insert_index]
insert_index -= 1
if insert_index != temp_index:
collection[insert_index + 1] = insert_value
return collection | sorts |
def gnome_sort(lst: list) -> list:
if len(lst) <= 1:
return lst
i = 1
while i < len(lst):
if lst[i - 1] <= lst[i]:
i += 1
else:
lst[i - 1], lst[i] = lst[i], lst[i - 1]
i -= 1
if i == 0:
i = 1
return lst | sorts |
def bubble_sort(collection):
length = len(collection)
for i in range(length - 1):
swapped = False
for j in range(length - 1 - i):
if collection[j] > collection[j + 1]:
swapped = True
collection[j], collection[j + 1] = collection[j + 1], collection[j]
if not swapped:
break # Stop iteration if the collection is sorted.
return collection | sorts |
def stooge_sort(arr):
stooge(arr, 0, len(arr) - 1)
return arr | sorts |
def stooge(arr, i, h):
if i >= h:
return
# If first element is smaller than the last then swap them
if arr[i] > arr[h]:
arr[i], arr[h] = arr[h], arr[i]
# If there are more than 2 elements in the array
if h - i + 1 > 2:
t = (int)((h - i + 1) / 3)
# Recursively sort first 2/3 elements
stooge(arr, i, (h - t))
# Recursively sort last 2/3 elements
stooge(arr, i + t, (h))
# Recursively sort first 2/3 elements
stooge(arr, i, (h - t)) | sorts |
def _in_place_quick_sort(a, start, end):
count = 0
if start < end:
pivot = randint(start, end)
temp = a[end]
a[end] = a[pivot]
a[pivot] = temp
p, count = _in_place_partition(a, start, end)
count += _in_place_quick_sort(a, start, p - 1)
count += _in_place_quick_sort(a, p + 1, end)
return count | sorts |
def _in_place_partition(a, start, end):
count = 0
pivot = randint(start, end)
temp = a[end]
a[end] = a[pivot]
a[pivot] = temp
new_pivot_index = start - 1
for index in range(start, end):
count += 1
if a[index] < a[end]: # check if current val is less than pivot value
new_pivot_index = new_pivot_index + 1
temp = a[new_pivot_index]
a[new_pivot_index] = a[index]
a[index] = temp
temp = a[new_pivot_index + 1]
a[new_pivot_index + 1] = a[end]
a[end] = temp
return new_pivot_index + 1, count | sorts |
def binary_search(lst, item, start, end):
if start == end:
return start if lst[start] > item else start + 1
if start > end:
return start
mid = (start + end) // 2
if lst[mid] < item:
return binary_search(lst, item, mid + 1, end)
elif lst[mid] > item:
return binary_search(lst, item, start, mid - 1)
else:
return mid | sorts |
def insertion_sort(lst):
length = len(lst)
for index in range(1, length):
value = lst[index]
pos = binary_search(lst, value, 0, index - 1)
lst = lst[:pos] + [value] + lst[pos:index] + lst[index + 1 :]
return lst | sorts |
def merge(left, right):
if not left:
return right
if not right:
return left
if left[0] < right[0]:
return [left[0], *merge(left[1:], right)]
return [right[0], *merge(left, right[1:])] | sorts |
def tim_sort(lst):
length = len(lst)
runs, sorted_runs = [], []
new_run = [lst[0]]
sorted_array = []
i = 1
while i < length:
if lst[i] < lst[i - 1]:
runs.append(new_run)
new_run = [lst[i]]
else:
new_run.append(lst[i])
i += 1
runs.append(new_run)
for run in runs:
sorted_runs.append(insertion_sort(run))
for run in sorted_runs:
sorted_array = merge(sorted_array, run)
return sorted_array | sorts |
def main():
lst = [5, 9, 10, 3, -4, 5, 178, 92, 46, -18, 0, 7]
sorted_lst = tim_sort(lst)
print(sorted_lst) | sorts |
def msd_radix_sort(list_of_ints: list[int]) -> list[int]:
if not list_of_ints:
return []
if min(list_of_ints) < 0:
raise ValueError("All numbers must be positive")
most_bits = max(len(bin(x)[2:]) for x in list_of_ints)
return _msd_radix_sort(list_of_ints, most_bits) | sorts |
def _msd_radix_sort(list_of_ints: list[int], bit_position: int) -> list[int]:
if bit_position == 0 or len(list_of_ints) in [0, 1]:
return list_of_ints
zeros = []
ones = []
# Split numbers based on bit at bit_position from the right
for number in list_of_ints:
if (number >> (bit_position - 1)) & 1:
# number has a one at bit bit_position
ones.append(number)
else:
# number has a zero at bit bit_position
zeros.append(number)
# recursively split both lists further
zeros = _msd_radix_sort(zeros, bit_position - 1)
ones = _msd_radix_sort(ones, bit_position - 1)
# recombine lists
res = zeros
res.extend(ones)
return res | sorts |
def msd_radix_sort_inplace(list_of_ints: list[int]):
length = len(list_of_ints)
if not list_of_ints or length == 1:
return
if min(list_of_ints) < 0:
raise ValueError("All numbers must be positive")
most_bits = max(len(bin(x)[2:]) for x in list_of_ints)
_msd_radix_sort_inplace(list_of_ints, most_bits, 0, length) | sorts |
def _msd_radix_sort_inplace(
list_of_ints: list[int], bit_position: int, begin_index: int, end_index: int
):
if bit_position == 0 or end_index - begin_index <= 1:
return
bit_position -= 1
i = begin_index
j = end_index - 1
while i <= j:
changed = False
if not (list_of_ints[i] >> bit_position) & 1:
# found zero at the beginning
i += 1
changed = True
if (list_of_ints[j] >> bit_position) & 1:
# found one at the end
j -= 1
changed = True
if changed:
continue
list_of_ints[i], list_of_ints[j] = list_of_ints[j], list_of_ints[i]
j -= 1
if j != i:
i += 1
_msd_radix_sort_inplace(list_of_ints, bit_position, begin_index, i)
_msd_radix_sort_inplace(list_of_ints, bit_position, i, end_index) | sorts |
def selection_sort(collection):
length = len(collection)
for i in range(length - 1):
least = i
for k in range(i + 1, length):
if collection[k] < collection[least]:
least = k
if least != i:
collection[least], collection[i] = (collection[i], collection[least])
return collection | sorts |
def circle_sort_util(collection: list, low: int, high: int) -> bool:
swapped = False
if low == high:
return swapped
left = low
right = high
while left < right:
if collection[left] > collection[right]:
collection[left], collection[right] = (
collection[right],
collection[left],
)
swapped = True
left += 1
right -= 1
if left == right and collection[left] > collection[right + 1]:
collection[left], collection[right + 1] = (
collection[right + 1],
collection[left],
)
swapped = True
mid = low + int((high - low) / 2)
left_swap = circle_sort_util(collection, low, mid)
right_swap = circle_sort_util(collection, mid + 1, high)
return swapped or left_swap or right_swap | sorts |
def is_sorted(collection):
for i in range(len(collection) - 1):
if collection[i] > collection[i + 1]:
return False
return True | sorts |
def radix_sort(list_of_ints: list[int]) -> list[int]:
placement = 1
max_digit = max(list_of_ints)
while placement <= max_digit:
# declare and initialize empty buckets
buckets: list[list] = [[] for _ in range(RADIX)]
# split list_of_ints between the buckets
for i in list_of_ints:
tmp = int((i / placement) % RADIX)
buckets[tmp].append(i)
# put each buckets' contents into list_of_ints
a = 0
for b in range(RADIX):
for i in buckets[b]:
list_of_ints[a] = i
a += 1
# move to next
placement *= RADIX
return list_of_ints | sorts |
def binary_search_insertion(sorted_list, item):
left = 0
right = len(sorted_list) - 1
while left <= right:
middle = (left + right) // 2
if left == right:
if sorted_list[middle] < item:
left = middle + 1
break
elif sorted_list[middle] < item:
left = middle + 1
else:
right = middle - 1
sorted_list.insert(left, item)
return sorted_list | sorts |
def merge(left, right):
result = []
while left and right:
if left[0][0] < right[0][0]:
result.append(left.pop(0))
else:
result.append(right.pop(0))
return result + left + right | sorts |
def sortlist_2d(list_2d):
length = len(list_2d)
if length <= 1:
return list_2d
middle = length // 2
return merge(sortlist_2d(list_2d[:middle]), sortlist_2d(list_2d[middle:])) | sorts |
def merge_insertion_sort(collection: list[int]) -> list[int]:
if len(collection) <= 1:
return collection
two_paired_list = []
has_last_odd_item = False
for i in range(0, len(collection), 2):
if i == len(collection) - 1:
has_last_odd_item = True
else:
if collection[i] < collection[i + 1]:
two_paired_list.append([collection[i], collection[i + 1]])
else:
two_paired_list.append([collection[i + 1], collection[i]])
sorted_list_2d = sortlist_2d(two_paired_list)
result = [i[0] for i in sorted_list_2d]
result.append(sorted_list_2d[-1][1])
if has_last_odd_item:
pivot = collection[-1]
result = binary_search_insertion(result, pivot)
is_last_odd_item_inserted_before_this_index = False
for i in range(len(sorted_list_2d) - 1):
if result[i] == collection[-1] and has_last_odd_item:
is_last_odd_item_inserted_before_this_index = True
pivot = sorted_list_2d[i][1]
# If last_odd_item is inserted before the item's index,
# you should forward index one more.
if is_last_odd_item_inserted_before_this_index:
result = result[: i + 2] + binary_search_insertion(result[i + 2 :], pivot)
else:
result = result[: i + 1] + binary_search_insertion(result[i + 1 :], pivot)
return result | sorts |
def odd_even_sort(input_list: list) -> list:
is_sorted = False
while is_sorted is False: # Until all the indices are traversed keep looping
is_sorted = True
for i in range(0, len(input_list) - 1, 2): # iterating over all even indices
if input_list[i] > input_list[i + 1]:
input_list[i], input_list[i + 1] = input_list[i + 1], input_list[i]
# swapping if elements not in order
is_sorted = False
for i in range(1, len(input_list) - 1, 2): # iterating over all odd indices
if input_list[i] > input_list[i + 1]:
input_list[i], input_list[i + 1] = input_list[i + 1], input_list[i]
# swapping if elements not in order
is_sorted = False
return input_list | sorts |
def counting_sort(collection):
# if the collection is empty, returns empty
if collection == []:
return []
# get some information about the collection
coll_len = len(collection)
coll_max = max(collection)
coll_min = min(collection)
# create the counting array
counting_arr_length = coll_max + 1 - coll_min
counting_arr = [0] * counting_arr_length
# count how much a number appears in the collection
for number in collection:
counting_arr[number - coll_min] += 1
# sum each position with it's predecessors. now, counting_arr[i] tells
# us how many elements <= i has in the collection
for i in range(1, counting_arr_length):
counting_arr[i] = counting_arr[i] + counting_arr[i - 1]
# create the output collection
ordered = [0] * coll_len
# place the elements in the output, respecting the original order (stable
# sort) from end to begin, updating counting_arr
for i in reversed(range(0, coll_len)):
ordered[counting_arr[collection[i] - coll_min] - 1] = collection[i]
counting_arr[collection[i] - coll_min] -= 1
return ordered | sorts |
def counting_sort_string(string):
return "".join([chr(i) for i in counting_sort([ord(c) for c in string])]) | sorts |
def __init__(self, val):
self.val = val
self.left = None
self.right = None | sorts |
def insert(self, val):
if self.val:
if val < self.val:
if self.left is None:
self.left = Node(val)
else:
self.left.insert(val)
elif val > self.val:
if self.right is None:
self.right = Node(val)
else:
self.right.insert(val)
else:
self.val = val | sorts |
def inorder(root, res):
# Recursive traversal
if root:
inorder(root.left, res)
res.append(root.val)
inorder(root.right, res) | sorts |