response_seed stringlengths 53 5.17k | instruction_seed stringlengths 29 4.02k | response stringlengths 16 8.81k | __original_row_idx int64 0 50k |
|---|---|---|---|
The instruction indicates that we should add braces to each line in a string, so we can use the `splitlines()` method to split the string into a list of lines. Then, we can use a list comprehension to add braces to each line.
2.
The solution to this problem can be achieved by using the `splitlines()` method to split ... | Write a Python function to add a string of braces to each line in a string, in the following format:
```
line1
line2
line3
```
should become
```
(line1)
(line2)
(line3)
```
If the input string is empty, return an empty string. If the input string contains only one line, return the line with braces. If the input str... | You can achieve this by defining a function that processes the input string, adding parentheses to each line. Here's a Python function that implements this logic:
```python
def add_braces_to_lines(input_string):
# Check if the input string is empty
if not input_string:
return ""
# Split the in... | 1,900 |
```python
class Node:
def __init__(self, value, left=None, right=None):
self.value = value
self.left = left
self.right = right
def swap_subtrees(node):
if node is None:
return
node.left, node.right = node.right, node.left
swap_subtrees(node.left)
swap_subtrees(node... | Write a Python function to modify a given binary tree in-place by swapping the left and right subtrees of every node recursively. The function should traverse the tree in pre-order, and each node should be modified in constant time. The function should not return anything, and it should modify the tree in-place.
For e... | To accomplish the task of swapping the left and right subtrees of every node in a binary tree recursively, you can implement a function that performs a pre-order traversal. During this traversal, you'll swap the left and right children of each node.
Here's how you can implement this in Python:
```python
class TreeNod... | 1,901 |
To sort a list of integers in ascending order using the merge sort algorithm, we can recursively divide the list into smaller sublists until each sublist contains only a single element. Then, we can merge the sublists back together in sorted order until we reach the original list. To merge two sublists in sorted order,... | Develop a recursive Python function `merge_sort` to sort a given list of integers in ascending order. The function should satisfy the following assertions:
```python
assert merge_sort([]) == []
assert merge_sort([5, 1, 2, 3, 4]) == [1, 2, 3, 4, 5]
assert merge_sort([3, 2, 1]) == [1, 2, 3]
assert merge_sort([1, 2, 3, 2... | To implement the `merge_sort` function in Python, we will follow the merge sort algorithm, which is a divide-and-conquer approach. The main steps involved in the algorithm are:
1. **Base Case**: If the list is of length 0 or 1, it is already sorted, so we can return it as is.
2. **Dividing**: Split the list into two h... | 1,902 |
Here is a Python function that implements the Sieve of Eratosthenes algorithm with dynamic programming:
```python
from typing import List
def sieve_of_eratosthenes(n: int) -> List[int]:
"""
Finds all prime numbers up to `n` using the Sieve of Eratosthenes algorithm.
"""
primes = [True] * (n + 1)
p... | Create a Python function to efficiently generate all prime numbers up to `n`. Implement dynamic programming with memoization, where the function should cache previously computed results and avoid re-computing when possible.
Your code should pass the following assertion:
```python
assert sieve_of_eratosthenes(10) == [2... | Certainly! To generate all prime numbers up to a given number `n`, we can use the Sieve of Eratosthenes algorithm. I'll implement a function that will utilize memoization to cache results, ensuring that we don't recompute the primes for previously calculated values of `n`.
Here's the implementation of the function:
`... | 1,903 |
Here's a possible implementation:
```python
def get_sorted_key_value_pairs_by_value(dictionary, ascending=True):
sorted_items = sorted(dictionary.items(), key=lambda x: x[1])
if not ascending:
sorted_items = sorted_items[::-1]
return sorted_items
```
In this implementation, we use the `sorted` fun... | Implement a Python function named `get_sorted_key_value_pairs_by_value` that takes two arguments, a dictionary and a boolean named `ascending`. The function should return a list of key-value pairs sorted by value in either ascending or descending order based on the value of `ascending`.
Your code should pass the follo... | Here’s how you can implement the `get_sorted_key_value_pairs_by_value` function in Python. The function receives a dictionary and a boolean value that specifies whether the sorting should be in ascending or descending order. It utilizes the built-in `sorted` function and returns a list of key-value pairs sorted by the ... | 1,904 |
```python
import numpy as np
def rotate_point(x, y, rotation_matrix):
point = np.array([[x], [y]])
transformed_point = np.dot(rotation_matrix, point)
return transformed_point
```
In the above code, we first define a function `rotate_point` that takes three parameters: `x`, `y`, and `rotation_matrix`. We t... | Write a Python function `rotate_point(x, y, rotation_matrix)` that takes a point (x, y) and a rotation matrix and returns the transformed point. Ensure your implementation handles any dimensionality of the point and rotation matrix. | To rotate a point using a rotation matrix in Python, we need to perform a matrix multiplication between the rotation matrix and the point (represented as a vector). The rotation matrix typically operates in 2D or 3D space, but we can generalize the approach for any dimensional space, as long as the dimensions match.
H... | 1,905 |
To read a file containing one integer per line and return the sum of all the integers, we can use list comprehension and the `sum` function in Python.
Here is the implementation:
```python
def sum_of_integers_in_file(file_path):
with open(file_path, 'r') as file:
integers = [int(line.strip()) for line in ... | Implement a Python function to read a file containing one integer per line and return the sum of all the integers. Use list comprehension and the `sum` function to achieve this. | Certainly! You can achieve this by defining a function that reads a file line by line, converts each line to an integer, and then calculates the sum using a combination of list comprehension and the `sum` function. Here's how you can implement this in Python:
```python
def sum_integers_from_file(filename):
with op... | 1,906 |
Here's how we can implement this:
```python
def find_min_max_indices(lst):
if not lst:
return ()
min_idx = 0
max_idx = 0
for i, x in enumerate(lst):
if x < lst[min_idx]:
min_idx = i
if x > lst[max_idx]:
max_idx = i
return (min_idx, max_idx)
``` | Write a Python function `find_min_max_indices(lst)` to find the indices of the minimum and maximum values in the given list `lst` and return them as a tuple. If the list contains multiple occurrences of the minimum or maximum values, find the indices of the first occurrences. Also, return an empty tuple if the list is ... | You can create the function `find_min_max_indices(lst)` as follows, which uses the `min()` and `max()` functions along with list traversal techniques to find the indices of the first occurrences of minimum and maximum values in the list. If the list is empty, the function will return an empty tuple. Here’s how to imple... | 1,907 |
Here is the implementation of the Python function `get_opposite_index(n, index)`:
```python
def get_opposite_index(n, index):
return (n - index) % n
```
In the implementation, `return (n - index) % n` is the key. The modulo operation `(n - index) % n` wraps around the indices and handles the case where `index > n... | Write a Python function `get_opposite_index(n, index)` that returns the opposite index of the given `index` in a circular list of length `n`. The opposite index is `n - index` (mod `n`), where the modulo operation handles the case where `index > n`.
For instance, if `n = 5` and `index = 2`, then the opposite index wou... | Here's a Python function that calculates the opposite index of a given `index` in a circular list of length `n`:
```python
def get_opposite_index(n, index):
# Calculate the opposite index using modulo
opposite_index = (n - index) % n
return opposite_index
# Testing the function with the provided assertion... | 1,908 |
With this understanding, we can implement a Python function that converts a list of dates (strings) into a list of datetimes, and then converts the datetimes into a list of 12-hour clock times (strings):
```python
from datetime import datetime
def convert_dates_to_times(dates):
datetimes = []
times = []
... | Write a Python function that converts a list of dates (strings) into a list of datetimes, and converts the datetimes into a list of 12-hour clock times (strings).
Input: A list of dates as strings in the format YYYY-MM-DD.
Output: A list of times as strings in the format HH:MM. | You can achieve this by using Python's `datetime` module to parse the dates and extract the time. Below is a Python function that converts a list of date strings into a list of formatted time strings.
```python
from datetime import datetime
def convert_dates_to_12hr_times(date_list):
time_list = []
for date_s... | 1,909 |
```python
def generate_deck(num_decks=1):
if num_decks <= 0:
raise ValueError("Number of decks must be a positive integer.")
deck = []
ranks = [str(i) for i in range(2, 11)] + ['Jack', 'Queen', 'King', 'Ace']
suits = ['clubs', 'diamonds', 'hearts', 'spades']
for _ in range(num_decks):
... | Construct a Python function to generate a deck of cards, where each card is represented by a string with the format "suit-rank". The function should return a list of cards, with the first card representing the 2 of clubs, the second card representing the 3 of clubs, and so on. The ranks should be the integers 2-10, the... | To create a function that generates a deck of cards in the specified format, we will construct a list of card representations based on the suits and ranks provided. Additionally, we will implement error handling to ensure that the input, if any, is a positive integer. However, since your description does not include in... | 1,910 |
Your function can use a key function to extract the digit sequence from each file name, convert it to an integer, and then sort the list based on the integers.
Here's how you can do it in Python:
```python
def sort_file_names(files):
def extract_digit_sequence(file_name):
return int(''.join(c for c in fil... | Create a Python function to sort a list of file names (strings) in the natural order (like the one used in Finder), where each file name contains a sequence of digits, e.g., `'file1.txt'`, `'file10.txt'`, `'file100.txt'`, and `'file2.txt'`, etc. The function should take a list of file names and return a sorted list of ... | To sort file names in a natural order, you can create a custom sorting function that splits each file name into parts—specifically, separating the numeric parts from the non-numeric parts. This way, when sorting, the numeric parts will be compared as integers rather than as strings, achieving the desired natural order.... | 1,911 |
To search for a pattern in a text, we need to follow these steps:
1. Check for the presence of `pattern` in `text` using `in` operator or `str.find()` method.
2. Return `True` if `pattern` is found, otherwise return `False`.
Here's how you can implement this function:
```python
def search_pattern(pattern: str, text:... | Write a Python function that takes two arguments: a string `pattern` and a text `text`. The function should return `True` if `pattern` is found in `text`, otherwise `False`. Handle the case where `pattern` is an empty string or `None` by returning `True` or `False`, respectively. You can assume that both `pattern` and ... | You can implement the function `search_pattern` as specified in your request. Here's the Python code that defines the function and also satisfies the given assertions:
```python
def search_pattern(pattern: str, text: str) -> bool:
if pattern is None:
return False
if pattern == "":
return True
... | 1,912 |
Here's how you could implement this function:
```python
def split_evenly(input, predicate):
bucket_1 = []
bucket_2 = []
for element in input:
if predicate(element):
bucket_1.append(element)
else:
bucket_2.append(element)
return (bucket_1, bucket_2)
```
The funct... | Create a Python function `split_evenly(input, predicate)` that splits a list of elements into two buckets based on the result of `predicate(element)`. If `predicate` returns `True`, the element is placed in the first bucket, otherwise it is placed in the second bucket. The function should return a tuple containing the ... | Certainly! Below is a Python function named `split_evenly` that takes a list of elements (`input`) and a `predicate` function. It will split the elements into two buckets based on the boolean result of the `predicate`.
```python
def split_evenly(input, predicate):
bucket_true = []
bucket_false = []
fo... | 1,913 |
Here's an example of how you can write a Python function to parse an integer from a string:
```python
def parse_int(s: str) -> int:
try:
return int(s)
except ValueError:
raise ValueError("Invalid input")
```
In this implementation, we use the `int()` function to convert the input string into a... | Write a Python function to parse an integer from a string. The input must be a string containing a non-negative integer value, and the function should return the corresponding integer. If the input is invalid, the function should raise a ValueError with the message "Invalid input".
The function should be defined with ... | Certainly! Below is a Python function that fulfills your requirements. The function is defined with type annotations, checks for valid input, and raises a `ValueError` with an appropriate message if the input is invalid.
```python
def parse_integer(input_str: str) -> int:
"""
Parses a non-negative integer from... | 1,914 |
Here is a Python function that implements this conversion:
```python
def convert_elastic_modulus(input_unit, elastic_modulus):
if input_unit == "SI":
return elastic_modulus * 1e-7 # Convert from SI to CGS
elif input_unit == "CGS":
return elastic_modulus * 1e7 # Convert from CGS to SI
else... | Design a Python function to convert the elastic modulus from SI unit to CGS unit or vice versa. The function should take two parameters, the input unit (SI or CGS) and the elastic modulus value, and return the corresponding converted elastic modulus value. Ensure that the function can handle both SI to CGS and CGS to S... | To create a function that converts the elastic modulus from SI to CGS and vice versa, we first need to understand the conversion factors involved:
- In SI units, elastic modulus is measured in pascals (Pa), and in CGS units, it is measured in dynes per square centimeter (dyne/cm²).
- The conversion between these units... | 1,915 |
Here's how you can create a function that takes `table_name`, `field_names`, and `data_values` as parameters and returns an SQL `INSERT` statement with parameterized values:
```python
def build_sql_insert_statement(table_name, field_names, data_values):
placeholders = ", ".join(["%s"] * len(field_names))
retur... | Write a Python function to build an SQL `INSERT` statement with parameters for the given table name, field names, and data values.
The function should take the following parameters:
- `table_name`: The name of the table to insert data into
- `field_names`: A list of field names to insert data for
- `data_values`: A l... | You can create a function called `build_sql_insert_statement` that constructs an SQL `INSERT` statement with parameterized values. Here's how to implement it in Python:
```python
def build_sql_insert_statement(table_name, field_names, data_values):
# Create a comma-separated string of field names
fields = ', '... | 1,916 |
Here's the code for the function:
```python
def create_mapping(labels, values):
return {label: value for label, value in zip(labels, values)}
```
The function takes in two lists as arguments: `labels` and `values`. It uses the built-in `zip()` function to combine the two lists into a list of tuples. Each tuple co... | I have a list of labels `'a', 'b', 'c', 'd'` and a list of values `[1, 2, 3, 4]`. I want to create a dictionary that maps each letter to its corresponding value. Assuming the list of labels and the list of values are always of equal length, can you write a Python function that takes in the two lists and returns the des... | Absolutely! You can create a dictionary that maps each label to its corresponding value using the `zip` function in Python. Here’s a simple function to accomplish that:
```python
def create_label_value_mapping(labels, values):
# Combine the two lists into a dictionary
mapping = dict(zip(labels, values))
re... | 1,917 |
Implementing the `collect_pairs` function requires understanding the given instruction. The function should take a list of strings and return a list of all possible pairs of strings found in the input list that are consecutive.
The following steps need to be followed:
1. Iterate over the input list, keeping track of ... | Create a Python function `collect_pairs` that takes a list of strings and returns a list of all possible pairs of strings that are found in the input list. A pair is a 2-element tuple of strings that appear consecutively in the input list. If a string appears multiple times in the input list, the pair should only be re... | You can create the function `collect_pairs` using a set to track the pairs of strings as you iterate through the input list. Since the order of pairs does not matter, a set will help you avoid duplicate pairs automatically. Here’s how you can implement this:
```python
def collect_pairs(strings):
# Initialize an em... | 1,918 |
Here is a Python function that implements this approach:
```python
def check_type_and_handle_list(obj, t):
"""
Checks if the type of `obj` is a list, and if so, returns a list with all elements
of type `t`. If `obj` is not a list, returns an empty list.
"""
if isinstance(obj, list):
return ... | Write a Python function `check_type_and_handle_list` that takes two arguments: a variable `obj` and a type `t`.
The function should check if the type of `obj` is `list`. If it is, the function should return a list with all elements of type `t`. If `obj` is not a `list`, the function should return an empty list.
Your ... | You can implement the function `check_type_and_handle_list` as follows:
```python
def check_type_and_handle_list(obj, t):
if isinstance(obj, list):
return [item for item in obj if isinstance(item, t)]
return []
# Example test cases
assert check_type_and_handle_list([1, "a", 2, "b", 3], int) == [1, 2, ... | 1,919 |
Here's how you could implement this function in Python using regular expressions:
```python
import re
def split_sentence(sentence):
words = re.findall(r"'?[\w]+'?", sentence)
words = [word.replace("'", "") for word in words]
return words
``` | Create a Python function to split a sentence into words and remove the punctuation. The function should properly handle special cases, such as apostrophes and contractions.
For example, given the sentence "I'm on the phone, but I'll get it done eventually." the function should return the list ["I", "m", "on", "the", "... | You can create a Python function to split a sentence into words while removing punctuation and handling special cases like apostrophes in contractions. One way to approach this is by using the `re` module for regular expressions to find word boundaries and remove punctuation appropriately. Below is a function that acco... | 1,920 |
Here's how we can implement this in Python:
```python
def count_feature_names(feature_names, prefix):
count = 0
for name in feature_names:
if name.startswith(prefix):
count += 1
return count
``` | Write a Python function that takes a list of feature names and a prefix string as parameters. The function should return the number of feature names that start with the given prefix.
Your code should pass the following test case:
```python
feature_names = ["feature1", "feature2", "feature3", "other_feature"]
assert co... | You can achieve this by defining a function that iterates through the list of feature names and counts how many of them start with the specified prefix. Here’s how you can implement the `count_feature_names` function:
```python
def count_feature_names(feature_names, prefix):
count = 0
for feature in feature_na... | 1,921 |
Here's how you can implement this:
```python
def integer_divide(dividend, divisor):
if divisor == 0:
raise ValueError("Division by zero is undefined.")
if not isinstance(dividend, int) or not isinstance(divisor, int):
raise TypeError("Both inputs must be integers.")
if divisor == 1:
... | Write a Python function `integer_divide(dividend, divisor)` to implement integer division without using the division operator (`/`). The function should return the quotient and remainder of the integer division, with the remainder always being the positive value. Handle possible errors or edge cases appropriately, such... | Certainly! Below is the implementation of the `integer_divide(dividend, divisor)` function in Python. This function performs integer division without using the division operator (`/`). It returns both the quotient and the remainder while ensuring that the remainder is always non-negative. It also handles edge cases lik... | 1,922 |
```python
def detect_chain_reversal(transactions):
prev_value = None
reversal_ids = []
for transaction in reversed(transactions):
if transaction.value > 0 and transaction.value <= 100 and transaction.value != prev_value:
reversal_ids.append(transaction.id)
prev_value = transacti... | Write a Python function `detect_chain_reversal` to detect and perform reversal of a series of transactions in a blockchain. The function should take a list of transactions and return a list of transaction IDs that need to be reversed. A transaction is considered a reversal if it meets the following conditions:
1. The ... | To implement the `detect_chain_reversal` function based on the specified criteria, we can follow these steps:
1. The function will accept a list of transactions where each transaction is represented as a dictionary containing at least an `id` and a `value`.
2. We'll iterate over the list of transactions in reverse ord... | 1,923 |
To provide an empty Python function with a docstring, you need to understand what a function definition is and how to use docstrings. A function definition includes the `def` keyword, a function name, and a set of parentheses with parameters. The docstring is a multi-line string that comes after the function definition... | Provide an empty Python function definition with a docstring that indicates its intended purpose. The docstring should include a description of the function's input parameters, expected behavior, and the expected return value. The function should be designed to handle any runtime conditions that may occur during execut... | Certainly! Below is an empty Python function definition that includes a comprehensive docstring outlining its intended purpose, input parameters, expected behavior, and return value. The function is designed to handle potential runtime conditions gracefully.
```python
def empty_function(param1, param2):
"""
Pl... | 1,924 |
```python
from typing import List, Optional
def search_index(lst: Optional[List[str]], substr: str) -> int:
if lst is None:
raise ValueError("List cannot be None.")
if substr == "":
return 0
try:
for i, s in enumerate(lst):
if substr.lower() in s.lower():
... | Create a Python function to search a list of strings for a substring. The function should have the following properties:
1. Accept a list of strings as the first parameter.
2. Accept another string as the second parameter, which is the substring to search for.
3. Search the list for the substring, and return the **inde... | Here's a Python function that fulfills all the specified requirements:
```python
def find_substring(strings, substring):
# Ensure the list is not None
if strings is None:
raise ValueError("List cannot be None.")
# If the list is empty, return -1
if not strings:
return -1
#... | 1,925 |
Here's how you can implement this in Python using a generator function:
```python
import itertools
def get_combinations(n, r):
for combination in itertools.combinations(n, r):
yield combination
``` | Write a Python function `get_combinations` that generates all possible combinations of a fixed number of elements (r) from a larger set (n) without repetition. The function should be implemented in a functional manner using generator to generate one combination at a time, and should return ``None`` once all combination... | To achieve the functionality of generating all possible combinations of a fixed number of elements from a larger set without repetition, you can write a recursive generator function. Below is the implementation of the `get_combinations` function according to your requirements:
```python
def get_combinations(elements, ... | 1,926 |
```python
def validate_truthiness(value):
try:
assert value is not None and value != "", "Value is empty"
assert value, "Value is not truthy"
except AssertionError as err:
return f"Value is invalid: {err}"
else:
return "Value is valid!"
``` | Create a function to validate the truthiness of a given input value, including the handling of custom error conditions. Use a `try/except` block for exception handling, and `assert` to ensure the input is not None or a blank string. If the input value is valid, return the string "Value is valid!", and if not, return th... | You can create a function called `validate_truthiness` that checks the truthiness of a given input value. This function will use a `try/except` block for exception handling and `assert` statements to ensure that the input is neither `None` nor a blank string. Here's how you might implement this:
```python
def validate... | 1,927 |
To check if `s1` is a prefix of `s2`, we can compare the first few characters of `s2` with `s1`. If they match, then `s1` is a prefix of `s2`.
Here's a Python function that implements this logic:
```python
def is_prefix(s1, s2):
if len(s1) > len(s2):
return False
return s2[:len(s1)] == s1
```
Let's b... | Write a Python function that takes two strings, `s1` and `s2`, and checks if `s1` is a prefix of `s2`. The function should return `True` if `s1` is a prefix of `s2`, `False` otherwise.
Your code should pass the following assertions:
```python
assert is_prefix("abc", "abcd") == True
assert is_prefix("ab", "abcd") == Tr... | You can create a function called `is_prefix` to check if one string is a prefix of another string. Here's how you can implement it:
```python
def is_prefix(s1, s2):
# Check if s2 starts with s1
return s2.startswith(s1)
# Testing the function with assertions
assert is_prefix("abc", "abcd") == True
assert is_pr... | 1,928 |
To create such a function, we can use the `os.path.join` function, which combines the file name and directory path using the operating system-specific path separator. We can also use the `os.path.normpath` function to normalize the path and ensure that it is in the correct format for the operating system.
```python
im... | Write a Python function named `add_config_file_with_path` that accepts a file name and directory path and returns the complete configuration file path with the file name and directory path separated by a forward slash.
`add_config_file_with_path` should be able to handle empty strings as input for either the file name... | Certainly! Below is a Python function named `add_config_file_with_path` that accepts a file name and a directory path. It will return the complete path by constructing it with a forward slash as the separator. The function also handles cases where either input is an empty string.
```python
def add_config_file_with_pat... | 1,929 |
```python
import re
def sum_of_digits(sequence):
try:
numbers = map(int, re.findall(r"\d", sequence))
return sum(numbers)
except Exception as e:
print(f"Error: {e}")
return None
``` | Design a Python function to convert a character sequence into its corresponding integer value. The input string will contain only the digits 0 to 9, with each digit separated by a comma (not including the quotes). The output should be the sum of the values of the digits. The function should ignore any other characters ... | You can create a Python function that processes the input string to extract the digit values while ignoring any non-digit characters. Here's a simple implementation of such a function:
```python
def sum_of_digits(input_str):
total = 0
# Split the input string by commas
parts = input_str.split(',')
... | 1,930 |
Here's how you can implement this function:
```python
def safe_divide(numerator, denominator):
if numerator is None or denominator is None:
return None
if denominator == 0:
return None
return numerator / denominator
``` | Create a Python function `safe_divide` that safely divides two numbers. The function should return `None` if either input is `None` or the denominator is zero. Otherwise, it should return the quotient of the two inputs.
Your code should pass the following assertion:
```python
assert safe_divide(None, None) is None
``` | Here is a Python function named `safe_divide` that meets your specified requirements:
```python
def safe_divide(numerator, denominator):
if numerator is None or denominator is None or denominator == 0:
return None
return numerator / denominator
```
This function checks if either the numerator or denom... | 1,931 |
Here is the implementation:
```python
def filter_nested_list(nested_list):
result = []
for element in nested_list:
if isinstance(element, list):
filtered_element = filter_nested_list(element)
if filtered_element:
result.append(filtered_element)
else:
... | Write a Python function to filter out False elements from a nested list of lists based on a certain condition. The input is a nested list of lists (or a list of lists of lists), and the output is a flattened list of lists. The condition for filtering is if the element is False, or if the element is an empty list, or if... | To implement a function that filters out False elements (which includes `False`, empty lists `[]`, and lists containing only `False` values) from a nested list of lists, we can use recursion to handle the nested structure effectively. The function will traverse each element of the input list, check for the filtering co... | 1,932 |
```python
import numpy as np
def precision_recall_scores(y_true, y_pred):
assert y_true.shape == y_pred.shape and len(y_true.shape) == 1
true_positives = np.sum(np.logical_and(y_true == 1, y_pred == 1))
false_positives = np.sum(np.logical_and(y_true == 0, y_pred == 1))
false_negatives = np.sum(np.logic... | Given two NumPy integer arrays of the same shape, `y_true` and `y_pred`, compute the precision and recall scores for the positive class.
Precision is the fraction of positive predictions that are true, and recall is the fraction of true positive instances that are correctly predicted. | To compute the precision and recall scores for the positive class using NumPy, you can follow these steps:
1. **Define True Positives (TP)**: The count of instances where both `y_true` and `y_pred` are equal to 1.
2. **Define False Positives (FP)**: The count of instances where `y_pred` is 1 and `y_true` is 0.
3. **De... | 1,933 |
Here is the implementation of the Python function to create a hash of a given string based on the MD5 algorithm:
```python
import hashlib
def create_hash_md5(string: str) -> str:
try:
encoded_string = string.encode("utf-8")
hash_md5 = hashlib.md5(encoded_string).hexdigest()
return hash_md... | Write a python function to create a hash of a given string based on the MD5 algorithm. The function should accept a string parameter, encode it into a byte array using UTF-8 encoding, and then use the `hashlib` module to generate the MD5 hash. The function should return the hash as a hexadecimal string. Handle any pote... | Certainly! Below is a Python function that accomplishes the task of creating an MD5 hash of a given string. This function handles potential errors during encoding and hashing with appropriate exception handling.
```python
import hashlib
def generate_md5_hash(input_string):
try:
# Encode the input string i... | 1,934 |
Here's how we can implement this:
```python
def find_intersection(A, B):
intersection = []
i, j = 0, 0
while i < len(A) and j < len(B):
if A[i] < B[j]:
i += 1
elif A[i] > B[j]:
j += 1
else:
intersection.append(A[i])
i += 1
... | You are given two lists of integers `A` and `B`, representing a data structure that is optimized for lookup (i.e., it should be quick to check if a number is in the list). The two lists are always the same length. Design a function that returns the intersection of the two lists, i.e., all the numbers that exist in both... | To efficiently find the intersection of two lists of integers `A` and `B` while using constant additional space, we can use a set to store the elements of one of the lists. Then, we can check each element of the other list against this set. This approach will give us a time complexity of O(n) while only using O(n) spac... | 1,935 |
A function that escapes special characters in a string can be written in Python using the built-in `repr()` function. The `repr()` function returns a printable representation of an object, which is suitable for debugging and logging purposes.
Here's how you can create a function to escape special characters in a strin... | Create a Python function to escape (or unescape, if the input string begins with '\') all special characters in a given string, including backslash, single quote, double quote, Unicode characters, backspace, and newline characters.
Your code should pass the following test case:
```python
input_string = 'Hello, World!\... | To create a Python function that escapes all special characters in a given string, including handling a potential unescape scenario, we can utilize the `repr()` function, which returns a string that would represent the object in the form of a string literal. We will also need to ensure that we handle the backslash prop... | 1,936 |
To find the maximum value in a dictionary, we can use the built-in `max()` function and pass in the dictionary's values as an argument. However, the `max()` function does not work on dictionaries directly. We can use the `values()` method to transform the dictionary into a list of values and pass it to `max()` to find ... | Write a Python function to find the maximum value in a dictionary, given its keys are integers. | You can create a function that takes a dictionary as input and returns the maximum value from it. Here's a simple implementation:
```python
def max_value_in_dict(input_dict):
# Check if the dictionary is empty
if not input_dict:
return None # or you can raise an exception
# Use the max function t... | 1,937 |
Here's how we can implement this function in Python:
```python
def calculate_damage(char_level, strength, dexterity, target_level, resistance):
damage = 2 * char_level * (strength + dexterity) / (char_level + target_level + resistance)
return damage
```
This function takes the character's level, strength, and... | Design a Python function that calculates and returns the amount of damage done by a character attack against a target, given the character's level, strength, and dexterity, along with the target's level and resistance. The function should apply the following damage calculation formula to calculate the damage: `damage =... | Certainly! Below is the Python function that calculates the damage done by a character's attack against a target using the specified formula:
```python
def calculate_damage(char_level, strength, dexterity, target_level, resistance):
"""
Calculate the damage done by a character attack against a target.
Par... | 1,938 |
Here is the implementation:
```python
def cast_string(string, data_type):
if data_type == 1:
return int(string)
elif data_type == 2:
return float(string)
else:
return str(string)
```
In this implementation:
- The `cast_string()` function takes the input string and an integer to ind... | Build a Python function that takes a string and an integer from 1 to 3 to indicate the data type to cast the string as. If the integer is 1, cast the string as an integer. If the integer is 2, cast it as a float. Otherwise, cast it as a string. Ensure that the input string can be safely converted to the specified data ... | Here is a Python function `cast_string` that meets the specified requirements. It takes a string and an integer to determine how to cast the string. It raises a `ValueError` if the conversion is not possible.
```python
def cast_string(value: str, data_type: int):
if data_type == 1:
if value.isdigit() or (v... | 1,939 |
Here is how you can implement the function in Python:
```python
import random
def generate_random_object():
object_length = 10
object_str = ""
first_char = random.choice(list("0123456789"))
object_str += first_char
remaining_chars = list("0123456789abcdefghijklmnopqrstuvwxyz")
for i in range(1... | Write a Python function `generate_random_object` that generates a random object according to the following constraints:
- The object is a string with a length of 10.
- The characters within the string are randomly selected from the digits 0-9 and the lowercase letters a-z.
- The first character must be a digit and the... | Certainly! To create a Python function that generates a random object with the specified constraints, we can utilize the `random` module to select characters. We'll ensure that the first character is a digit, the last character is a lowercase letter, and that we track previously generated objects to ensure uniqueness.
... | 1,940 |
To parse a configuration file and extract the values of a given key(s), we need to iterate through the file line by line and parse each line for the key and value. We can use a regular expression to extract the key and value from each line, and then store them in a dictionary.
Here's how we can implement this:
```pyt... | Write a Python function to parse a configuration file and extract the values of a given key(s). The configuration file is in the format of `key=value`, where the key is an alphanumeric string, and the value is a string of any characters. The function should return a dictionary that maps each key to its value. | Certainly! Below is a Python function that reads a configuration file with the specified format and extracts the key-value pairs into a dictionary.
```python
def parse_config_file(file_path):
"""
Parses a configuration file and returns a dictionary mapping keys to their values.
:param file_path: Path ... | 1,941 |
To find the value of a slot in a list of slots, we can use a dictionary to store the slots as key-value pairs, where the key is the slot name and the value is the slot value. By iterating through the list of tuples, we can populate the dictionary with the slot names and values. Then, we can simply return the value corr... | Define a Python function `find_slot_value` that takes a list of intention-based dialog management slots, represented as a list of two-element tuples (slot name, slot value). The function should return the value of the slot whose name matches the target slot name, or return a default value if the slot does not exist.
F... | You can implement the `find_slot_value` function as described. Here's how to do it in Python:
```python
def find_slot_value(slots, target_slot_name, default_value=None):
"""
Finds the value of a slot by its name from a list of slots.
Args:
- slots: List of tuples, where each tuple contains (slot name,... | 1,942 |
Here's a Python implementation of this approach:
```python
def is_valid(s: str) -> bool:
stack = []
pairs = {
'(': ')',
'[': ']',
'{': '}'
}
for char in s:
if char in pairs:
stack.append(char)
elif char in pairs.values():
if not stack or p... | Given a string `s` that contains only parentheses, brackets, and curly braces, create a Python function `is_valid` that checks if the string has valid brackets. The brackets must be closed in the correct order and every open bracket must have a corresponding closing bracket. The function should return a boolean value i... | You can create a function `is_valid` that uses a stack data structure to validate the string of brackets. The idea is to push opening brackets onto the stack and pop them when a corresponding closing bracket is encountered. If the stack is empty at the end of the process and all brackets have been matched correctly, th... | 1,943 |
Here's the code for the function:
```python
def extract_last_three(s: str) -> str:
if len(s) >= 3:
return s[-3:]
else:
return s
```
This function first checks the length of the string using `len(s)`. If the length is greater than or equal to 3, it returns the last three characters using `s[-3:... | Write a Python function to extract the last three characters from a given string. If the string has fewer than three characters, return the entire string. Use unpacking and pattern matching in your function.
Your code should pass the following assertions:
```python
assert extract_last_three("123") == "123"
assert extr... | You can achieve this by using pattern matching (also known as structural pattern matching) that was introduced in Python 3.10. Here's a function that uses unpacking and pattern matching to extract the last three characters from a given string:
```python
def extract_last_three(s: str) -> str:
match s:
case ... | 1,944 |
Here's how you can implement this function:
```python
def format_cell(cell):
if isinstance(cell, str):
cell = cell.replace('"', '\\"')
return f'"{cell}"'
elif isinstance(cell, int):
return str(cell)
elif isinstance(cell, list):
return '[' + ', '.join(map(format_cell, cell)) ... | Write a Python function `format_cell(cell)` that takes a cell data structure as input, which can be either a `str`, `int`, `list`, or `dict`. The function should return the cell data as a string, formatted according to the following rules:
* `str`: The original string, surrounded by double quotes, and escaped by a bac... | Certainly! Below is a Python function `format_cell` that meets the specified formatting requirements for different data types (string, integer, list, dictionary). It effectively handles escaping of double quotes in strings and formats lists and dictionaries recursively.
Here's the implementation:
```python
def format... | 1,945 |
Here's a Python function that implements this calculation:
```python
def find_coefficients(slope, y_intercept):
A = -slope * y_intercept
B = 1
C = -y_intercept
return A, B, C
``` | Given a line (not a segment) in the standard form $Ax + By + C = 0$, calculate the coefficients $(A, B, C)$. | To determine the coefficients \(A\), \(B\), and \(C\) in the standard form of a line equation \(Ax + By + C = 0\), we first understand what the standard form represents.
1. **Identifying the Given Line**: If you have a specific line in another format (like point-slope, slope-intercept, or two points), we can convert t... | 1,946 |
To solve this problem, we can use a recursive approach. We can define a recursive function that takes in a number `n` and returns the sum of all integers from 1 to `n`. The base case for this recursion is when `n` is 1, in which case the function returns 1. For any other number `n`, the function calls itself with `n-1`... | Write a recursive Python function that takes in a positive integer and returns the sum of all the integers from 1 to that number. For example, if the input is 3, the function should return 6 (because 1 + 2 + 3 = 6). | Certainly! Below is a Python function that implements recursion to calculate the sum of all integers from 1 to a given positive integer:
```python
def recursive_sum(n):
# Base case: if n is 1, return 1
if n == 1:
return 1
else:
# Recursive case: n plus the sum of integers up to n-1
... | 1,947 |
To implement this function, we need to work from the right side of the input number to insert commas appropriately. We can use a `while` loop to iterate through the digits of the number, keeping track of the number of digits and inserting commas every three digits.
Here is the implementation of the `add_commas` functi... | Implement a Python function `add_commas` that takes an integer and a boolean flag `use_commas` as arguments. The function should return a string representation of the integer with commas added between every three digits from the right. If the `use_commas` flag is set to `False`, the function should just return the inpu... | You can implement the `add_commas` function in Python using the built-in string formatting features. Here's one way to accomplish the task:
```python
def add_commas(number: int, use_commas: bool) -> str:
if not use_commas:
return str(number)
return f"{number:,}"
# Example usage:
number = 1234567
with_... | 1,948 |
Here is a Python function that implements this approach:
```python
def process_iterator_with_default(my_iter, default_val=None):
"""
Takes an iterator and a default value as inputs and returns a generator that produces items
from the iterator and yields the default value if the iterator is exhausted. The d... | Develop a Python function `process_iterator_with_default` that takes an iterator `my_iter` and a default value `default_val` as inputs and returns a generator that produces items from `my_iter` and repeatedly yields `default_val` if `my_iter` is exhausted. The function should have a default value of `None` for `default... | You can implement the `process_iterator_with_default` function using a generator. This function will iterate over the provided iterator and, once it is exhausted, it will continue to yield the specified default value indefinitely. Here's how you can do it:
```python
def process_iterator_with_default(my_iter, default_v... | 1,949 |
To calculate the power spectrum of a 3D tensor, several key steps are required:
1. The input tensor can be reshaped into a 2D tensor with the samples and channels dimensions flattened.
2. Each column of the reshaped tensor corresponds to a single channel and can be treated as a vector of samples.
3. The power spectrum... | Create a function to calculate the power spectrum of a 3D tensor, given that the dimensions have the following meanings: the first dimension is the number of samples, the second dimension is the number of frequency bins, and the third dimension is the number of channels. The function should return a 2D tensor represent... | To create a function that calculates the power spectrum of a 3D tensor as you described, we will utilize the PyTorch library. The function will average the power spectrum over the samples and frequency bins dimensions, yielding a 2D tensor where each element corresponds to the average power spectrum for each channel.
... | 1,950 |
Here's how you could do it:
```python
import json
import datetime
def create_metadata(author, title, tags, language, timestamp, comments):
metadata = {
"author": author,
"title": title,
"tags": tags,
"language": language,
"timestamp": timestamp,
"comments": comments... | Write a Python function named `create_metadata` to construct a JSON object that represents a metadata record for a document. The function should accept the following arguments:
- `author`: A string representing the author of the document.
- `title`: A string representing the title of the document.
- `tags`: A list of ... | To create a JSON object representing a metadata record for a document, we can define a Python function named `create_metadata`. This function will gather the provided information into a structured dictionary and then convert it to a JSON object using Python's `json` module. Below is the implementation of this function:... | 1,951 |
To recursively search for a key in a nested dictionary, we can use a recursive function. The function takes three arguments: `dictionary`, the dictionary to search, `key`, the key to search for, and `default`, the default value to return if the key is not found.
The function works as follows:
1. Check if the key is i... | Write a Python function that recursively searches for a key in a nested dictionary of arbitrary depth and returns the value stored at that key. If the key is not found in the dictionary, the function should return None.
In addition to the key and the dictionary, the function should take a second argument, `default`, w... | Your implementation of the function `recursively_search_dict` looks great! It follows the recursive approach necessary to search through nested dictionaries, and it correctly handles both the base case (finding the key) and the recursive case (searching through nested dictionaries).
Here is the complete implementatio... | 1,952 |
To write a Python function `get_ip_host` that takes an IP address as input and returns its associated hostname, using `socket` to resolve the IP address and `contextlib.suppress` to suppress any exceptions that may arise, you can follow these steps:
1. Use `socket.gethostbyaddr` to resolve the IP address and return th... | Write a Python function `get_ip_host` that takes a single argument, an IP address, and returns its associated hostname. If the hostname cannot be resolved, return `None`. Your function should use `socket` to resolve the IP address and `contextlib.suppress` to suppress any exceptions that may arise.
Your code should pa... | You can achieve this by using the `socket` library for DNS resolution and `contextlib.suppress` to handle exceptions gracefully. Here's how the `get_ip_host` function can be implemented:
```python
import socket
from contextlib import suppress
def get_ip_host(ip_address):
with suppress(socket.herror, socket.gaierr... | 1,953 |
To create a Python function to generate HTML for a submit button with the specified field name and button value, you can follow these steps:
1. Define a function that takes two arguments: `field_name` and `button_value`.
2. Use string formatting to construct the HTML element with the specified field name and button va... | Create a Python function to generate HTML for a submit button with the specified field name and button value. The function should return a string containing the HTML element `<input type="submit" name="<field_name>" value="<button_value>" />` with the specified field name and button value.
Your code should pass the fo... | You can create the desired function in Python as follows:
```python
def generate_submit_button(field_name, button_value):
return f'<input type="submit" name="{field_name}" value="{button_value}" />'
# Test the function with the provided assertion
assert generate_submit_button('username', 'Submit') == '<input type... | 1,954 |
Here's how you can implement this:
```python
def get_missing_tasks(suites, tasks):
missing_tasks = []
for suite in suites:
if suite["suite_id"] not in [task["suite_id"] for task in tasks]:
missing_tasks.append(suite)
return missing_tasks
``` | Create a Python function `get_missing_tasks` that takes two arguments: `suites` (a list of dictionaries) and `tasks` (a list of dictionaries). Each dictionary in `suites` represents a suite and each dictionary in `tasks` represents a task. Both dictionaries have the `suite_id` key. The function should return a list of ... | You can create the `get_missing_tasks` function based on your requirements. The function will check each suite in the `suites` list and see if the corresponding task exists in the `tasks` list. It will return a list of tasks that are present in the suites but missing from the tasks.
Here's how you can implement this:
... | 1,955 |
To build a weighted graph from a dictionary representing its adjacency list, you need to process the given dictionary and extract the information for each node and its neighbors and corresponding weights. The approach would be to iterate over the keys and values of the dictionary, and in each iteration, extract the nei... | Build a Python function to create a weighted graph from a dictionary representing its adjacency list. The keys of the dictionary are the nodes of the graph, and the values are lists containing the neighbors and their corresponding weights. Each neighbor is a tuple with the form `(neighbor, weight)`. The function should... | To create a weighted graph from an adjacency list represented by a dictionary, we need to process the input dictionary and convert it into the desired output format. The resulting structure will map each node to another dictionary that represents its neighbors and corresponding weights.
Here's how this can be implemen... | 1,956 |
Here's how you can implement this function using PyTorch:
```python
import torch
def threshold_tensor(tensor, threshold):
comparison = tensor.ge(threshold)
binary_tensor = comparison.int()
return binary_tensor
```
The `tensor.ge()` method performs an element-wise comparison of the tensor with the thresho... | Implement a function `threshold_tensor(tensor, threshold)` in Python that takes a multi-dimensional tensor `tensor` and a scalar `threshold`, and returns a binary tensor where the value of each element is 1 if it is greater than or equal to `threshold`, and 0 otherwise. Use PyTorch for tensor manipulation. | To implement the function `threshold_tensor(tensor, threshold)` using PyTorch, you can use the following code:
```python
import torch
def threshold_tensor(tensor, threshold):
"""
This function takes a multi-dimensional tensor and a threshold value,
and returns a binary tensor where each element is 1 if it... | 1,957 |
Here's a Python function implementation that follows the given instructions:
```python
import re
def parse_keys_values(input_string):
quoted_strings = re.findall(r'".*?"', input_string)
for quoted_string in quoted_strings:
input_string = input_string.replace(quoted_string, quoted_string.replace(' ', '... | Implement a Python function that takes a string of comma-separated key-value pairs and returns a dictionary. The string is composed of key-value pairs separated by commas, where each pair contains a key and a value separated by a colon. The key and value may contain spaces, but they are always enclosed in double quotes... | To implement the requested function, we need to parse a string of comma-separated key-value pairs while handling the specific requirements. We'll need to:
1. Split the input string on commas to get individual key-value pairs.
2. Strip whitespace from the ends of the pairs.
3. For each pair, further split it by the fir... | 1,958 |
To create a Python function that checks if the input is a valid object and returns a value if it is a number or None if it is not, you can follow these steps:
1. Check if the input is a number by using the `isinstance` function and passing in `int` as the class.
2. If the input is a number, check if the input is None.... | Create a Python function that checks if the input is a valid object and returns a value if it is a number or None if it is not. Assume that the input object is either None or a number with an integer type. If the input is None, the function should return None, while if it is a number, the function should return its val... | You can create the function `check_number` to check if the input is either `None` or a number, and apply the callback if it is a number. Below is the implementation of the function based on the provided specifications:
```python
def check_number(obj, callback=lambda x: x * x):
# Check if the input is None
if o... | 1,959 |
Here's how you could do it:
```python
import numpy as np
def get_sorted_words(words):
words_list = words.split(' ')
sorted_words = np.sort(words_list)
sorted_words_string = ' '.join(sorted_words)
return sorted_words_string
```
This function takes in a string of words and splits them into a list of w... | Write a Python function `get_sorted_words` that takes in a string of words (words separated by spaces) and returns a string of the words in sorted order, separated by spaces. Words with the same letters, but in a different order, are considered the same word (e.g., "cat" and "act"). The function should use the `join` m... | To create the `get_sorted_words` function, we'll follow these steps:
1. Split the input string into individual words.
2. Normalize each word by sorting the letters in the word and using a set to ensure uniqueness.
3. Convert the set back to a list so that we can sort the words.
4. Use the `numpy.sort` function to sor... | 1,960 |
To count the number of digits in a binary representation of an integer, we can use Python's bitwise operations to check the 1-bits in the binary representation. Here's how:
1. Initialize a counter variable to 0.
2. While the input integer is greater than 0:
1. Use the bitwise AND operator (`&`) to check if the righ... | Write a Python function to count the number of digits in the binary representation of a non-negative integer, using bitwise operations. Your function should take a positive integer as input and return a count of the number of 1-bits in the binary representation of the integer. | You can count the number of 1-bits (also known as the Hamming weight or population count) in the binary representation of a non-negative integer using bitwise operations. The following Python function does just that:
```python
def count_ones_in_binary(n):
if n < 0:
raise ValueError("Input must be a non-neg... | 1,961 |
Here's a Python function that takes an integer `n` and returns a string containing the 32-bit binary representation of `n`:
```python
def to_bits(n):
if n >= 0:
return bin(n).replace('0b', '').zfill(32)
else:
return bin(2**32 + n).replace('0b', '').zfill(32)
``` | Given an integer `n` (which is a non-negative, 32-bit integer), write a Python function `to_bits(n)` that returns a string containing the 32-bit binary representation of `n`. If the integer is negative, it should be represented using the 2's complement representation. Your function should support conversion of both pos... | You can achieve the desired functionality by using Python's built-in formatting capabilities to convert integers into their binary representation, while taking care of the negative values using two's complement. Here's a function that implements this:
```python
def to_bits(n: int) -> str:
# If n is negative, calcu... | 1,962 |
To implement a function that returns the number of trailing zeros in the binary representation of an integer, you can follow these steps:
1. Use type hinting and type annotations to specify the expected input and output types.
2. Initialize a counter variable and set it to zero.
3. Use a while loop to iterate over the... | Implement a Python function that takes an integer and returns the number of trailing zeros in the binary representation of the integer. The function should use the standard Python libraries and do not use the built-in `bin()` function to find the binary representation. Instead, you should use a different approach that ... | To implement the function that counts the number of trailing zeros in the binary representation of an integer, we can use a simple approach that repeatedly divides the number by 2 (shifting right in binary) until we hit an odd number. Each division by 2 will effectively check for a trailing zero. We can use type hints ... | 1,963 |
Here is a sample implementation of the function:
```python
def find_lines_with_string(file_path, string, case_sensitive=False):
matching_lines = []
with open(file_path, 'r') as file:
lines = file.readlines()
for line in lines:
if case_sensitive and string in line:
ma... | You have a text file that contains multiple lines of text. Write a Python function to read this file and find the lines that contain a specific string. The function should take the file path, the string to search for, and an optional boolean flag to specify whether the search should be case-sensitive or not. | You can accomplish this task using the following Python function. The function reads the specified text file line by line, checks if the line contains the specific string, and returns a list of matched lines. The case sensitivity can be controlled with an optional boolean parameter.
Here’s how you can write the functi... | 1,964 |
Here is an example implementation of a setter injection decorator using Python's `__set_name__` method and a descriptor class:
```python
class SetterInjection:
def __init__(self, setter_method):
self.setter_method = setter_method
def __set_name__(self, owner, name):
self.name = name
def ... | Write a Python decorator function `setter_injection` that takes a setter method as an argument and injects it into another class method at runtime. This should be done using Python's `__set_name__` method and a descriptor class. Use `@setter_injection` to create a decorator for the `set_a` method in the `Example` class... | To implement the `setter_injection` decorator that injects a setter method into a class through a descriptor, we need to create a base descriptor class that will handle the attribute's setting and getting. The `@setter_injection` decorator will be applied to the setter method, and we will use the `__set_name__` method ... | 1,965 |
Here is an example implementation of the function:
```python
def filter_divisible_by_3(input_list):
if not all(isinstance(item, int) for item in input_list):
raise Exception("Input list contains non-numeric values")
return [num for num in input_list if num % 3 == 0]
```
The `isinstance` function is us... | Write a Python function that takes a list of numbers and returns a list of numbers that are divisible by 3. Your function should validate the input list to ensure it contains only numbers. If the input list is invalid, your function should throw an exception. | You can create a Python function that checks for valid numbers in the input list and then returns a new list containing only those numbers that are divisible by 3. The function will raise a `ValueError` if the input list contains any non-numeric values. Here's a suitable implementation:
```python
def get_divisible_by_... | 1,966 |
Randomly splitting a list into two sets can be achieved by first shuffling the list, then slicing it according to the provided ratio.
Here's how you could implement the `random_split()` function:
```python
import random
def random_split(data, ratio):
if ratio < 0 or ratio > 1:
raise ValueError('Ratio mus... | Create a Python function `random_split(data, ratio)` that, given a list `data` and a `ratio` value, returns two lists corresponding to a random split according to the provided ratio. The ratio should be a float between 0 and 1, where 0 returns an empty list and 1 returns a copy of the original list. The function should... | Certainly! Below is a Python function `random_split(data, ratio)` that achieves the desired functionality by splitting the input list `data` according to the specified `ratio`. The function returns two lists, ensuring that the original list remains unmodified.
```python
import random
def random_split(data, ratio):
... | 1,967 |
To correctly handle integer and floating-point inputs with the same precision, it's best to use `decimal.Decimal` for precise numeric calculations.
Here's how you could write the function to handle both integer and floating-point inputs:
```python
import decimal
def convert_to_numeric(input_string):
try:
... | Write a Python function to convert a string value to a numeric value. Handle both integer and floating-point inputs. Ensure that the output matches the input value exactly, even when the input is a string representation of a floating-point value. For example, if the input is `'1.00'`, the output should be `1.00` (not `... | You can achieve this by creating a function that attempts to convert a string to a numerical type while preserving the original format if it represents a floating-point number. Here's a function that does just that:
```python
def convert_to_numeric(value):
"""
Convert a string to a numeric value while preservi... | 1,968 |
Here is the implementation of the function:
```python
import numpy as np
def generate_random_vectors(num_vectors: int) -> np.ndarray:
vectors = np.random.random((num_vectors, 3))
lengths = np.linalg.norm(vectors, axis=1)
vectors = vectors / lengths[:, np.newaxis]
angles = np.arccos(vectors[:, 2]) * 18... | Develop a Python function to generate a set of random 3D vectors, where each vector is a light source position, with the coordinates of its X, Y, and Z components sampled from a uniform distribution and normalized. Additionally, the function should uniformly sample the vectors from a hemisphere to avoid a light source ... | To generate random 3D vectors that represent light source positions uniformly sampled from a hemisphere, we can use the following approach:
1. Generate random points within a unit sphere.
2. Discard any points that fall below the XY-plane since we want points above the plane (hemisphere).
3. Normalize the vectors to e... | 1,969 |
Here's how you could implement the `create_async_task` function:
```python
import asyncio
def create_async_task(func, *args, **kwargs):
loop = asyncio.new_event_loop()
task = loop.create_task(func(*args, **kwargs))
loop.run_until_complete(task)
return task
```
This function creates a new event loop u... | Write a Python function `create_async_task` that creates an asynchronous task (with a function operating asynchronously) and runs the task in an event loop. The function should take the following arguments:
- `func`: The function to be executed asynchronously.
- `*args`: Any positional arguments to be passed to the fu... | You can achieve the desired functionality by defining the `create_async_task` function as follows. This function will create an asynchronous task using the `asyncio` library, and the main event loop will be responsible for running that task. Here’s how to implement it:
```python
import asyncio
def create_async_task(f... | 1,970 |
To merge multiple dictionaries into a single dictionary with a specified arithmetic function, we can follow these steps:
1. Create an empty dictionary to hold the merged result.
2. For each dictionary in the list of dictionaries:
1. Iterate over the key-value pairs.
2. If the key is already present in the merged... | Design a Python function to merge multiple dictionaries into a single dictionary, where the key-value pairs are aggregated using a specified arithmetic function. The arithmetic function will take two numerical values as arguments and return their sum, product, or other mathematical operation. Use deep copy to preserve ... | Certainly! Below is a Python function that merges multiple dictionaries into a single dictionary, using a specified arithmetic function to aggregate the values of the same keys. The function deep copies the original dictionaries to preserve them.
We will use the `copy` module for deep copying and define the merge func... | 1,971 |
Here's an implementation of the `sort_by_length_then_alphabetically` function using the `sorted` built-in function with a custom key function:
```python
def sort_by_length_then_alphabetically(strings):
def key_func(string):
return (len(string), string)
return sorted(strings, key=key_func)
```
In the `... | Design a Python function `sort_by_length_then_alphabetically` that takes a list of strings and returns a list of strings sorted first by the length of the original strings and then alphabetically. | Certainly! You can create a Python function `sort_by_length_then_alphabetically` that uses Python's built-in sorting capabilities to achieve the desired result. The function will first sort the strings by their lengths, and then for strings of the same length, it will sort them alphabetically.
Here's how you can imple... | 1,972 |
Here's a possible implementation of the function using the `re` and `datetime` modules:
```python
import re
from datetime import datetime
def parse_datetime(text):
pattern = r"\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}"
match = re.search(pattern, text)
if match:
datetime_str = match.group(0)
dat... | Given a string of text, parse the first datetime in it and convert it into a `datetime` object. The format of the datetime should be "%Y-%m-%d %H:%M:%S" (YYYY-MM-DD HH:MM:SS). The function should return the converted `datetime` object if found, or `None` if not found.
Your code should pass the following test case:
```... | To achieve the task of parsing the first datetime from a string and converting it into a `datetime` object, we can use Python's `re` module to find the datetime string that matches the specific format. Here's the implementation of the `parse_datetime` function:
```python
import re
from datetime import datetime
def pa... | 1,973 |
Here's a possible implementation of the function:
```python
def replace_placeholders(path, context):
parts = path.split('{{')
result = []
for part in parts:
if '}}' in part:
key = part.split('}}')[0].strip()
keys = key.split('.')
value = context
for k... | Write a Python function that takes a string argument `path` and a Python dictionary `context` as parameters, and returns a new string where occurrences of `{{ key }}` in `path` are replaced with the appropriate value from `context`. `context` may contain nested objects, and the function should be able to access attribu... | You can achieve this by using Python's string manipulation capabilities along with the `jsonpath-ng` library for better handling of nested dictionaries. However, for simplicity, I'll show you a more direct approach using the built-in `str.replace()` method and a custom function to extract values from the nested diction... | 1,974 |
You can use the `divmod()` function to perform integer division and find the remainder on each iteration. This will allow you to decompose the base-10 number into its binary representation.
Here's how you could do it:
```python
def base10_to_base2(base10):
binary = []
while base10 > 0:
quotient, rema... | Write a function that takes a base-10 integer as an argument and returns its base-2 representation. You may use any built-in function or data type, except for the `bin()` function. | Certainly! Below is a Python function that converts a base-10 integer to its base-2 representation without using the `bin()` function. The function repeatedly divides the number by 2 and keeps track of the remainders, which correspond to the bits of the binary representation.
```python
def decimal_to_binary(n):
if... | 1,975 |
We can use a Python function to implement the RLE algorithm. The function will take a string as an input and then iterate over each character in the string.
Here is the implementation of the function:
```python
def compress(input_string):
output_string = ''
current_char = ''
current_count = 0
for cha... | Implement a Python function `compress` that takes a string as input and compresses it using the Run-Length Encoding (RLE) algorithm. The function should return the compressed string.
The RLE algorithm works by replacing consecutive repeated characters in the input string with a single occurrence of the character follo... | Certainly! Below is a Python function named `compress` that implements the Run-Length Encoding (RLE) algorithm. This function takes a string as input and returns the compressed version of that string.
```python
def compress(s: str) -> str:
if not s: # If the string is empty, return an empty string
return ... | 1,976 |
Here's how you can implement this:
```python
def count_unique_integers(integers):
unique = set()
for integer in integers:
if integer not in unique:
unique.add(integer)
return len(unique)
```
This implementation uses a set to keep track of unique integers while iterating over the given ... | Create a Python function that takes a list of integers and returns the number of unique integers in the list. Solve this problem in O(n) time complexity, without using additional data structures.
Your code should pass the following assertion:
```python
assert count_unique_integers([]) == 0
``` | To count the number of unique integers in a list in O(n) time complexity without using additional data structures, we can modify the input list itself. One common technique is to traverse the list and mark visited integers in such a way that we don't require extra space. However, note that this will only work if we can... | 1,977 |
To determine if a point is on an edge of a polygon, you can compare the point's coordinates against the endpoints of each edge in the polygon. The point is considered on an edge if it matches one of the endpoints exactly.
Here's an example function that implements this idea:
```python
def get_edges_of_polygon(points)... | I have a function `get_edges_of_polygon` that takes in a list of points `[x0, y0, x1, y1, ..., xn, yn]` that represent the vertices of a 2D polygon. The function should return a list of line segments, each of which is a pair of coordinates `[x0, y0, x1, y1]` that represent the endpoints of an edge of the polygon.
I ne... | To determine if a point is on the edge of a polygon, you can follow these steps:
1. Use the `get_edges_of_polygon` function to get the edges of the polygon.
2. For each edge, check if the point lies on that edge.
A point `(x, y)` is considered to be on the line segment between two points `(x0, y0)` and `(x1, y1)` if:... | 1,978 |
Here's how you could do it:
```python
def get_urls(string_list):
filtered_urls = []
for string in string_list:
if string.find('youtube') >= 0 or string.find('youtu.be') >= 0:
filtered_urls.append(string)
return filtered_urls
```
This function goes through each string in the list, and... | Write a Python function `get_urls` that takes a list of strings and returns a new list with only the URLs that contain the keywords "youtube" or "youtu.be". Use the built-in `find` function to search for the keywords in each string.
Your code should pass the following test case:
```python
string_list = ['youtube.com/w... | You can achieve the desired functionality by creating a function that iterates through a list of strings and checks each one for the presence of the keywords "youtube" or "youtu.be" using the `find` method. Here's how to define the `get_urls` function:
```python
def get_urls(string_list):
filtered_urls = []
fo... | 1,979 |
You can use `re.match` to match a string against a list of regular expressions, and then use the `return_type` parameter to control the return value. If `return_type` is set to `"match_groups"`, then the function should return a list of match groups. If `return_type` is set to `"match_text"`, then the function should r... | Write a Python function that matches a string against a given set of regular expressions. The function should take an optional parameter named "return_type" that can be "match_groups" or "match_text". If the parameter is set to "match_groups", the function should return a list of match groups. If the parameter is set t... | Here’s a Python function that matches a string against a given set of regular expressions. The function takes an optional parameter `return_type` that determines whether to return match groups, matched text, or a boolean value indicating if a match was found:
```python
import re
from typing import List, Optional, Unio... | 1,980 |
Here's the code:
```python
def aspect_ratio(width, height=1):
return width / height
``` | Write a Python function `aspect_ratio` that takes two positional arguments `width` and `height` and returns their ratio as a float. Set the default value of `height` to 1. If the `height` argument is not passed, use `width` as the denominator and `1` as the numerator.
Your code should pass the following assertions:
``... | You can create the `aspect_ratio` function as described by using default argument values in Python. Here's how to implement the function:
```python
def aspect_ratio(width, height=1):
return width / height
# Testing the function with assertions
assert aspect_ratio(10) == 10.0
assert aspect_ratio(10, 5) == 2.0
```
... | 1,981 |
Here's how you can do it using the `numpy.matmul` function:
```python
import numpy as np
def matrix_product(a, b):
return np.matmul(a, b)
```
You can also use the `@` operator, which is equivalent to the `numpy.matmul` function:
```python
import numpy as np
def matrix_product(a, b):
return a @ b
```
The N... | Create a Python program that takes two `numpy` arrays of shape (N, M) and (M, K) and returns a numpy array of shape (N, K) that represents the product of the two matrices. The program should handle any device-dependent code, such as GPU or CPU.
Your code should pass the following test case:
```python
a = np.array([[1,... | Here's a Python program that utilizes NumPy to perform matrix multiplication, supporting both CPU and GPU computations using CuPy if available. CuPy is a library that provides a NumPy-like API for GPU-accelerated computing. If CuPy is not installed, it will fall back to using NumPy exclusively for CPU computations.
``... | 1,982 |
To create such a function in Python, we can use the `math.radians` function provided by the standard math module. This function takes an angle in degrees and returns the corresponding value in radians.
```python
import math
def angle_degree_to_radians(angle_in_degrees):
angle_in_radians = math.radians(angle_in_de... | In Python, create a function that takes the value of an angle in degrees and returns the value of the same angle in radians. Use the `math.radians` function for this conversion. Name your function `angle_degree_to_radians`. | Certainly! Below is a Python function named `angle_degree_to_radians` that takes an angle in degrees and returns the corresponding value in radians using the `math.radians` function.
```python
import math
def angle_degree_to_radians(degrees):
"""Convert an angle from degrees to radians."""
return math.radians... | 1,983 |
Here's how you can implement the `calculate` function:
```python
def calculate(expression):
return eval(expression)
```
The `eval` function is a built-in Python function that takes a string as an argument and evaluates it as if it were a Python expression. This means that it can parse and evaluate expressions suc... | Write a Python function `calculate` that takes a string representing a simple mathematical expression and calculates its result. The expression can contain numbers, `*`, `/`, `+`, `-`, `(` and `)`.
For example, given `"1 + 2 * 3"`, the function should output the result `7`.
To solve this problem, you can use Python's... | You can write a function `calculate` to evaluate a simple mathematical expression using Python's built-in `eval` function. Here is how you could implement it:
```python
def calculate(expression: str) -> float:
try:
# Evaluate the mathematical expression and return the result
result = eval(expressio... | 1,984 |
Here's one way to implement the `comma_insert` function:
```python
def comma_insert(input_str):
if not isinstance(input_str, str) or not input_str.isnumeric():
return '' # Return an empty string or handle the error appropriately
number = int(input_str)
if number < 1000:
return input_str ... | Design a Python function `comma_insert` that takes a string `input_str` and inserts commas into the number, where each comma represents the thousands place. The function should return the formatted string with commas inserted. For example, given the input `str = "123456789"`, the function should return the formatted st... | To accomplish the task of inserting commas into a numerical string to represent thousands, we can leverage Python’s built-in formatting features. Below is a implementation of the `comma_insert` function that takes a string, checks if it's valid, and formats it accordingly.
Here's the implementation:
```python
def com... | 1,985 |
To generate the $n$th Fibonacci number using memoization, we can store the previously calculated Fibonacci numbers in a dictionary to avoid unnecessary calculations. This optimization reduces the time complexity to $O(n)$ from $O(2^n)$, which is exponential without memoization.
```python
def fibonacci(n):
if n < 0... | Create a Python function to generate the $n$th term of the Fibonacci sequence, where $n$ is a non-negative integer. The Fibonacci sequence is defined as: $F_0 = 0$, $F_1 = 1$, $F_n = F_{n-1} + F_{n-2}$ for $n \ge 2$. Your function should use memoization to improve efficiency. | You can create a Python function to generate the nth term of the Fibonacci sequence using a technique called memoization to enhance efficiency. Below is an example of how you might implement this:
```python
def fibonacci(n, memo={}):
# Check if the value has already been computed
if n in memo:
return m... | 1,986 |
Here is how you could implement this composition function:
```python
def compose_fns(f, g):
def compose_fns_inner(x):
try:
return g(f(x))
except Exception as e:
raise e
return compose_fns_inner
``` | Given two functions, `f` and `g`, create a new function `compose_fns` that returns a composed function that calls `f` and `g` on the given input, in that order, and returns the result of the last call. If any of the calls to `f` or `g` raises an exception, the composed function should raise the exception and skip calli... | To create a function `compose_fns` that composes two functions `f` and `g`, we can define it as follows:
```python
def compose_fns(f, g):
def composed_function(x):
try:
result_f = f(x)
except Exception as e:
raise e # Reraise the exception without calling g
try:
... | 1,987 |
Here's how you can implement this:
```python
def create_sorting_function(order):
def sort_numbers(numbers, order=order):
if order == "ascending":
return sorted(numbers)
elif order == "descending":
return sorted(numbers, reverse=True)
else:
raise ValueErro... | Create a Python function `create_sorting_function` that takes a sorting order (either "ascending" or "descending") as an argument and returns a function that sorts a list of numbers according to that order. | Certainly! You can create the `create_sorting_function` in Python by defining a higher-order function that returns a sorting function based on the specified order. Here’s how you can implement this:
```python
def create_sorting_function(order):
if order == "ascending":
def sort_function(numbers):
... | 1,988 |
Here's how you can implement this function:
```python
import numpy as np
def compute_absolute_value(array: np.ndarray) -> np.ndarray:
if not isinstance(array, np.ndarray):
raise ValueError("Input must be a Numpy array.")
return np.abs(array)
```
This function checks if the input is a valid Numpy arr... | Write a Python function to compute the absolute value of each element in a Numpy array, which is a fundamental operation in math and linear algebra. | You can compute the absolute value of each element in a NumPy array using the `numpy.abs()` function or the `numpy.absolute()` function. Here’s a Python function that takes a NumPy array as input and returns another array containing the absolute values of the original array's elements:
```python
import numpy as np
de... | 1,989 |
Here is how you could implement the function `is_github_url`:
```python
import re
def is_github_url(url):
pattern = r"^https://github\.com/([a-zA-Z0-9_\-]+)/([a-zA-Z0-9_\-]+)$"
match = re.match(pattern, url)
if match:
return True
else:
return False
```
The function `is_github_url` tak... | Write a Python function `is_github_url` that takes a URL string as input and returns a boolean value indicating whether the URL is a valid GitHub URL. The function should check if the URL matches the following pattern: `https://github.com/<user>/<repo>`, where `<user>` and `<repo>` correspond to the GitHub username and... | To implement the `is_github_url` function in Python, we will utilize regular expressions (regex) to validate the URL format according to your specifications. Specifically, we will check that the URL begins with `https://github.com/`, followed by a valid GitHub username and a valid repository name.
Here’s a possible i... | 1,990 |
We can use the `getattr` function to get the method from the object. We will iterate through the list of method names and corresponding arguments, invoking the method with the given arguments and storing the result in a list. If the method name is not valid for the object, we will skip it. For invalid arguments, we wil... | Write a Python function that takes three arguments as input: an object, a list of method names, and a list of method arguments. The function should iterate through the given list of method names, invoke the method with the corresponding arguments, and return the result. If the method name is not valid for the object, i... | Below is a Python function that accomplishes the task you've described. The function `invoke_methods` will take an object, a list of method names, and a list of arguments (where each entry corresponds to a method). It will invoke the methods if they are valid for the object and check if the argument counts match. If th... | 1,991 |
Here's a possible implementation of the function:
```python
lookup_table = {
0: "Monday",
1: "Tuesday",
2: "Wednesday",
3: "Thursday",
4: "Friday",
5: "Saturday",
6: "Sunday",
}
def get_days_of_week(numbers):
days = []
for number in numbers:
if number in lookup_table:
... | Write a Python function that takes a list of integers and returns a list of strings representing the corresponding days of the week. The function should accept a list of integers and return a list of strings representing the days of the week. A lookup table for the mapping should be used. | Certainly! Below is a Python function that takes a list of integers and maps them to corresponding days of the week using a lookup table. The integers are expected to range from 0 to 6, where 0 corresponds to 'Sunday', 1 to 'Monday', and so on, up to 6 which corresponds to 'Saturday'.
```python
def map_integers_to_day... | 1,992 |
Here's how we can implement this:
```python
def does_function_have_any_parameter_named(function, parameter_name):
return parameter_name in function.__code__.co_varnames
``` | Write a Python function `does_function_have_any_parameter_named(function, parameter_name)` that checks whether a given function has any parameter named `parameter_name` (a string). If the parameter exists, then the function should return `True`. Otherwise, return `False`.
The function should check the function's param... | You can create the function `does_function_have_any_parameter_named` by accessing the function's `__code__` attribute, which provides information about its arguments. Specifically, you'll want to look at the `co_varnames` attribute of the `__code__` object to check for the presence of the parameter name. Here’s how you... | 1,993 |
Here's an implementation of the function:
```python
def get_batting_order(team):
return [(player['person']['fullName'], player['battingOrder']) for player in team['roster'] if 'battingOrder' in player]
```
This function uses list comprehension to generate a list of tuples, where each tuple contains the player's n... | I want to display the roster of a team in MLB. The API returns a JSON object with the attribute `team`, which has the attribute `roster` which is a list. This is the list of player objects. This list is ordered by the `battingOrder` attribute.
Write a function that takes the team as an input and returns a list of tupl... | You can create a function in Python that takes a team data structure (assumed to be a parsed JSON object) and extracts the player names along with their batting order into a list of tuples. Below is an example function that accomplishes this:
```python
def get_roster_with_batting_order(team):
# Extract the roster ... | 1,994 |
This function requires string manipulation to remove the suffix from a string. The Python string manipulation methods and splicing operations can be used to achieve this goal.
Here's how you can implement the `strip_suffix` function:
```python
def strip_suffix(string, suffix):
if string.endswith(suffix):
... | Create a Python function `strip_suffix` that removes a specified suffix from a string. The function should perform string manipulation and splicing operations to achieve this task. Include an assertion to ensure the input string ends with the specified suffix. If the suffix is not found, the function should raise an er... | Certainly! Below is a Python function called `strip_suffix` that removes a specified suffix from a given string. The function includes an assertion to check that the input string ends with the specified suffix, and it raises a `ValueError` if the suffix is not found.
Here is the implementation:
```python
def strip_su... | 1,995 |
Here's an example of how you can implement this:
```python
import itertools
def concat_strings(strings, separator):
return list(itertools.chain.from_iterable([s.split(separator) for s in strings]))
``` | Write a Python function to concatenate multiple lists of strings into a single list, where each string is separated by a given separator.
Your code should pass the following assertions:
```python
assert concat_strings(['1|2|3', '4|5|6'], '|') == ['1', '2', '3', '4', '5', '6']
assert concat_strings(['1 2 3', '4 5 6'], ... | You can achieve the desired functionality by defining a function `concat_strings` that takes a list of strings and a separator. The function will split each string in the list by the given separator and then flatten the result into a single list. Here's how you can implement this function:
```python
def concat_strings... | 1,996 |
Here's how you could do it:
```python
def split_numbers(input_string):
try:
num_list = input_string.split(',')
int_list = [int(num) for num in num_list]
return int_list
except ValueError:
raise ValueError('Invalid input string. Not all elements can be converted to integers.')
`... | Write a Python function that splits a string of comma-separated numbers and returns a list of integers. Validate the input to ensure all elements can be converted to integers.
For example, given the input string '1,2,3,4,5', the function should return the list [1, 2, 3, 4, 5]. If the input string is invalid, raise an ... | Certainly! Below is a Python function that splits a given string of comma-separated numbers and returns a list of integers. The function also includes validation to ensure that all elements can be converted to integers, and raises a `ValueError` if any conversion fails.
```python
def split_and_convert_to_integers(inpu... | 1,997 |
Here's a possible implementation of the `is_magic_sum` function:
```python
def is_magic_sum(numbers):
if not numbers or len(numbers) < 3:
return False
if not all(isinstance(x, (int, float)) for x in numbers):
return False
return numbers[0] + numbers[1] == numbers[-1]
```
The function first... | Write a Python function that takes a list of numbers and returns `True` if the sum of the first two numbers is equal to the last number, `False` otherwise. The function should return `False` if the list is empty, or if the elements are not numbers, or if the length of the list is less than three.
Here's an example:
``... | You can create the `is_magic_sum` function as described. Here’s the implementation:
```python
def is_magic_sum(numbers):
# Check if the list is empty or has less than three elements
if len(numbers) < 3:
return False
# Check if all elements are numbers
if not all(isinstance(x, (int, float))... | 1,998 |
Here's how you can implement the function:
```python
def add_attribute(class_name, attribute_name, attribute_type, attribute_value):
class_dict = {attribute_name: attribute_type}
new_class = type(class_name, (), class_dict)
setattr(new_class, attribute_name, attribute_value)
return new_class
``` | Implement a Python function to add a new attribute to an existing class. The function takes four arguments:
- class_name: The name of the class to add the attribute to.
- attribute_name: The name of the attribute to be added.
- attribute_type: The type of the attribute (e.g., `str`, `int`, etc.)
- attribute_value: The... | To implement the function that adds a new attribute to an existing class, we can utilize Python's `type` function, which allows us to dynamically create classes. Here's how we can achieve this:
```python
def add_attribute(class_name, attribute_name, attribute_type, attribute_value):
# Create a new class with the s... | 1,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.