function stringlengths 18 3.86k | intent_category stringlengths 5 24 |
|---|---|
def simple_interest(
principal: float, daily_interest_rate: float, days_between_payments: int
) -> float:
if days_between_payments <= 0:
raise ValueError("days_between_payments must be > 0")
if daily_interest_rate < 0:
raise ValueError("daily_interest_rate must be >= 0")
if principal <= ... | financial |
def compound_interest(
principal: float,
nominal_annual_interest_rate_percentage: float,
number_of_compounding_periods: int,
) -> float:
if number_of_compounding_periods <= 0:
raise ValueError("number_of_compounding_periods must be > 0")
if nominal_annual_interest_rate_percentage < 0:
... | financial |
def equated_monthly_installments(
principal: float, rate_per_annum: float, years_to_repay: int
) -> float:
if principal <= 0:
raise Exception("Principal borrowed must be > 0")
if rate_per_annum < 0:
raise Exception("Rate of interest must be >= 0")
if years_to_repay <= 0 or not isinstance... | financial |
def calculate_waiting_times(duration_times: list[int]) -> list[int]:
waiting_times = [0] * len(duration_times)
for i in range(1, len(duration_times)):
waiting_times[i] = duration_times[i - 1] + waiting_times[i - 1]
return waiting_times | scheduling |
def calculate_turnaround_times(
duration_times: list[int], waiting_times: list[int]
) -> list[int]:
return [
duration_time + waiting_times[i]
for i, duration_time in enumerate(duration_times)
] | scheduling |
def calculate_average_turnaround_time(turnaround_times: list[int]) -> float:
return sum(turnaround_times) / len(turnaround_times) | scheduling |
def calculate_average_waiting_time(waiting_times: list[int]) -> float:
return sum(waiting_times) / len(waiting_times) | scheduling |
def __init__(self, process_name: str, arrival_time: int, burst_time: int) -> None:
self.process_name = process_name # process name
self.arrival_time = arrival_time # arrival time of the process
# completion time of finished process or last interrupted time
self.stop_time = arrival_time... | scheduling |
def __init__(
self,
number_of_queues: int,
time_slices: list[int],
queue: deque[Process],
current_time: int,
) -> None:
# total number of mlfq's queues
self.number_of_queues = number_of_queues
# time slice of queues that round robin algorithm applied
... | scheduling |
def calculate_sequence_of_finish_queue(self) -> list[str]:
sequence = []
for i in range(len(self.finish_queue)):
sequence.append(self.finish_queue[i].process_name)
return sequence | scheduling |
def calculate_waiting_time(self, queue: list[Process]) -> list[int]:
waiting_times = []
for i in range(len(queue)):
waiting_times.append(queue[i].waiting_time)
return waiting_times | scheduling |
def calculate_turnaround_time(self, queue: list[Process]) -> list[int]:
turnaround_times = []
for i in range(len(queue)):
turnaround_times.append(queue[i].turnaround_time)
return turnaround_times | scheduling |
def calculate_completion_time(self, queue: list[Process]) -> list[int]:
completion_times = []
for i in range(len(queue)):
completion_times.append(queue[i].stop_time)
return completion_times | scheduling |
def calculate_remaining_burst_time_of_processes(
self, queue: deque[Process]
) -> list[int]:
return [q.burst_time for q in queue] | scheduling |
def update_waiting_time(self, process: Process) -> int:
process.waiting_time += self.current_time - process.stop_time
return process.waiting_time | scheduling |
def first_come_first_served(self, ready_queue: deque[Process]) -> deque[Process]:
finished: deque[Process] = deque() # sequence deque of finished process
while len(ready_queue) != 0:
cp = ready_queue.popleft() # current process
# if process's arrival time is later than current... | scheduling |
def round_robin(
self, ready_queue: deque[Process], time_slice: int
) -> tuple[deque[Process], deque[Process]]:
finished: deque[Process] = deque() # sequence deque of terminated process
# just for 1 cycle and unfinished processes will go back to queue
for _ in range(len(ready_queue)... | scheduling |
def multi_level_feedback_queue(self) -> deque[Process]:
# all queues except last one have round_robin algorithm
for i in range(self.number_of_queues - 1):
finished, self.ready_queue = self.round_robin(
self.ready_queue, self.time_slices[i]
)
# the last ... | scheduling |
def job_sequencing_with_deadlines(num_jobs: int, jobs: list) -> list:
# Sort the jobs in descending order of profit
jobs = sorted(jobs, key=lambda value: value[2], reverse=True)
# Create a list of size equal to the maximum deadline
# and initialize it with -1
max_deadline = max(jobs, key=lambda va... | scheduling |
def calculate_waiting_times(burst_times: list[int]) -> list[int]:
quantum = 2
rem_burst_times = list(burst_times)
waiting_times = [0] * len(burst_times)
t = 0
while True:
done = True
for i, burst_time in enumerate(burst_times):
if rem_burst_times[i] > 0:
d... | scheduling |
def calculate_turn_around_times(
burst_times: list[int], waiting_times: list[int]
) -> list[int]:
return [burst + waiting for burst, waiting in zip(burst_times, waiting_times)] | scheduling |
def calculate_turn_around_time(
process_name: list, arrival_time: list, burst_time: list, no_of_process: int
) -> list:
current_time = 0
# Number of processes finished
finished_process_count = 0
# Displays the finished process.
# If it is 0, the performance is completed if it is 1, before the p... | scheduling |
def calculate_waiting_time(
process_name: list, turn_around_time: list, burst_time: list, no_of_process: int
) -> list:
waiting_time = [0] * no_of_process
for i in range(0, no_of_process):
waiting_time[i] = turn_around_time[i] - burst_time[i]
return waiting_time | scheduling |
def calculate_waitingtime(
arrival_time: list[int], burst_time: list[int], no_of_processes: int
) -> list[int]:
waiting_time = [0] * no_of_processes
remaining_time = [0] * no_of_processes
# Initialize remaining_time to waiting_time.
for i in range(no_of_processes):
remaining_time[i] = bur... | scheduling |
def calculate_turnaroundtime(
burst_time: list[int], no_of_processes: int, waiting_time: list[int]
) -> list[int]:
turn_around_time = [0] * no_of_processes
for i in range(no_of_processes):
turn_around_time[i] = burst_time[i] + waiting_time[i]
return turn_around_time | scheduling |
def calculate_waitingtime(
arrival_time: list[int], burst_time: list[int], no_of_processes: int
) -> list[int]:
remaining_time = [0] * no_of_processes
waiting_time = [0] * no_of_processes
# Copy the burst time into remaining_time[]
for i in range(no_of_processes):
remaining_time[i] = burst_t... | scheduling |
def calculate_turnaroundtime(
burst_time: list[int], no_of_processes: int, waiting_time: list[int]
) -> list[int]:
turn_around_time = [0] * no_of_processes
for i in range(no_of_processes):
turn_around_time[i] = burst_time[i] + waiting_time[i]
return turn_around_time | scheduling |
def calculate_average_times(
waiting_time: list[int], turn_around_time: list[int], no_of_processes: int
) -> None:
total_waiting_time = 0
total_turn_around_time = 0
for i in range(no_of_processes):
total_waiting_time = total_waiting_time + waiting_time[i]
total_turn_around_time = total_t... | scheduling |
def evaluate(item: str, main_target: str = target) -> tuple[str, float]:
score = len(
[g for position, g in enumerate(item) if g == main_target[position]]
)
return (item, float(score)) | genetic_algorithm |
def select(parent_1: tuple[str, float]) -> list[str]:
random_slice = random.randint(0, len(parent_1) - 1)
child_1 = parent_1[:random_slice] + parent_2[random_slice:]
child_2 = parent_2[:random_slice] + parent_1[random_slice:]
return (child_1, child_2) | genetic_algorithm |
def pressure_conversion(value: float, from_type: str, to_type: str) -> float:
if from_type not in PRESSURE_CONVERSION:
raise ValueError(
f"Invalid 'from_type' value: {from_type!r} Supported values are:\n"
+ ", ".join(PRESSURE_CONVERSION)
)
if to_type not in PRESSURE_CONV... | conversions |
def convert_speed(speed: float, unit_from: str, unit_to: str) -> float:
if unit_to not in speed_chart or unit_from not in speed_chart_inverse:
raise ValueError(
f"Incorrect 'from_type' or 'to_type' value: {unit_from!r}, {unit_to!r}\n"
f"Valid values are: {', '.join(speed_chart_invers... | conversions |
def convert_si_prefix(
known_amount: float,
known_prefix: str | SIUnit,
unknown_prefix: str | SIUnit,
) -> float:
if isinstance(known_prefix, str):
known_prefix = SIUnit[known_prefix.lower()]
if isinstance(unknown_prefix, str):
unknown_prefix = SIUnit[unknown_prefix.lower()]
unkn... | conversions |
def convert_binary_prefix(
known_amount: float,
known_prefix: str | BinaryUnit,
unknown_prefix: str | BinaryUnit,
) -> float:
if isinstance(known_prefix, str):
known_prefix = BinaryUnit[known_prefix.lower()]
if isinstance(unknown_prefix, str):
unknown_prefix = BinaryUnit[unknown_pref... | conversions |
def hex_to_decimal(hex_string: str) -> int:
hex_string = hex_string.strip().lower()
if not hex_string:
raise ValueError("Empty string was passed to the function")
is_negative = hex_string[0] == "-"
if is_negative:
hex_string = hex_string[1:]
if not all(char in hex_table for char in h... | conversions |
def hsv_to_rgb(hue: float, saturation: float, value: float) -> list[int]:
if hue < 0 or hue > 360:
raise Exception("hue should be between 0 and 360")
if saturation < 0 or saturation > 1:
raise Exception("saturation should be between 0 and 1")
if value < 0 or value > 1:
raise Except... | conversions |
def rgb_to_hsv(red: int, green: int, blue: int) -> list[float]:
if red < 0 or red > 255:
raise Exception("red should be between 0 and 255")
if green < 0 or green > 255:
raise Exception("green should be between 0 and 255")
if blue < 0 or blue > 255:
raise Exception("blue should be b... | conversions |
def hex_to_bin(hex_num: str) -> int:
hex_num = hex_num.strip()
if not hex_num:
raise ValueError("No value was passed to the function")
is_negative = hex_num[0] == "-"
if is_negative:
hex_num = hex_num[1:]
try:
int_num = int(hex_num, 16)
except ValueError:
raise... | conversions |
def get_positive(cls: type[T]) -> dict:
return {unit.name: unit.value for unit in cls if unit.value > 0} | conversions |
def get_negative(cls: type[T]) -> dict:
return {unit.name: unit.value for unit in cls if unit.value < 0} | conversions |
def add_si_prefix(value: float) -> str:
prefixes = SIUnit.get_positive() if value > 0 else SIUnit.get_negative()
for name_prefix, value_prefix in prefixes.items():
numerical_part = value / (10**value_prefix)
if numerical_part > 1:
return f"{str(numerical_part)} {name_prefix}"
ret... | conversions |
def add_binary_prefix(value: float) -> str:
for prefix in BinaryUnit:
numerical_part = value / (2**prefix.value)
if numerical_part > 1:
return f"{str(numerical_part)} {prefix.name}"
return str(value) | conversions |
def weight_conversion(from_type: str, to_type: str, value: float) -> float:
if to_type not in KILOGRAM_CHART or from_type not in WEIGHT_TYPE_CHART:
raise ValueError(
f"Invalid 'from_type' or 'to_type' value: {from_type!r}, {to_type!r}\n"
f"Supported values are: {', '.join(WEIGHT_TYPE... | conversions |
def binary_recursive(decimal: int) -> str:
decimal = int(decimal)
if decimal in (0, 1): # Exit cases for the recursion
return str(decimal)
div, mod = divmod(decimal, 2)
return binary_recursive(div) + str(mod) | conversions |
def main(number: str) -> str:
number = str(number).strip()
if not number:
raise ValueError("No input value was provided")
negative = "-" if number.startswith("-") else ""
number = number.lstrip("-")
if not number.isnumeric():
raise ValueError("Input value is not an integer")
retu... | conversions |
def bin_to_octal(bin_string: str) -> str:
if not all(char in "01" for char in bin_string):
raise ValueError("Non-binary value was passed to the function")
if not bin_string:
raise ValueError("Empty string was passed to the function")
oct_string = ""
while len(bin_string) % 3 != 0:
... | conversions |
def oct_to_decimal(oct_string: str) -> int:
oct_string = str(oct_string).strip()
if not oct_string:
raise ValueError("Empty string was passed to the function")
is_negative = oct_string[0] == "-"
if is_negative:
oct_string = oct_string[1:]
if not oct_string.isdigit() or not all(0 <= i... | conversions |
def molarity_to_normality(nfactor: int, moles: float, volume: float) -> float:
return round(float(moles / volume) * nfactor) | conversions |
def moles_to_pressure(volume: float, moles: float, temperature: float) -> float:
return round(float((moles * 0.0821 * temperature) / (volume))) | conversions |
def moles_to_volume(pressure: float, moles: float, temperature: float) -> float:
return round(float((moles * 0.0821 * temperature) / (pressure))) | conversions |
def pressure_and_volume_to_temperature(
pressure: float, moles: float, volume: float
) -> float:
return round(float((pressure * volume) / (0.0821 * moles))) | conversions |
def excel_title_to_column(column_title: str) -> int:
assert column_title.isupper()
answer = 0
index = len(column_title) - 1
power = 0
while index >= 0:
value = (ord(column_title[index]) - 64) * pow(26, power)
answer += value
power += 1
index -= 1
return answer | conversions |
def roman_to_int(roman: str) -> int:
vals = {"I": 1, "V": 5, "X": 10, "L": 50, "C": 100, "D": 500, "M": 1000}
total = 0
place = 0
while place < len(roman):
if (place + 1 < len(roman)) and (vals[roman[place]] < vals[roman[place + 1]]):
total += vals[roman[place + 1]] - vals[roman[plac... | conversions |
def int_to_roman(number: int) -> str:
result = []
for arabic, roman in ROMAN:
(factor, number) = divmod(number, arabic)
result.append(roman * factor)
if number == 0:
break
return "".join(result) | conversions |
def volume_conversion(value: float, from_type: str, to_type: str) -> float:
if from_type not in METRIC_CONVERSION:
raise ValueError(
f"Invalid 'from_type' value: {from_type!r} Supported values are:\n"
+ ", ".join(METRIC_CONVERSION)
)
if to_type not in METRIC_CONVERSION:
... | conversions |
def length_conversion(value: float, from_type: str, to_type: str) -> float:
new_from = from_type.lower().rstrip("s")
new_from = TYPE_CONVERSION.get(new_from, new_from)
new_to = to_type.lower().rstrip("s")
new_to = TYPE_CONVERSION.get(new_to, new_to)
if new_from not in METRIC_CONVERSION:
rais... | conversions |
def length_conversion(value: float, from_type: str, to_type: str) -> float:
from_sanitized = from_type.lower().strip("s")
to_sanitized = to_type.lower().strip("s")
from_sanitized = UNIT_SYMBOL.get(from_sanitized, from_sanitized)
to_sanitized = UNIT_SYMBOL.get(to_sanitized, to_sanitized)
if from_s... | conversions |
def bin_to_hexadecimal(binary_str: str) -> str:
# Sanitising parameter
binary_str = str(binary_str).strip()
# Exceptions
if not binary_str:
raise ValueError("Empty string was passed to the function")
is_negative = binary_str[0] == "-"
binary_str = binary_str[1:] if is_negative else bina... | conversions |
def bin_to_decimal(bin_string: str) -> int:
bin_string = str(bin_string).strip()
if not bin_string:
raise ValueError("Empty string was passed to the function")
is_negative = bin_string[0] == "-"
if is_negative:
bin_string = bin_string[1:]
if not all(char in "01" for char in bin_strin... | conversions |
def send_file(filename: str = "mytext.txt", testing: bool = False) -> None:
import socket
port = 12312 # Reserve a port for your service.
sock = socket.socket() # Create a socket object
host = socket.gethostname() # Get local machine name
sock.bind((host, port)) # Bind to the port
sock.list... | file_transfer |
def knapsack(capacity: int, weights: list[int], values: list[int], counter: int) -> int:
# Base Case
if counter == 0 or capacity == 0:
return 0
# If weight of the nth item is more than Knapsack of capacity,
# then this item cannot be included in the optimal solution,
# else return the ma... | knapsack |
def calc_profit(profit: list, weight: list, max_weight: int) -> int:
if len(profit) != len(weight):
raise ValueError("The length of profit and weight must be same.")
if max_weight <= 0:
raise ValueError("max_weight must greater than zero.")
if any(p < 0 for p in profit):
raise ValueE... | knapsack |
def knapsack(
weights: list, values: list, number_of_items: int, max_weight: int, index: int
) -> int:
if index == number_of_items:
return 0
ans1 = 0
ans2 = 0
ans1 = knapsack(weights, values, number_of_items, max_weight, index + 1)
if weights[index] <= max_weight:
ans2 = values[i... | knapsack |
def test_base_case(self):
cap = 0
val = [0]
w = [0]
c = len(val)
self.assertEqual(k.knapsack(cap, w, val, c), 0)
val = [60]
w = [10]
c = len(val)
self.assertEqual(k.knapsack(cap, w, val, c), 0) | knapsack |
def test_easy_case(self):
cap = 3
val = [1, 2, 3]
w = [3, 2, 1]
c = len(val)
self.assertEqual(k.knapsack(cap, w, val, c), 5) | knapsack |
def test_knapsack(self):
cap = 50
val = [60, 100, 120]
w = [10, 20, 30]
c = len(val)
self.assertEqual(k.knapsack(cap, w, val, c), 220) | knapsack |
def test_sorted(self):
profit = [10, 20, 30, 40, 50, 60]
weight = [2, 4, 6, 8, 10, 12]
max_weight = 100
self.assertEqual(kp.calc_profit(profit, weight, max_weight), 210) | knapsack |
def test_negative_max_weight(self):
# profit = [10, 20, 30, 40, 50, 60]
# weight = [2, 4, 6, 8, 10, 12]
# max_weight = -15
self.assertRaisesRegex(ValueError, "max_weight must greater than zero.") | knapsack |
def test_negative_profit_value(self):
# profit = [10, -20, 30, 40, 50, 60]
# weight = [2, 4, 6, 8, 10, 12]
# max_weight = 15
self.assertRaisesRegex(ValueError, "Weight can not be negative.") | knapsack |
def test_negative_weight_value(self):
# profit = [10, 20, 30, 40, 50, 60]
# weight = [2, -4, 6, -8, 10, 12]
# max_weight = 15
self.assertRaisesRegex(ValueError, "Profit can not be negative.") | knapsack |
def test_null_max_weight(self):
# profit = [10, 20, 30, 40, 50, 60]
# weight = [2, 4, 6, 8, 10, 12]
# max_weight = null
self.assertRaisesRegex(ValueError, "max_weight must greater than zero.") | knapsack |
def test_unequal_list_length(self):
# profit = [10, 20, 30, 40, 50]
# weight = [2, 4, 6, 8, 10, 12]
# max_weight = 100
self.assertRaisesRegex(
IndexError, "The length of profit and weight must be same."
) | knapsack |
def count_inversions_bf(arr):
num_inversions = 0
n = len(arr)
for i in range(n - 1):
for j in range(i + 1, n):
if arr[i] > arr[j]:
num_inversions += 1
return num_inversions | divide_and_conquer |
def count_inversions_recursive(arr):
if len(arr) <= 1:
return arr, 0
mid = len(arr) // 2
p = arr[0:mid]
q = arr[mid:]
a, inversion_p = count_inversions_recursive(p)
b, inversions_q = count_inversions_recursive(q)
c, cross_inversions = _count_cross_inversions(a, b)
num_inversion... | divide_and_conquer |
def _count_cross_inversions(p, q):
r = []
i = j = num_inversion = 0
while i < len(p) and j < len(q):
if p[i] > q[j]:
# if P[1] > Q[j], then P[k] > Q[k] for all i < k <= len(P)
# These are all inversions. The claim emerges from the
# property that P is sorted.
... | divide_and_conquer |
def main():
arr_1 = [10, 2, 1, 5, 5, 2, 11]
# this arr has 8 inversions:
# (10, 2), (10, 1), (10, 5), (10, 5), (10, 2), (2, 1), (5, 2), (5, 2)
num_inversions_bf = count_inversions_bf(arr_1)
_, num_inversions_recursive = count_inversions_recursive(arr_1)
assert num_inversions_bf == num_inversi... | divide_and_conquer |
def __init__(self, x, y):
self.x, self.y = float(x), float(y) | divide_and_conquer |
def __eq__(self, other):
return self.x == other.x and self.y == other.y | divide_and_conquer |
def __ne__(self, other):
return not self == other | divide_and_conquer |
def __gt__(self, other):
if self.x > other.x:
return True
elif self.x == other.x:
return self.y > other.y
return False | divide_and_conquer |
def __lt__(self, other):
return not self > other | divide_and_conquer |
def __ge__(self, other):
if self.x > other.x:
return True
elif self.x == other.x:
return self.y >= other.y
return False | divide_and_conquer |
def __le__(self, other):
if self.x < other.x:
return True
elif self.x == other.x:
return self.y <= other.y
return False | divide_and_conquer |
def __repr__(self):
return f"({self.x}, {self.y})" | divide_and_conquer |
def __hash__(self):
return hash(self.x) | divide_and_conquer |
def _construct_points(
list_of_tuples: list[Point] | list[list[float]] | Iterable[list[float]],
) -> list[Point]:
points: list[Point] = []
if list_of_tuples:
for p in list_of_tuples:
if isinstance(p, Point):
points.append(p)
else:
try:
... | divide_and_conquer |
def _validate_input(points: list[Point] | list[list[float]]) -> list[Point]:
if not hasattr(points, "__iter__"):
raise ValueError(
f"Expecting an iterable object but got an non-iterable type {points}"
)
if not points:
raise ValueError(f"Expecting a list of points but got {p... | divide_and_conquer |
def _det(a: Point, b: Point, c: Point) -> float:
det = (a.x * b.y + b.x * c.y + c.x * a.y) - (a.y * b.x + b.y * c.x + c.y * a.x)
return det | divide_and_conquer |
def convex_hull_bf(points: list[Point]) -> list[Point]:
points = sorted(_validate_input(points))
n = len(points)
convex_set = set()
for i in range(n - 1):
for j in range(i + 1, n):
points_left_of_ij = points_right_of_ij = False
ij_part_of_convex_hull = True
... | divide_and_conquer |
def convex_hull_recursive(points: list[Point]) -> list[Point]:
points = sorted(_validate_input(points))
n = len(points)
# divide all the points into an upper hull and a lower hull
# the left most point and the right most point are definitely
# members of the convex hull by definition.
# use the... | divide_and_conquer |
def _construct_hull(
points: list[Point], left: Point, right: Point, convex_set: set[Point]
) -> None:
if points:
extreme_point = None
extreme_point_distance = float("-inf")
candidate_points = []
for p in points:
det = _det(left, right, p)
if det > 0:
... | divide_and_conquer |
def convex_hull_melkman(points: list[Point]) -> list[Point]:
points = sorted(_validate_input(points))
n = len(points)
convex_hull = points[:2]
for i in range(2, n):
det = _det(convex_hull[1], convex_hull[0], points[i])
if det > 0:
convex_hull.insert(0, points[i])
... | divide_and_conquer |
def main():
points = [
(0, 3),
(2, 2),
(1, 1),
(2, 1),
(3, 0),
(0, 0),
(3, 3),
(2, -1),
(2, -4),
(1, -3),
]
# the convex set of points is
# [(0, 0), (0, 3), (1, -3), (2, -4), (3, 0), (3, 3)]
results_bf = convex_hull_bf(p... | divide_and_conquer |
def max_sum_from_start(array):
array_sum = 0
max_sum = float("-inf")
for num in array:
array_sum += num
if array_sum > max_sum:
max_sum = array_sum
return max_sum | divide_and_conquer |
def max_cross_array_sum(array, left, mid, right):
max_sum_of_left = max_sum_from_start(array[left : mid + 1][::-1])
max_sum_of_right = max_sum_from_start(array[mid + 1 : right + 1])
return max_sum_of_left + max_sum_of_right | divide_and_conquer |
def max_subarray_sum(array, left, right):
# base case: array has only one element
if left == right:
return array[right]
# Recursion
mid = (left + right) // 2
left_half_sum = max_subarray_sum(array, left, mid)
right_half_sum = max_subarray_sum(array, mid + 1, right)
cross_sum = max_... | divide_and_conquer |
def generate(k: int, arr: list):
if k == 1:
res.append(tuple(arr[:]))
return
generate(k - 1, arr)
for i in range(k - 1):
if k % 2 == 0: # k is even
arr[i], arr[k - 1] = arr[k - 1], arr[i]
else: # k is odd
arr[0],... | divide_and_conquer |
def generate(n: int, arr: list):
c = [0] * n
res.append(tuple(arr))
i = 0
while i < n:
if c[i] < i:
if i % 2 == 0:
arr[0], arr[i] = arr[i], arr[0]
else:
arr[c[i]], arr[i] = arr[i], arr[c[i]]
... | divide_and_conquer |
def max_difference(a: list[int]) -> tuple[int, int]:
# base case
if len(a) == 1:
return a[0], a[0]
else:
# split A into half.
first = a[: len(a) // 2]
second = a[len(a) // 2 :]
# 2 sub problems, 1/2 of original size.
small1, big1 = max_difference(first)
... | divide_and_conquer |
def peak(lst: list[int]) -> int:
# middle index
m = len(lst) // 2
# choose the middle 3 elements
three = lst[m - 1 : m + 2]
# if middle element is peak
if three[1] > three[0] and three[1] > three[2]:
return three[1]
# if increasing, recurse on right
elif three[0] < three[2]:
... | divide_and_conquer |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.