source stringclasses 6
values | id int64 0 111k | instruction stringlengths 167 4.39k | response stringlengths 244 6.1k |
|---|---|---|---|
code_exercise_27k | 23,872 | Write a Python function to merge two JSON dictionaries and update any duplicate keys with their combined values. If a key exists in both dictionaries, the value in the merged dictionary should be the sum of the values from both dictionaries. If a key exists only in one dictionary, it should be included in the merged di... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Dict
def merge_json_dicts(dict1: Dict[str, int], dict2: Dict[str, int]) -> Dict[str, int]:
"""
Merge two JSON dictionaries and update any duplicate keys with their combined values.
Args:
dict1 (D... |
code_exercise_27k | 23,923 | Write a Python function to count the occurrences of a specific value in a nested JSON-like structure. The structure can contain lists and dictionaries, and the value can be nested within these structures. The function should recursively traverse the structure to count all occurrences of the specified value.
The code s... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Any, Union
def count_occurrences_in_json(json_structure: Union[list, dict], value: Any) -> int:
"""
Count the occurrences of a specific value in a nested JSON-like structure.
Args:
json_structure... |
code_exercise_27k | 24,049 | Write a Python function to find the maximum product subarray in an array of non-negative integers. The function should efficiently handle the case where the array contains zeros, which reset the product subarray. The code should start with:
```python
from typing import List
def max_product_subarray(nums: List[int]) ->... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def max_product_subarray(nums: List[int]) -> int:
"""
Finds the maximum product subarray in an array of non-negative integers.
Args:
nums (List[int]): The input array of non-negative integer... |
code_exercise_27k | 24,089 | Write a Python function to check if two binary trees are identical. Two binary trees are considered identical if they have the same structure and the same values at each node. The function should take the roots of the two binary trees as input and return `True` if the trees are identical, and `False` otherwise.
The co... | Here is the Python code to solve the given problem in the markdown block:
```python
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def are_identical_trees(root1: TreeNode, root2: TreeNode) -> bool:
"""
Check if tw... |
code_exercise_27k | 24,104 | Write a Python function to merge two JSON objects into a single object. The function should handle nested dictionaries and merge them recursively. If both objects have the same key, the value from the second object should overwrite the value from the first object. The function should raise a `TypeError` if either of th... | Here is the Python code to solve the given problem in the markdown block:
```python
def merge_json_objects(obj1: dict, obj2: dict) -> dict:
"""
Merge two JSON objects (represented as dictionaries) into a single object.
If both objects have the same key, the value from the second object will overwrite the va... |
code_exercise_27k | 24,105 | Write a Python function to generate the Fibonacci series up to a given number `n`. The function should return a list containing the Fibonacci series up to `n`. The code should start with:
```python
from typing import List
def generate_fibonacci_series(n: int) -> List[int]:
```
| Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def generate_fibonacci_series(n: int) -> List[int]:
"""
Generate the Fibonacci series up to a given number `n`.
Args:
n (int): The number up to which the Fibonacci series will be generated.
... |
code_exercise_27k | 24,111 | Write a Python function to extract all keys from a deeply nested JSON object. The JSON object can contain nested dictionaries and lists. The function should return a list of all keys found in the JSON object, including those in nested dictionaries.
The code should start with:
```python
from typing import List, Union
... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Union
def extract_all_keys(data: Union[dict, list]) -> List[str]:
"""
Extracts all keys from a deeply nested JSON object.
Args:
data (Union[dict, list]): The JSON object to extract keys fro... |
code_exercise_27k | 24,112 | Write a Python function to determine if a given number is a power of two using bitwise operations. The function should return `True` if the number is a power of two, and `False` otherwise. The code should start with:
```python
def is_power_of_two_bitwise(number: int) -> bool:
```
| Here is the Python code to solve the given problem in the markdown block:
```python
def is_power_of_two_bitwise(number: int) -> bool:
"""
Determine if a given number is a power of two using bitwise operations.
Parameters:
number (int): The number to check.
Returns:
bool: True if the number is ... |
code_exercise_27k | 24,121 | Write a Python function to calculate the sum of all numbers in a given list. The function should handle lists containing integers, floats, and a mix of both. The code should start with:
```python
from typing import List, Union
def calculate_sum(numbers: List[Union[int, float]]) -> Union[int, float]:
```
| Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Union
def calculate_sum(numbers: List[Union[int, float]]) -> Union[int, float]:
"""
Calculate the sum of all numbers in a given list.
Args:
numbers (List[Union[int, float]]): A list of numb... |
code_exercise_27k | 24,135 | Write a Python function to sort a list of numbers in descending order using the merge sort algorithm. The merge sort algorithm should be implemented from scratch without using Python's built-in sorting functions. The function should start with:
```python
from typing import List
def merge_sort_descending(nums: List[int... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def merge_sort_descending(nums: List[int]) -> List[int]:
"""
Sorts a list of numbers in descending order using the merge sort algorithm.
Args:
nums (List[int]): A list of numbers to be sorte... |
code_exercise_27k | 24,148 | Write a Python function to recursively extract all values for a given key at all levels of nested JSON objects. The JSON object can be a dictionary or a list containing dictionaries and lists. The function should handle any level of nesting and return a list of all values corresponding to the given key.
The code shoul... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Any, List, Dict
def extract_values(obj: Any, key: str) -> List[Any]:
"""
Recursively extracts all values for a given key at all levels of nested JSON objects.
Args:
obj (Any): The JSON object to ... |
code_exercise_27k | 24,153 | Write a Python function to calculate the average of all numbers in a given list. The function should handle the case where the input list is empty by returning `None` instead of raising an exception.
The code should start with:
```python
from typing import List, Optional
def calculate_average(numbers: List[int]) -> O... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Optional
def calculate_average(numbers: List[int]) -> Optional[float]:
"""
Calculates the average of all the numbers in a list.
Args:
numbers (List[int]): A list of integers.
Returns:
... |
code_exercise_27k | 24,155 | Write a Python function to replace multiple occurrences of a specific value in a nested JSON object. The JSON object can be a dictionary or a list, and it may contain nested dictionaries and lists. The function should recursively traverse the JSON object and replace all occurrences of the specified old value with the n... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Union
def replace_value_in_nested_json(json_obj: Union[dict, list], old_value, new_value) -> Union[dict, list]:
"""
Replace all occurrences of a specific value in a nested JSON object.
Args:
json... |
code_exercise_27k | 24,157 | Write a Python function to find the maximum and minimum elements in a list without using built-in functions like `min()` and `max()`. The function should handle lists of integers and floats. The code should start with:
```python
from typing import List, Tuple
def find_max_min_elements(lst: List[float]) -> Tuple[float,... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Tuple
def find_max_min_elements(lst: List[float]) -> Tuple[float, float]:
"""
Find the maximum and minimum elements in a list of numeric values.
Args:
lst (List[float]): A list of numeric v... |
code_exercise_27k | 24,223 | Write a Python function to generate the first n prime numbers. The function should use a helper function to check if a number is prime. The code should start with:
```python
from typing import List
def is_prime(n: int) -> bool:
"""
Check if a number is prime.
Parameters:
n (int): Number to check for p... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def is_prime(n: int) -> bool:
"""
Check if a number is prime.
Parameters:
n (int): Number to check for primality.
Returns:
bool: True if the number is prime, False otherwise.
"""
... |
code_exercise_27k | 24,231 | Write a Python function to reverse the words in a given sentence without using the built-in `reverse` function or any other built-in functions that directly reverse a list or string. The function should handle sentences with multiple spaces between words and leading/trailing spaces.
The code should start with:
```pyth... | Here is the Python code to solve the given problem in the markdown block:
```python
def reverse_words_in_sentence(sentence: str) -> str:
"""
Reverse the words in a given sentence without using built-in reverse functions.
Args:
sentence (str): The input sentence whose words are to be reversed.
... |
code_exercise_27k | 24,235 | Write a Python function to determine if a given number is a perfect number. A perfect number is a positive integer that is equal to the sum of its proper divisors (excluding itself). The function should return `True` if the number is perfect and `False` otherwise. The code should start with:
```python
def is_perfect_nu... | Here is the Python code to solve the given problem in the markdown block:
```python
def is_perfect_number(number: int) -> bool:
"""
Determine if a given number is a perfect number.
A perfect number is a positive integer that is equal to the sum of its proper divisors (excluding itself).
Args:
... |
code_exercise_27k | 24,239 | Write a Python function to find the maximum subarray sum of a given list of integers. The function should return the maximum sum of any contiguous subarray within the list. The code should start with:
```python
from typing import List
def max_subarray_sum(lst: List[int]) -> int:
```
| Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def max_subarray_sum(lst: List[int]) -> int:
"""
Calculate the maximum subarray sum of a given list of integers.
Args:
lst (List[int]): The list of integers to find the maximum subarray sum.... |
code_exercise_27k | 24,249 | Write a Python function to find the smallest number that can be divided evenly by all numbers from 1 to n. The function should use the least common multiple (LCM) of the numbers to achieve this. The code should start with:
```python
def smallest_multiple(n: int) -> int:
```
| Here is the Python code to solve the given problem in the markdown block:
```python
def smallest_multiple(n: int) -> int:
"""
Find the smallest number that can be divided evenly by all numbers from 1 to n.
Args:
n (int): The highest number to consider.
Returns:
int: The smallest number... |
code_exercise_27k | 24,312 | Write a Python function to find the length of the last word in a given string without using the built-in `split` function. The function should handle strings with multiple spaces and leading/trailing spaces. The code should start with:
```python
def find_last_word_length(string: str) -> int:
```
| Here is the Python code to solve the given problem in the markdown block:
```python
def find_last_word_length(string: str) -> int:
"""
Finds the length of the last word in a given string without using the built-in split function.
Args:
string (str): The input string from which to find the length of... |
code_exercise_27k | 24,315 | Write a Python function to calculate the number of unique paths from the top-left corner to the bottom-right corner in an m x n grid, where you can only move down or right. The function should start with:
```python
def unique_paths(m: int, n: int) -> int:
```
| Here is the Python code to solve the given problem in the markdown block:
```python
def unique_paths(m: int, n: int) -> int:
"""
Calculate the number of unique paths from the top-left corner to the bottom-right corner in an m x n grid.
Args:
m (int): Number of rows in the grid.
n (int):... |
code_exercise_27k | 24,322 | Write a Python function to find the largest rectangular area in a histogram given a list of heights of bars. The function should handle the following constraints:
- The input list should not be empty.
- The input list should not contain negative values.
- The function should return the largest rectangular area that can... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def largest_rectangular_area(heights: List[int]) -> int:
"""
Find the largest rectangular area in a histogram.
Parameters:
heights (list): A list of heights of bars in the histogram.
Return... |
code_exercise_27k | 24,325 | Write a Python function to find a peak element in a given list. A peak element is defined as an element that is greater than its neighbors. If the list has multiple peaks, return any one of them. The list is not necessarily sorted, and it may contain duplicate values. The function should handle edge cases such as an em... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Optional
def find_peak_element(nums: List[int]) -> Optional[int]:
"""
Finds a peak element in a given list. A peak element is an element that is greater than its neighbors.
Args:
nums (... |
code_exercise_27k | 24,339 | Write a Python function to find the length of the longest common subsequence (LCS) of two given strings. The function should use dynamic programming to efficiently compute the result. The code should start with:
```python
def longest_common_subsequence_length(str1: str, str2: str) -> int:
```
| Here is the Python code to solve the given problem in the markdown block:
```python
def longest_common_subsequence_length(str1: str, str2: str) -> int:
"""
Calculate the length of the longest common subsequence (LCS) of two strings.
Args:
str1 (str): The first input string.
str2 (str): The ... |
code_exercise_27k | 24,341 | Write a Python function to find the minimum number of coins needed to make a given amount of change, given a list of coin denominations. The function should return the minimum number of coins required to make the exact change. If it is not possible to make the exact change with the given denominations, the function sho... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def min_coin_change(coins: List[int], amount: int) -> int:
"""
Calculate the minimum number of coins needed to make a given amount of change.
Args:
coins (List[int]): List of coin denominati... |
code_exercise_27k | 24,364 | Write a Python function to find the length of the longest increasing subsequence (LIS) in a given list of integers. The function should return the length of the LIS.
The code should start with:
```python
from typing import List
def longest_increasing_subsequence_length(nums: List[int]) -> int:
```
| Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def longest_increasing_subsequence_length(nums: List[int]) -> int:
"""
Finds the length of the longest increasing subsequence in a given list.
Args:
nums (List[int]): The input list of integ... |
code_exercise_27k | 24,379 | Write a Python function to implement the Sieve of Eratosthenes algorithm to find all prime numbers up to a given limit. The function should return a list of prime numbers. The code should start with:
```python
from typing import List
def find_primes_up_to(limit: int) -> List[int]:
```
| Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def find_primes_up_to(limit: int) -> List[int]:
"""
Find all prime numbers up to a given limit using the Sieve of Eratosthenes algorithm.
Args:
limit (int): The upper limit up to which to fi... |
code_exercise_27k | 24,387 | Write a Python function to calculate the Manhattan distance between two points in two-dimensional space. The function should accept two tuples representing the coordinates of the points and return the Manhattan distance as an integer or float. The code should start with:
```python
def manhattan_distance(p1: tuple, p2: ... | Here is the Python code to solve the given problem in the markdown block:
```python
def manhattan_distance(p1: tuple, p2: tuple) -> float:
"""
Calculate the Manhattan distance between two points in two-dimensional space.
Args:
p1 (tuple): A tuple representing the coordinates of the first point (x1,... |
code_exercise_27k | 24,422 | Write a Python function to calculate the shortest distance between a point and a rectangle in two-dimensional space. The rectangle is defined by two diagonal corner points, and the point is defined by its coordinates. The function should return the shortest distance between the point and any part of the rectangle.
The... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Tuple
import math
def shortest_distance_point_to_rectangle(point: Tuple[float, float], rect: Tuple[Tuple[float, float], Tuple[float, float]]) -> float:
"""
Calculate the shortest distance between a point and ... |
code_exercise_27k | 24,423 | Write a Python function to perform a left join on two JSON objects based on a common key. The function should merge the two JSON objects such that all key-value pairs from the first JSON object are included, and only the key-value pairs from the second JSON object that do not conflict with the common key are added. If ... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Dict
def left_join_json_objects(json_obj1: Dict, json_obj2: Dict, common_key: str) -> Dict:
"""
Perform a left join on two JSON objects based on a common key.
Args:
json_obj1 (dict): The first JS... |
code_exercise_27k | 24,435 | Write a Python function to calculate the shortest distance between two points in three-dimensional space. The function should accept two tuples representing the coordinates of the points and return the distance as a float. The code should start with:
```python
from typing import Tuple
import math
def calculate_3d_dist... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Tuple
import math
def calculate_3d_distance(point1: Tuple[float, float, float], point2: Tuple[float, float, float]) -> float:
"""
Calculate the shortest distance between two points in three-dimensional space.... |
code_exercise_27k | 24,438 | Write a Python function to perform a full join on two JSON objects based on a common key. The function should merge the two JSON objects such that if a key exists in both objects, the value should be a list containing both values. If a key exists only in one of the objects, it should be included in the result with its ... | Here is the Python code to solve the given problem in the markdown block:
```python
def full_join(json1: dict, json2: dict, common_key: str) -> dict:
"""
Perform a full join on two JSON objects based on a common key.
Args:
json1 (dict): The first JSON object.
json2 (dict): The second JSON o... |
code_exercise_27k | 24,443 | Write a Python function to extract all unique keys from a nested JSON object. The JSON object can be a dictionary or a list, and it may contain nested dictionaries and lists. The function should return a set of all unique keys found in the JSON object, including those in nested structures.
The code should start with:
... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Union, List, Dict
def extract_all_keys(json_obj: Union[Dict, List]) -> set:
"""
Extracts all unique keys from a nested JSON object.
Args:
json_obj (Union[Dict, List]): The JSON object to extract ... |
code_exercise_27k | 24,456 | Write a Python function to count the number of occurrences of each element in a given list and return the results as a dictionary where the keys are the elements and the values are their respective counts.
The code should start with:
```python
from typing import List, Dict
def count_elements(lst: List) -> Dict:
```
| Here is the Python code to solve the given problem in the markdown block:
:
```python
from typing import List, Dict
def count_elements(lst: List) -> Dict:
"""
Count the number of occurrences of each element in a list and return the results as a dictionary.
Args:
lst (list): The list to count the o... |
code_exercise_27k | 24,460 | Write a Python function to calculate the length of a list without using the built-in `len()` function. The function should iterate through the list and count the number of elements manually.
The code should start with:
```python
from typing import List
def calculate_list_length(lst: List) -> int:
```
| Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def calculate_list_length(lst: List) -> int:
"""
Calculates the length of a list without using the built-in len() function.
Args:
lst (List): The list for which the length needs to be calcul... |
code_exercise_27k | 24,462 | Write a Python function to merge two lists such that the resulting list contains all elements from both lists in alternating order. If one list is longer than the other, the remaining elements of the longer list should be appended at the end.
The code should start with:
```python
from typing import List
def merge_lis... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def merge_lists_alternating(list1: List[int], list2: List[int]) -> List[int]:
"""
Merges two lists such that the resulting list contains all elements from both lists in alternating order.
If one list... |
code_exercise_27k | 24,468 | Write a Python function to find the maximum element in a list of numbers. The function should handle an empty list by raising a `ValueError`. The code should start with:
```python
from typing import List, Union
def find_max_element(lst: List[Union[int, float]]) -> Union[int, float]:
```
| Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Union
def find_max_element(lst: List[Union[int, float]]) -> Union[int, float]:
"""
Find the maximum element in a list of numbers.
Args:
lst (List[Union[int, float]]): A list of numbers.
... |
code_exercise_27k | 24,472 | Write a Python function to find the minimum element in a list of numbers. The function should handle an empty list by raising a `ValueError`. The code should start with:
```python
from typing import List, Union
def find_minimum(numbers: List[Union[int, float]]) -> Union[int, float]:
```
| Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Union
def find_minimum(numbers: List[Union[int, float]]) -> Union[int, float]:
"""
Finds the minimum element in a list of numbers.
Args:
numbers (List[Union[int, float]]): A list of numbers... |
code_exercise_27k | 24,474 | Write a Python function to check if two lists are identical, meaning they have the same elements in the same order. The function should return `True` if the lists are identical and `False` otherwise. The code should start with:
```python
from typing import List
def are_lists_identical(list1: List[int], list2: List[int... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def are_lists_identical(list1: List[int], list2: List[int]) -> bool:
"""
Check if two lists are identical, meaning they have the same elements in the same order.
Args:
list1 (List[int]): The... |
code_exercise_27k | 24,480 | Write a Python function to calculate the shortest distance between two sets of points in two-dimensional space. Each set of points is represented as a list of tuples, where each tuple contains the coordinates of a point. The function should compute the Euclidean distance between each pair of points from the two sets an... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Tuple
import math
from itertools import product
def euclidean_distance(point1: Tuple[float, float], point2: Tuple[float, float]) -> float:
"""
Calculate the Euclidean distance between two points in two-... |
code_exercise_27k | 24,483 | Write a Python function to remove the nth element from a given list. If the index `n` is out of range, the function should return the original list without any changes. The function should not raise any exceptions.
The code should start with:
```python
from typing import List
def remove_nth_element(lst: List[int], n:... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def remove_nth_element(lst: List[int], n: int) -> List[int]:
"""
Removes the nth element from a given list. If the index is out of range,
the original list is returned without any changes.
Args:... |
code_exercise_27k | 24,491 | Write a Python function to count the frequency of each element in a given list and store the results in a dictionary. The function should handle lists with any type of elements, including integers, strings, and other data types. The code should start with:
```python
from typing import List, Dict, Any
def count_element... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Dict, Any
def count_element_frequency(lst: List[Any]) -> Dict[Any, int]:
"""
Count the frequency of each element in a given list and store the results in a dictionary.
Args:
lst (List[Any])... |
code_exercise_27k | 24,497 | Write a Python function to reverse the order of elements in a given list. The function should return a new list with the elements in reverse order without modifying the original list. The code should start with:
```python
from typing import List
def reverse_list(lst: List) -> List:
```
| Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def reverse_list(lst: List) -> List:
"""
Reverse the order of elements in a given list.
Parameters:
lst (list): The input list to be reversed.
Returns:
list: A new list with the element... |
code_exercise_27k | 24,515 | Write a Python function to find the mode(s) of a given list of integers. The mode is the value(s) that appears most frequently in the list. If there are multiple values with the same highest frequency, the function should return all of them. The function should handle lists with a single mode, multiple modes, and an em... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def find_mode(lst: List[int]) -> List[int]:
"""
Returns the mode(s) of a given list of integers.
The mode of a list is the value(s) that appears most frequently. If there are multiple values
wit... |
code_exercise_27k | 24,520 | Write a Python function to flatten a deeply nested JSON object into a single-level JSON object. The function should handle both nested dictionaries and lists, and use a specified delimiter to concatenate keys at different levels. The code should start with:
```python
from typing import Dict, Any
def flatten_json(neste... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Dict, Any
def flatten_json(nested_json: Dict[str, Any], delimiter: str = '_') -> Dict[str, Any]:
"""
Flatten a deeply nested JSON object into a single-level JSON object.
Args:
nested_json (dict):... |
code_exercise_27k | 24,522 | Write a Python function to partition a list into two separate lists based on a given condition. The function should take a list and a callable (function) as input and return a tuple containing two lists. The first list should contain items that satisfy the condition, and the second list should contain items that do not... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Callable, Tuple
def partition_list(lst: List, condition: Callable) -> Tuple[List, List]:
"""
Partition a list into two separate lists based on a given condition.
Args:
lst (List): The origi... |
code_exercise_27k | 24,526 | Write a Python function to merge two sorted lists into a single sorted list. The function should efficiently combine the elements from both lists while maintaining the sorted order. The code should start with:
```python
from typing import List
def merge_sorted_lists(list1: List[int], list2: List[int]) -> List[int]:
``... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def merge_sorted_lists(list1: List[int], list2: List[int]) -> List[int]:
"""
Merge two sorted lists into a single sorted list.
Args:
list1 (List[int]): The first sorted list.
list2 (... |
code_exercise_27k | 24,529 | Write a Python function to perform a binary search on a sorted list and return the index of the target value. If the target value is not found, return -1. The function should handle edge cases such as an empty list or a target value that is outside the range of the list.
The code should start with:
```python
from typi... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def binary_search(arr: List[int], target: int) -> int:
"""
Perform binary search on a sorted list to find the index of the target value.
Args:
arr (List[int]): The sorted list to search in.
... |
code_exercise_27k | 24,534 | Write a Python function to calculate the nth Fibonacci number using dynamic programming. The function should be efficient and avoid redundant calculations by storing previously computed Fibonacci numbers in a list. The code should start with:
```python
def fibonacci(n: int) -> int:
```
| Here is the Python code to solve the given problem in the markdown block:
```python
def fibonacci(n: int) -> int:
"""
Calculate the nth Fibonacci number using dynamic programming.
Args:
n (int): The position of the Fibonacci number to be calculated.
Returns:
int: The nth Fibonacci numb... |
code_exercise_27k | 24,541 | Write a Python function to find the minimum number of coins required to make a given amount using a given set of coin denominations. The function should return the minimum number of coins needed, or -1 if it is not possible to make the amount with the given denominations. The code should start with:
```python
from typi... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def find_minimum_coins(coins: List[int], amount: int) -> int:
"""
Finds the minimum number of coins required to make a given amount using a given set of coin denominations.
Args:
coins (List... |
code_exercise_27k | 24,544 | Write a Python function to find the longest common subsequence (LCS) between two given strings. The function should return the LCS as a string. The code should start with:
```python
def longest_common_subsequence(str1: str, str2: str) -> str:
```
| Here is the Python code to solve the given problem in the markdown block:
```python
def longest_common_subsequence(str1: str, str2: str) -> str:
"""
Find the Longest Common Subsequence (LCS) between two strings.
Args:
str1 (str): The first input string.
str2 (str): The second input string.
... |
code_exercise_27k | 24,549 | Write a Python function to calculate the shortest distance and path between two cities on a map using Dijkstra's algorithm. The map is represented as a dictionary where keys are cities and values are dictionaries containing the neighboring cities and their distances. The function should return the shortest distance and... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Dict, List, Tuple, Union
import heapq
def calculate_shortest_distance(graph: Dict[str, Dict[str, float]], start_city: str, end_city: str) -> Union[Tuple[float, List[str]], None]:
"""
Calculates the shortest d... |
code_exercise_27k | 24,552 | Write a Python function to solve the 0/1 knapsack problem using dynamic programming. The function should take three parameters: a list of values for each item, a list of weights for each item, and the maximum capacity of the knapsack. The function should return the maximum value that can be obtained without exceeding t... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def knapsack_problem(values: List[int], weights: List[int], capacity: int) -> int:
"""
Solves the 0/1 knapsack problem using dynamic programming.
Args:
values (List[int]): A list of values f... |
code_exercise_27k | 24,561 | Write a Python function to calculate the shortest distance between two points in a 2D plane using the Euclidean distance formula. The function should accept four parameters representing the coordinates of the two points and return the distance as a floating-point number. The code should start with:
```python
import mat... | Here is the Python code to solve the given problem in the markdown block:
```python
import math
def calculate_shortest_distance(x1: float, y1: float, x2: float, y2: float) -> float:
"""
Calculate the shortest distance between two points in a 2D plane using the Euclidean distance formula.
Args:
x1 ... |
code_exercise_27k | 24,575 | Write a Python function to count the number of ways to reach the top of a staircase with a given number of steps and a list of possible step sizes. The function should use dynamic programming to optimize the solution and avoid redundant calculations.
The code should start with:
```python
from typing import List
def c... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def count_ways_to_reach_top(n: int, step_sizes: List[int]) -> int:
"""
Count the number of ways to reach the top of a staircase with given step sizes using dynamic programming.
Args:
n (int)... |
code_exercise_27k | 24,579 | Write a Python function to solve the coin change problem using dynamic programming. The function should calculate the minimum number of coins needed to make up a given amount using the provided denominations. If it is impossible to make up the amount with the given coins, the function should return -1.
The code should... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def min_coins_needed(coins: List[int], amount: int) -> int:
"""
Calculates the minimum number of coins needed to make up the given amount using the provided denominations.
Args:
coins (List[... |
code_exercise_27k | 24,590 | Write a Python function to find the longest common substring between two given strings. The function should return the longest substring that appears in both strings. If there is no common substring, the function should return an empty string.
The code should start with:
```python
def longest_common_substring(s1: str,... | Here is the Python code to solve the given problem in the markdown block:
```python
def longest_common_substring(s1: str, s2: str) -> str:
"""
Find the longest common substring between two given strings.
Args:
s1 (str): The first input string.
s2 (str): The second input string.
Returns... |
code_exercise_27k | 24,594 | Write a Python function to calculate the Euclidean distance between two points in a 2D plane. The function should accept two tuples, each containing the x and y coordinates of a point, and return the distance between these two points. The function should also include input validation to ensure that the input arguments ... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Tuple
import math
def calculate_euclidean_distance(point1: Tuple[float, float], point2: Tuple[float, float]) -> float:
"""
Calculate the Euclidean distance between two points in a 2D plane.
Args:
... |
code_exercise_27k | 24,600 | Write a Python function to count the number of ways to reach the bottom-right corner of a grid with obstacles. The grid is represented as a 2D list where `0` denotes an empty cell and `1` denotes an obstacle. The function should start with:
```python
from typing import List
def count_paths_with_obstacles(grid: List[Li... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def count_paths_with_obstacles(grid: List[List[int]]) -> int:
"""
Count the number of ways to reach the bottom-right corner of a grid with obstacles.
Args:
grid (List[List[int]]): The grid r... |
code_exercise_27k | 24,605 | Write a Python function to calculate the shortest distance between two points in a weighted graph using Dijkstra's algorithm. The graph is represented as an adjacency list where each key is a node and the value is a dictionary of neighboring nodes with their respective weights. The function should return the shortest d... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Dict, Union
import heapq
def shortest_distance(graph: Dict[str, Dict[str, int]], start: str, end: str) -> Union[int, float]:
"""
Calculates the shortest distance between two points in a weighted graph using D... |
code_exercise_27k | 24,631 | Write a Python function to calculate the shortest distance between two points in a 2D plane using the Euclidean distance formula. The function should take two tuples representing the coordinates of the points and return the distance as a float. The code should start with:
```python
from typing import Tuple
import math
... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Tuple
import math
def calculate_euclidean_distance(point1: Tuple[float, float], point2: Tuple[float, float]) -> float:
"""
Calculate the Euclidean distance between two points in a 2D plane.
Args:
... |
code_exercise_27k | 24,634 | Write a Python function to calculate the number of unique paths in an `m x n` grid from the top-left corner to the bottom-right corner. The function should only move right or down at any point in time. The code should start with:
```python
def unique_paths(m: int, n: int) -> int:
```
| Here is the Python code to solve the given problem in the markdown block:
```python
def unique_paths(m: int, n: int) -> int:
"""
Calculate the number of unique paths in an m x n grid from the top-left to the bottom-right corner.
Args:
m (int): The number of rows in the grid.
n (int): The nu... |
code_exercise_27k | 24,640 | Write a Python function to calculate the shortest distance between two points in a 2D plane using the Euclidean distance formula. The function should handle input validation to ensure that the points are provided as tuples and have the same number of dimensions. The code should start with:
```python
from typing import ... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Tuple
import math
def calculate_shortest_distance(point1: Tuple[float, float], point2: Tuple[float, float]) -> float:
"""
Calculate the shortest distance between two points in a 2D plane using the Euclidean d... |
code_exercise_27k | 24,642 | Write a Python function to calculate the maximum profit that can be obtained by buying and selling stocks given their prices on different days. The function should take a list of integers representing the stock prices on different days and return an integer representing the maximum profit. The function should handle ed... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def max_profit(prices: List[int]) -> int:
"""
Calculate the maximum profit that can be obtained by buying and selling stocks.
Args:
prices (List[int]): A list of integers representing the st... |
code_exercise_27k | 24,643 | Write a Python function to calculate the shortest distance between two points in a 2D plane using the Euclidean distance formula. The function should take two tuples representing the coordinates of the points and return the distance as a float. The code should start with:
```python
from typing import Tuple
import math
... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Tuple
import math
def calculate_shortest_distance(point1: Tuple[float, float], point2: Tuple[float, float]) -> float:
"""
Calculate the shortest distance between two points in a 2D plane using the Euclidean d... |
code_exercise_27k | 24,646 | Write a Python function to find the longest palindromic substring in a given string using dynamic programming. The function should return the longest palindromic substring found in the input string.
The code should start with:
```python
def longest_palindromic_substring(s: str) -> str:
```
| Here is the Python code to solve the given problem in the markdown block:
```python
def longest_palindromic_substring(s: str) -> str:
"""
Compute and return the longest palindromic substring in a given string using dynamic programming.
Args:
s (str): The input string.
Returns:
str: The... |
code_exercise_27k | 24,647 | Write a Python function to calculate the shortest distance between two points in a 2D plane using the Euclidean distance formula. The function should take four parameters representing the coordinates of the two points and return the distance as a floating-point number. The code should start with:
```python
import math
... | Here is the Python code to solve the given problem in the markdown block:
```python
import math
def calculate_shortest_distance(x1: float, y1: float, x2: float, y2: float) -> float:
"""
Calculates the shortest distance between two points in a 2D plane using the Euclidean distance formula.
Args:
x1... |
code_exercise_27k | 24,659 | Write a Python function to find the minimum sum difference between two subsets of a given set of integers. The function should partition the set into two subsets such that the difference between the sums of the two subsets is minimized.
The code should start with:
```python
from typing import List
def find_min_sum_pa... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def find_min_sum_partition(nums: List[int]) -> int:
"""
Finds the minimum sum difference between two subsets of a given set of integers.
Args:
nums (List[int]): List of integers representing... |
code_exercise_27k | 24,662 | Write a Python function to calculate the shortest distance between two points in a 2D plane using the Euclidean distance formula. The function should take four arguments representing the coordinates of the two points and return the distance as a float. The code should start with:
```python
import math
def calculate_eu... | Here is the Python code to solve the given problem in the markdown block:
```python
import math
def calculate_euclidean_distance(x1: float, y1: float, x2: float, y2: float) -> float:
"""
Calculate the Euclidean distance between two points (x1, y1) and (x2, y2) in a 2D plane.
Args:
x1 (float): The ... |
code_exercise_27k | 24,680 | Write a Python function to calculate the shortest path between two points in a graph using Dijkstra's algorithm. The function should return the shortest path as a list of nodes from the start node to the end node. If no path exists, the function should return an empty list.
The code should start with:
```python
from t... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Dict, List, Tuple
import heapq
def calculate_shortest_path(graph: Dict[str, Dict[str, int]], start: str, end: str) -> List[str]:
"""
Calculate the shortest path between two points in a graph using Dijkstra's ... |
code_exercise_27k | 24,683 | Write a Python function to calculate the shortest distance between two points in a 2D space. The function should handle points represented as tuples of length 2, and it should return the Euclidean distance between the two points. The function should also include input validation to ensure that the points are tuples of ... | Here is the Python code to solve the given problem in the markdown block:
```python
import math
def calculate_distance(point1: tuple, point2: tuple) -> float:
"""
Calculate the shortest distance between two points in a 2D space.
Args:
point1 (tuple): The coordinates of the first point in the form ... |
code_exercise_27k | 24,684 | Write a Python function to find the longest common subsequence (LCS) between three given strings. The function should return the LCS as a string. The code should start with:
```python
def longest_common_subsequence_of_three(string1: str, string2: str, string3: str) -> str:
```
| Here is the Python code to solve the given problem in the markdown block:
```python
def longest_common_subsequence_of_three(string1: str, string2: str, string3: str) -> str:
"""
Finds the longest common subsequence between three strings.
Args:
string1 (str): The first string.
string2 (str):... |
code_exercise_27k | 24,699 | Write a Python function to find the longest common subarray between two given arrays using dynamic programming. The function should return the length of the longest common subarray. The code should start with:
```python
from typing import List
def longest_common_subarray(arr1: List[int], arr2: List[int]) -> int:
```
| Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def longest_common_subarray(arr1: List[int], arr2: List[int]) -> int:
"""
Find the length of the longest common subarray between two arrays using dynamic programming.
Args:
arr1 (List[int]):... |
code_exercise_27k | 24,706 | Write a Python function to calculate the shortest distance between two points in a dataset using the Euclidean distance metric. The dataset is a list of points, where each point is represented as a list of coordinates. The function should take three arguments: the dataset, the first point, and the second point. The fun... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
import math
def calculate_shortest_distance(points: List[List[float]], point1: List[float], point2: List[float]) -> float:
"""
Calculate the shortest distance between two points in a dataset using the Eu... |
code_exercise_27k | 24,709 | Write a Python function to calculate the shortest distance between two points in a 2D space using the Euclidean distance formula. The function should take two tuples representing the coordinates of the points and return the distance as a float. The code should start with:
```python
from typing import Tuple
import math
... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Tuple
import math
def calculate_shortest_distance(point1: Tuple[float, float], point2: Tuple[float, float]) -> float:
"""
Calculates the shortest distance between two points in a 2D space using the Euclidean ... |
code_exercise_27k | 24,711 | Write a Python function to calculate the shortest distance between two points in a 2D plane using the Euclidean distance formula. The function should handle points represented as tuples of two integers. The code should start with:
```python
from typing import Tuple
import math
def calculate_shortest_distance(point1: T... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Tuple
import math
def calculate_shortest_distance(point1: Tuple[int, int], point2: Tuple[int, int]) -> float:
"""
Calculate the shortest distance between two points in a 2D plane using the Euclidean distance ... |
code_exercise_27k | 24,719 | Write a Python function to calculate the shortest distance between two points in a 2D plane using the Euclidean distance formula. The function should take two tuples representing the coordinates of the points and return the distance as a float. The code should start with:
```python
from typing import Tuple
import math
... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Tuple
import math
def calculate_euclidean_distance(point1: Tuple[float, float], point2: Tuple[float, float]) -> float:
"""
Calculate the shortest distance between two points in a 2D plane using the Euclidean ... |
code_exercise_27k | 24,727 | Write a Python function to calculate the shortest distance between two points in a 2D plane using the Euclidean distance formula. The function should handle points represented as tuples of two integers or floats. The code should start with:
```python
from typing import Tuple
def euclidean_distance(point1: Tuple[float,... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Tuple
import math
def euclidean_distance(point1: Tuple[float, float], point2: Tuple[float, float]) -> float:
"""
Calculate the Euclidean distance between two points in a 2D plane.
Args:
point1 (T... |
code_exercise_27k | 24,732 | Write a Python function to calculate the Euclidean distance between two points in a multi-dimensional space. The function should handle points with any number of dimensions and ensure that both points have the same number of dimensions. If the points have different dimensions, the function should raise a `ValueError`.
... | Here is the Python code to solve the given problem in the markdown block:
```python
import math
from typing import Tuple
def calculate_euclidean_distance(point1: Tuple[float, ...], point2: Tuple[float, ...]) -> float:
"""
Calculate the Euclidean distance between two points in a multi-dimensional space.
Ar... |
code_exercise_27k | 24,736 | Write a Python function to calculate the shortest distance between two points in a 2D plane using the Euclidean distance formula. The function should take two tuples representing the coordinates of the points and return the distance as a float. The code should start with:
```python
from typing import Tuple
import math
... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Tuple
import math
def calculate_shortest_distance(point1: Tuple[float, float], point2: Tuple[float, float]) -> float:
"""
Calculate the shortest distance between two points in a 2D plane using the Euclidean d... |
code_exercise_27k | 24,741 | Write a Python function to calculate the shortest distance between two points in a 2D plane using the Euclidean distance formula. The function should take four parameters representing the coordinates of the two points and return the distance as a float. The code should start with:
```python
import math
def calculate_s... | Here is the Python code to solve the given problem in the markdown block:
```python
import math
def calculate_shortest_distance(x1: float, y1: float, x2: float, y2: float) -> float:
"""
Calculates the shortest distance between two points (x1, y1) and (x2, y2) using the Euclidean distance formula.
Args:
... |
code_exercise_27k | 24,747 | Write a Python function to find the minimum number of operations required to convert one string to another using insertion, deletion, and substitution operations. The function should use dynamic programming to achieve this.
The code should start with:
```python
def min_edit_distance(str1: str, str2: str) -> int:
```
| Here is the Python code to solve the given problem in the markdown block:
```python
def min_edit_distance(str1: str, str2: str) -> int:
"""
Calculate the minimum number of operations required to convert one string to another.
The operations allowed are insertion, deletion, and substitution.
Args:
... |
code_exercise_27k | 24,757 | Write a Python function to calculate the Levenshtein distance between two strings. The Levenshtein distance is defined as the minimum number of single-character edits (insertions, deletions, or substitutions) required to change one string into the other. The function should be efficient and use dynamic programming to a... | Here is the Python code to solve the given problem in the markdown block:
```python
import numpy as np
def levenshtein_distance(str1: str, str2: str) -> int:
"""
Calculate the Levenshtein distance between two strings.
The Levenshtein distance is the minimum number of single-character edits
(insertions... |
code_exercise_27k | 24,774 | Write a Python function to calculate the shortest distance between two points in a 2D plane using the Euclidean distance formula. The function should take four parameters representing the coordinates of the two points and return the distance as a floating-point number.
The code should start with:
```python
import math... | Here is the Python code to solve the given problem in the markdown block:
```python
import math
def calculate_euclidean_distance(x1: float, y1: float, x2: float, y2: float) -> float:
"""
Calculate the Euclidean distance between two points (x1, y1) and (x2, y2) in a 2D plane.
Args:
x1 (float): The ... |
code_exercise_27k | 24,787 | Write a Python function to calculate the shortest distance between two points in a 2D plane using the Euclidean distance formula. The function should take two tuples representing the coordinates of the points and return the distance as a float. The code should start with:
```python
from typing import Tuple
import math
... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Tuple
import math
def calculate_shortest_distance(point1: Tuple[float, float], point2: Tuple[float, float]) -> float:
"""
Calculate the shortest distance between two points in a 2D plane using the Euclidean d... |
code_exercise_27k | 24,809 | Write a Python function to compute the minimum value from a list of numbers. The function should handle empty lists and non-numeric values by raising appropriate exceptions. The code should start with:
```python
from typing import List, Union
def compute_minimum(numbers: List[Union[int, float]]) -> Union[int, float]:
... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Union
def compute_minimum(numbers: List[Union[int, float]]) -> Union[int, float]:
"""
Compute the minimum value from a list of numbers.
Args:
numbers (List[Union[int, float]]): List of numb... |
code_exercise_27k | 24,820 | Write a Python function to compute the Greatest Common Divisor (GCD) of two numbers using the Euclidean algorithm. The function should handle only positive integers and should not raise any exceptions. The code should start with:
```python
def compute_gcd(a: int, b: int) -> int:
```
| Here is the Python code to solve the given problem in the markdown block:
```python
def compute_gcd(a: int, b: int) -> int:
"""
Compute the Greatest Common Divisor (GCD) of two positive integers using the Euclidean algorithm.
Args:
a (int): The first positive integer.
b (int): The second po... |
code_exercise_27k | 24,826 | Write a Python function to calculate the number of unique elements in a given list. The function should efficiently handle lists of various sizes and types of elements, including nested lists and tuples. The function should also handle cases where the input list contains elements that are themselves lists or tuples, tr... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Tuple, Any
def flatten_list(lst: List[Any]) -> List[Any]:
"""
Recursively flattens a list, including nested lists and tuples.
Args:
lst (list): The list to flatten.
Returns:
li... |
code_exercise_27k | 24,828 | Write a Python function to calculate the number of distinct prime factors of a given number `n`. The function should efficiently determine the prime factors and count their distinct occurrences.
The code should start with:
```python
def count_distinct_prime_factors(n: int) -> int:
```
| Here is the Python code to solve the given problem in the markdown block:
```python
def count_distinct_prime_factors(n: int) -> int:
"""
Calculate the number of distinct prime factors of a given number.
Args:
n (int): The number to calculate the distinct prime factors for.
Returns:
int... |
code_exercise_27k | 24,835 | Write a Python function to find the length of the longest increasing subsequence (LIS) in a given list of integers. The function should return the length of the LIS, not the subsequence itself.
The code should start with:
```python
from typing import List
def longest_increasing_subsequence_length(nums: List[int]) -> ... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def longest_increasing_subsequence_length(nums: List[int]) -> int:
"""
Calculate the length of the longest increasing subsequence in a given list of integers.
Args:
nums (List[int]): A list ... |
code_exercise_27k | 24,876 | Write a Python function to find the longest common subarray with at least `k` elements in any order, allowing skipping elements, mismatches, and swaps. The function should return the longest common subarray that meets these criteria.
The code should start with:
```python
from typing import List
from collections import... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
from collections import Counter
from itertools import combinations
def longest_common_subarray(arr1: List[int], arr2: List[int], k: int) -> List[int]:
"""
Finds the longest common subarray with at least ... |
code_exercise_27k | 24,910 | Write a Python function to tokenize a given string into words, considering various delimiters such as spaces, commas, periods, and other punctuation marks. The function should handle multiple consecutive delimiters by treating them as a single delimiter. The code should start with:
```python
from typing import List
imp... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
import re
def tokenize_string(text: str) -> List[str]:
"""
Tokenizes a given string into words, considering various delimiters such as spaces, commas, periods, and other punctuation marks.
Args:
... |
code_exercise_27k | 24,914 | Write a Python function to tokenize a given string into alphanumeric tokens, ensuring that each token is either entirely alphabetic or entirely numeric. The function should handle various cases, including strings with mixed characters, punctuation, and spaces.
The code should start with:
```python
import re
from typin... | Here is the Python code to solve the given problem in the markdown block:
```python
import re
from typing import List
def tokenize_string(string: str) -> List[str]:
"""
Tokenize a given string into alphanumeric tokens.
This function uses regular expressions to find sequences of alphanumeric characters
... |
code_exercise_27k | 24,918 | Write a Python function to tokenize a given string into individual characters, while also handling special cases such as empty strings and strings with only whitespace characters. The function should return a list of characters, with each character representing a token. The code should start with:
```python
from typing... | Here is the Python code to solve the given problem in the markdown block:
:
```python
from typing import List
def tokenize_string(string: str) -> List[str]:
"""
Tokenizes the given string into individual characters.
Args:
string (str): The input string to tokenize.
Returns:
List[str]:... |
code_exercise_27k | 24,923 | Write a Python function to count the frequency of each word in a given string after tokenization. The function should handle punctuation and case sensitivity by converting all words to lowercase and ignoring punctuation marks. The code should start with:
```python
from typing import Dict
def count_word_frequency(strin... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Dict
import re
from collections import Counter
def count_word_frequency(string: str) -> Dict[str, int]:
"""
Count the frequency of each word in a given string after tokenization.
This function tokenizes ... |
code_exercise_27k | 24,941 | Write a Python function to determine if a directed graph is acyclic. The graph is represented as a dictionary where keys are vertices and values are lists of vertices that the key vertex points to. The function should return `True` if the graph is acyclic and `False` otherwise.
The code should start with:
```python
fr... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Dict, List
def is_acyclic_graph(graph: Dict[int, List[int]]) -> bool:
"""
Determine if a directed graph is acyclic.
Args:
graph (Dict[int, List[int]]): A dictionary representing the directed grap... |
code_exercise_27k | 24,949 | Write a Python function to find the vertex with the maximum out-degree in a directed graph. The graph is represented as a dictionary where keys are vertex names and values are lists of adjacent vertex names. If there are multiple vertices with the same maximum out-degree, the function should return the first one encoun... | Here is the Python code to solve the given problem in the markdown block:
```python
def find_vertex_with_max_outdegree(graph: dict) -> str:
"""
Find the vertex with the maximum out-degree in a directed graph.
Parameters:
graph (dict): A dictionary representing the graph.
The k... |
code_exercise_27k | 24,965 | Write a Python function to find the nth Fibonacci number using dynamic programming. The function should handle non-negative integer inputs and return the corresponding Fibonacci number. The code should start with:
```python
def fibonacci_dp(n: int) -> int:
```
| Here is the Python code to solve the given problem in the markdown block:
```python
def fibonacci_dp(n: int) -> int:
"""
Calculates the nth Fibonacci number using dynamic programming.
Args:
n (int): The index of the Fibonacci number to be calculated.
Returns:
int: The nth Fibonacci num... |
code_exercise_27k | 24,968 | Write a Python function to compute the factorial of a given number using dynamic programming. The function should handle non-negative integers only and should return the factorial of the input number. The code should start with:
```python
def factorial_dp(n: int) -> int:
```
| Here is the Python code to solve the given problem in the markdown block:
```python
def factorial_dp(n: int) -> int:
"""
Compute the factorial of a given number using dynamic programming.
Args:
n (int): The number for which the factorial is to be computed.
Returns:
int: The factorial o... |
code_exercise_27k | 24,978 | Write a Python function to find the length of the longest common subsequence (LCS) between two given strings. The function should use dynamic programming to efficiently compute the result. The code should start with:
```python
def longest_common_subsequence_length(str1: str, str2: str) -> int:
```
| Here is the Python code to solve the given problem in the markdown block:
```python
def longest_common_subsequence_length(str1: str, str2: str) -> int:
"""
Calculates the length of the longest common subsequence between two strings.
Args:
str1 (str): The first string.
str2 (str): The second str... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.