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 <= 0:
raise ValueError("principal must be > 0")
return principal * daily_interest_rate * days_between_payments | 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:
raise ValueError("nominal_annual_interest_rate_percentage must be >= 0")
if principal <= 0:
raise ValueError("principal must be > 0")
return principal * (
(1 + nominal_annual_interest_rate_percentage) ** number_of_compounding_periods
- 1
) | 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(years_to_repay, int):
raise Exception("Years to repay must be an integer > 0")
# Yearly rate is divided by 12 to get monthly rate
rate_per_month = rate_per_annum / 12
# Years to repay is multiplied by 12 to get number of payments as payment is monthly
number_of_payments = years_to_repay * 12
return (
principal
* rate_per_month
* (1 + rate_per_month) ** number_of_payments
/ ((1 + rate_per_month) ** number_of_payments - 1)
) | 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
self.burst_time = burst_time # remaining burst time
self.waiting_time = 0 # total time of the process wait in ready queue
self.turnaround_time = 0 # time from arrival time to completion 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
self.time_slices = time_slices
# unfinished process is in this ready_queue
self.ready_queue = queue
# current time
self.current_time = current_time
# finished process is in this sequence queue
self.finish_queue: deque[Process] = deque() | 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 time, update current time
if self.current_time < cp.arrival_time:
self.current_time += cp.arrival_time
# update waiting time of current process
self.update_waiting_time(cp)
# update current time
self.current_time += cp.burst_time
# finish the process and set the process's burst-time 0
cp.burst_time = 0
# set the process's turnaround time because it is finished
cp.turnaround_time = self.current_time - cp.arrival_time
# set the completion time
cp.stop_time = self.current_time
# add the process to queue that has finished queue
finished.append(cp)
self.finish_queue.extend(finished) # add finished process to finish queue
# FCFS will finish all remaining processes
return finished | 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)):
cp = ready_queue.popleft() # current process
# if process's arrival time is later than current time, update current time
if self.current_time < cp.arrival_time:
self.current_time += cp.arrival_time
# update waiting time of unfinished processes
self.update_waiting_time(cp)
# if the burst time of process is bigger than time-slice
if cp.burst_time > time_slice:
# use CPU for only time-slice
self.current_time += time_slice
# update remaining burst time
cp.burst_time -= time_slice
# update end point time
cp.stop_time = self.current_time
# locate the process behind the queue because it is not finished
ready_queue.append(cp)
else:
# use CPU for remaining burst time
self.current_time += cp.burst_time
# set burst time 0 because the process is finished
cp.burst_time = 0
# set the finish time
cp.stop_time = self.current_time
# update the process' turnaround time because it is finished
cp.turnaround_time = self.current_time - cp.arrival_time
# add the process to queue that has finished queue
finished.append(cp)
self.finish_queue.extend(finished) # add finished process to finish queue
# return finished processes queue and remaining processes queue
return finished, 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 queue has first_come_first_served algorithm
self.first_come_first_served(self.ready_queue)
return self.finish_queue | 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 value: value[1])[1]
time_slots = [-1] * max_deadline
# Finding the maximum profit and the count of jobs
count = 0
max_profit = 0
for job in jobs:
# Find a free time slot for this job
# (Note that we start from the last possible slot)
for i in range(job[1] - 1, -1, -1):
if time_slots[i] == -1:
time_slots[i] = job[0]
count += 1
max_profit += job[2]
break
return [count, max_profit] | 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:
done = False
if rem_burst_times[i] > quantum:
t += quantum
rem_burst_times[i] -= quantum
else:
t += rem_burst_times[i]
waiting_times[i] = t - burst_time
rem_burst_times[i] = 0
if done is True:
return waiting_times | 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 performance.
finished_process = [0] * no_of_process
# List to include calculation results
turn_around_time = [0] * no_of_process
# Sort by arrival time.
burst_time = [burst_time[i] for i in np.argsort(arrival_time)]
process_name = [process_name[i] for i in np.argsort(arrival_time)]
arrival_time.sort()
while no_of_process > finished_process_count:
i = 0
while finished_process[i] == 1:
i += 1
if current_time < arrival_time[i]:
current_time = arrival_time[i]
response_ratio = 0
# Index showing the location of the process being performed
loc = 0
# Saves the current response ratio.
temp = 0
for i in range(0, no_of_process):
if finished_process[i] == 0 and arrival_time[i] <= current_time:
temp = (burst_time[i] + (current_time - arrival_time[i])) / burst_time[
i
]
if response_ratio < temp:
response_ratio = temp
loc = i
# Calculate the turn around time
turn_around_time[loc] = current_time + burst_time[loc] - arrival_time[loc]
current_time += burst_time[loc]
# Indicates that the process has been performed.
finished_process[loc] = 1
# Increase finished_process_count by 1
finished_process_count += 1
return turn_around_time | 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] = burst_time[i]
ready_process: list[int] = []
completed = 0
total_time = 0
# When processes are not completed,
# A process whose arrival time has passed \
# and has remaining execution time is put into the ready_process.
# The shortest process in the ready_process, target_process is executed.
while completed != no_of_processes:
ready_process = []
target_process = -1
for i in range(no_of_processes):
if (arrival_time[i] <= total_time) and (remaining_time[i] > 0):
ready_process.append(i)
if len(ready_process) > 0:
target_process = ready_process[0]
for i in ready_process:
if remaining_time[i] < remaining_time[target_process]:
target_process = i
total_time += burst_time[target_process]
completed += 1
remaining_time[target_process] = 0
waiting_time[target_process] = (
total_time - arrival_time[target_process] - burst_time[target_process]
)
else:
total_time += 1
return waiting_time | 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_time[i]
complete = 0
increment_time = 0
minm = 999999999
short = 0
check = False
# Process until all processes are completed
while complete != no_of_processes:
for j in range(no_of_processes):
if arrival_time[j] <= increment_time and remaining_time[j] > 0:
if remaining_time[j] < minm:
minm = remaining_time[j]
short = j
check = True
if not check:
increment_time += 1
continue
remaining_time[short] -= 1
minm = remaining_time[short]
if minm == 0:
minm = 999999999
if remaining_time[short] == 0:
complete += 1
check = False
# Find finish time of current process
finish_time = increment_time + 1
# Calculate waiting time
finar = finish_time - arrival_time[short]
waiting_time[short] = finar - burst_time[short]
if waiting_time[short] < 0:
waiting_time[short] = 0
# Increment time
increment_time += 1
return waiting_time | 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_turn_around_time + turn_around_time[i]
print(f"Average waiting time = {total_waiting_time / no_of_processes:.5f}")
print("Average turn around time =", total_turn_around_time / no_of_processes) | 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_CONVERSION:
raise ValueError(
f"Invalid 'to_type' value: {to_type!r}. Supported values are:\n"
+ ", ".join(PRESSURE_CONVERSION)
)
return (
value * PRESSURE_CONVERSION[from_type].from_ * PRESSURE_CONVERSION[to_type].to
) | 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_inverse)}"
)
return round(speed * speed_chart[unit_from] * speed_chart_inverse[unit_to], 3) | 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()]
unknown_amount: float = known_amount * (
10 ** (known_prefix.value - unknown_prefix.value)
)
return unknown_amount | 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_prefix.lower()]
unknown_amount: float = known_amount * (
2 ** ((known_prefix.value - unknown_prefix.value) * 10)
)
return unknown_amount | 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 hex_string):
raise ValueError("Non-hexadecimal value was passed to the function")
decimal_number = 0
for char in hex_string:
decimal_number = 16 * decimal_number + hex_table[char]
return -decimal_number if is_negative else decimal_number | 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 Exception("value should be between 0 and 1")
chroma = value * saturation
hue_section = hue / 60
second_largest_component = chroma * (1 - abs(hue_section % 2 - 1))
match_value = value - chroma
if hue_section >= 0 and hue_section <= 1:
red = round(255 * (chroma + match_value))
green = round(255 * (second_largest_component + match_value))
blue = round(255 * (match_value))
elif hue_section > 1 and hue_section <= 2:
red = round(255 * (second_largest_component + match_value))
green = round(255 * (chroma + match_value))
blue = round(255 * (match_value))
elif hue_section > 2 and hue_section <= 3:
red = round(255 * (match_value))
green = round(255 * (chroma + match_value))
blue = round(255 * (second_largest_component + match_value))
elif hue_section > 3 and hue_section <= 4:
red = round(255 * (match_value))
green = round(255 * (second_largest_component + match_value))
blue = round(255 * (chroma + match_value))
elif hue_section > 4 and hue_section <= 5:
red = round(255 * (second_largest_component + match_value))
green = round(255 * (match_value))
blue = round(255 * (chroma + match_value))
else:
red = round(255 * (chroma + match_value))
green = round(255 * (match_value))
blue = round(255 * (second_largest_component + match_value))
return [red, green, blue] | 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 between 0 and 255")
float_red = red / 255
float_green = green / 255
float_blue = blue / 255
value = max(max(float_red, float_green), float_blue)
chroma = value - min(min(float_red, float_green), float_blue)
saturation = 0 if value == 0 else chroma / value
if chroma == 0:
hue = 0.0
elif value == float_red:
hue = 60 * (0 + (float_green - float_blue) / chroma)
elif value == float_green:
hue = 60 * (2 + (float_blue - float_red) / chroma)
else:
hue = 60 * (4 + (float_red - float_green) / chroma)
hue = (hue + 360) % 360
return [hue, saturation, value] | 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 ValueError("Invalid value was passed to the function")
bin_str = ""
while int_num > 0:
bin_str = str(int_num % 2) + bin_str
int_num >>= 1
return int(("-" + bin_str) if is_negative else bin_str) | 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}"
return str(value) | 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_CHART)}"
)
return value * KILOGRAM_CHART[to_type] * WEIGHT_TYPE_CHART[from_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")
return f"{negative}0b{binary_recursive(int(number))}" | 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:
bin_string = "0" + bin_string
bin_string_in_3_list = [
bin_string[index : index + 3]
for index in range(len(bin_string))
if index % 3 == 0
]
for bin_group in bin_string_in_3_list:
oct_val = 0
for index, val in enumerate(bin_group):
oct_val += int(2 ** (2 - index) * int(val))
oct_string += str(oct_val)
return oct_string | 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 <= int(char) <= 7 for char in oct_string):
raise ValueError("Non-octal value was passed to the function")
decimal_number = 0
for char in oct_string:
decimal_number = 8 * decimal_number + int(char)
if is_negative:
decimal_number = -decimal_number
return decimal_number | 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[place]]
place += 2
else:
total += vals[roman[place]]
place += 1
return total | 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:
raise ValueError(
f"Invalid 'to_type' value: {to_type!r}. Supported values are:\n"
+ ", ".join(METRIC_CONVERSION)
)
return value * METRIC_CONVERSION[from_type].from_ * METRIC_CONVERSION[to_type].to | 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:
raise ValueError(
f"Invalid 'from_type' value: {from_type!r}.\n"
f"Conversion abbreviations are: {', '.join(METRIC_CONVERSION)}"
)
if new_to not in METRIC_CONVERSION:
raise ValueError(
f"Invalid 'to_type' value: {to_type!r}.\n"
f"Conversion abbreviations are: {', '.join(METRIC_CONVERSION)}"
)
return value * METRIC_CONVERSION[new_from].from_ * METRIC_CONVERSION[new_to].to | 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_sanitized not in METRIC_CONVERSION:
raise ValueError(
f"Invalid 'from_type' value: {from_type!r}.\n"
f"Conversion abbreviations are: {', '.join(METRIC_CONVERSION)}"
)
if to_sanitized not in METRIC_CONVERSION:
raise ValueError(
f"Invalid 'to_type' value: {to_type!r}.\n"
f"Conversion abbreviations are: {', '.join(METRIC_CONVERSION)}"
)
from_exponent = METRIC_CONVERSION[from_sanitized]
to_exponent = METRIC_CONVERSION[to_sanitized]
exponent = 1
if from_exponent > to_exponent:
exponent = from_exponent - to_exponent
else:
exponent = -(to_exponent - from_exponent)
return value * pow(10, exponent) | 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 binary_str
if not all(char in "01" for char in binary_str):
raise ValueError("Non-binary value was passed to the function")
binary_str = (
"0" * (4 * (divmod(len(binary_str), 4)[0] + 1) - len(binary_str)) + binary_str
)
hexadecimal = []
for x in range(0, len(binary_str), 4):
hexadecimal.append(BITS_TO_HEX[binary_str[x : x + 4]])
hexadecimal_str = "0x" + "".join(hexadecimal)
return "-" + hexadecimal_str if is_negative else hexadecimal_str | 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_string):
raise ValueError("Non-binary value was passed to the function")
decimal_number = 0
for char in bin_string:
decimal_number = 2 * decimal_number + int(char)
return -decimal_number if is_negative else decimal_number | 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.listen(5) # Now wait for client connection.
print("Server listening....")
while True:
conn, addr = sock.accept() # Establish connection with client.
print(f"Got connection from {addr}")
data = conn.recv(1024)
print(f"Server received: {data = }")
with open(filename, "rb") as in_file:
data = in_file.read(1024)
while data:
conn.send(data)
print(f"Sent {data!r}")
data = in_file.read(1024)
print("Done sending")
conn.close()
if testing: # Allow the test to complete
break
sock.shutdown(1)
sock.close() | 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 maximum of two cases:
# (1) nth item included
# (2) not included
if weights[counter - 1] > capacity:
return knapsack(capacity, weights, values, counter - 1)
else:
left_capacity = capacity - weights[counter - 1]
new_value_included = values[counter - 1] + knapsack(
left_capacity, weights, values, counter - 1
)
without_new_value = knapsack(capacity, weights, values, counter - 1)
return max(new_value_included, without_new_value) | 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 ValueError("Profit can not be negative.")
if any(w < 0 for w in weight):
raise ValueError("Weight can not be negative.")
# List created to store profit gained for the 1kg in case of each weight
# respectively. Calculate and append profit/weight for each element.
profit_by_weight = [p / w for p, w in zip(profit, weight)]
# Creating a copy of the list and sorting profit/weight in ascending order
sorted_profit_by_weight = sorted(profit_by_weight)
# declaring useful variables
length = len(sorted_profit_by_weight)
limit = 0
gain = 0
i = 0
# loop till the total weight do not reach max limit e.g. 15 kg and till i<length
while limit <= max_weight and i < length:
# flag value for encountered greatest element in sorted_profit_by_weight
biggest_profit_by_weight = sorted_profit_by_weight[length - i - 1]
index = profit_by_weight.index(biggest_profit_by_weight)
profit_by_weight[index] = -1
# check if the weight encountered is less than the total weight
# encountered before.
if max_weight - limit >= weight[index]:
limit += weight[index]
# Adding profit gained for the given weight 1 ===
# weight[index]/weight[index]
gain += 1 * profit[index]
else:
# Since the weight encountered is greater than limit, therefore take the
# required number of remaining kgs and calculate profit for it.
# weight remaining / weight[index]
gain += (max_weight - limit) / weight[index] * profit[index]
break
i += 1
return gain | 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[index] + knapsack(
weights, values, number_of_items, max_weight - weights[index], index + 1
)
return max(ans1, ans2) | 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_inversions = inversion_p + inversions_q + cross_inversions
return c, num_inversions | 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.
num_inversion += len(p) - i
r.append(q[j])
j += 1
else:
r.append(p[i])
i += 1
if i < len(p):
r.extend(p[i:])
else:
r.extend(q[j:])
return r, num_inversion | 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_inversions_recursive == 8
print("number of inversions = ", num_inversions_bf)
# testing an array with zero inversion (a sorted arr_1)
arr_1.sort()
num_inversions_bf = count_inversions_bf(arr_1)
_, num_inversions_recursive = count_inversions_recursive(arr_1)
assert num_inversions_bf == num_inversions_recursive == 0
print("number of inversions = ", num_inversions_bf)
# an empty list should also have zero inversions
arr_1 = []
num_inversions_bf = count_inversions_bf(arr_1)
_, num_inversions_recursive = count_inversions_recursive(arr_1)
assert num_inversions_bf == num_inversions_recursive == 0
print("number of inversions = ", num_inversions_bf) | 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:
points.append(Point(p[0], p[1]))
except (IndexError, TypeError):
print(
f"Ignoring deformed point {p}. All points"
" must have at least 2 coordinates."
)
return points | 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 {points}")
return _construct_points(points) | 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
for k in range(n):
if k != i and k != j:
det_k = _det(points[i], points[j], points[k])
if det_k > 0:
points_left_of_ij = True
elif det_k < 0:
points_right_of_ij = True
else:
# point[i], point[j], point[k] all lie on a straight line
# if point[k] is to the left of point[i] or it's to the
# right of point[j], then point[i], point[j] cannot be
# part of the convex hull of A
if points[k] < points[i] or points[k] > points[j]:
ij_part_of_convex_hull = False
break
if points_left_of_ij and points_right_of_ij:
ij_part_of_convex_hull = False
break
if ij_part_of_convex_hull:
convex_set.update([points[i], points[j]])
return sorted(convex_set) | 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 these two anchors to divide all the points into two hulls,
# an upper hull and a lower hull.
# all points to the left (above) the line joining the extreme points belong to the
# upper hull
# all points to the right (below) the line joining the extreme points below to the
# lower hull
# ignore all points on the line joining the extreme points since they cannot be
# part of the convex hull
left_most_point = points[0]
right_most_point = points[n - 1]
convex_set = {left_most_point, right_most_point}
upper_hull = []
lower_hull = []
for i in range(1, n - 1):
det = _det(left_most_point, right_most_point, points[i])
if det > 0:
upper_hull.append(points[i])
elif det < 0:
lower_hull.append(points[i])
_construct_hull(upper_hull, left_most_point, right_most_point, convex_set)
_construct_hull(lower_hull, right_most_point, left_most_point, convex_set)
return sorted(convex_set) | 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:
candidate_points.append(p)
if det > extreme_point_distance:
extreme_point_distance = det
extreme_point = p
if extreme_point:
_construct_hull(candidate_points, left, extreme_point, convex_set)
convex_set.add(extreme_point)
_construct_hull(candidate_points, extreme_point, right, convex_set) | 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])
break
elif det < 0:
convex_hull.append(points[i])
break
else:
convex_hull[1] = points[i]
i += 1
for j in range(i, n):
if (
_det(convex_hull[0], convex_hull[-1], points[j]) > 0
and _det(convex_hull[-1], convex_hull[0], points[1]) < 0
):
# The point lies within the convex hull
continue
convex_hull.insert(0, points[j])
convex_hull.append(points[j])
while _det(convex_hull[0], convex_hull[1], convex_hull[2]) >= 0:
del convex_hull[1]
while _det(convex_hull[-1], convex_hull[-2], convex_hull[-3]) <= 0:
del convex_hull[-2]
# `convex_hull` is contains the convex hull in circular order
return sorted(convex_hull[1:] if len(convex_hull) > 3 else convex_hull) | 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(points)
results_recursive = convex_hull_recursive(points)
assert results_bf == results_recursive
results_melkman = convex_hull_melkman(points)
assert results_bf == results_melkman
print(results_bf) | 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_cross_array_sum(array, left, mid, right)
return max(left_half_sum, right_half_sum, cross_sum) | 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], arr[k - 1] = arr[k - 1], arr[0]
generate(k - 1, arr) | 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]]
res.append(tuple(arr))
c[i] += 1
i = 0
else:
c[i] = 0
i += 1 | 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)
small2, big2 = max_difference(second)
# get min of first and max of second
# linear time
min_first = min(first)
max_second = max(second)
# 3 cases, either (small1, big1),
# (min_first, max_second), (small2, big2)
# constant comparisons
if big2 - small2 > max_second - min_first and big2 - small2 > big1 - small1:
return small2, big2
elif big1 - small1 > max_second - min_first:
return small1, big1
else:
return min_first, max_second | 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]:
if len(lst[:m]) == 2:
m -= 1
return peak(lst[m:])
# decreasing
else:
if len(lst[:m]) == 2:
m += 1
return peak(lst[:m]) | divide_and_conquer |