response_seed stringlengths 53 5.17k | instruction_seed stringlengths 29 4.02k | response stringlengths 16 8.81k | __original_row_idx int64 0 50k |
|---|---|---|---|
Here's an example implementation of the `add_noise_to_torch_tensor` function in Python:
```python
def add_noise_to_torch_tensor(tensor, scale, device):
noise = torch.randn(tensor.shape, device=device) * scale
return tensor + noise
``` | Create a Python function `add_noise_to_torch_tensor` that adds Gaussian noise to a PyTorch tensor. The function should take three parameters: `tensor`, the tensor to which noise is to be added; `scale`, the standard deviation of the noise distribution; and `device`, the device on which the noise tensor will be created.... | Certainly! Below is the Python function `add_noise_to_torch_tensor` that adds Gaussian noise to a given PyTorch tensor, following the specifications you've outlined.
```python
import torch
def add_noise_to_torch_tensor(tensor, scale, device):
"""
Adds Gaussian noise to a PyTorch tensor.
Parameters:
-... | 24,100 |
Here's how you can implement the function:
```python
import re
def replace_tag(input_string, value):
pattern = r'{{\s*(\w+)\s*}}'
return re.sub(pattern, value, input_string)
``` | Create a Python function to replace the placeholder tag with the provided value. The function should process the placeholder tag and output the final string. The placeholder tag is in the format of {{placeholder}}.
Your code should pass the following assertions:
```python
assert replace_tag("Hi, {{name}}, how are you?... | You can achieve this by creating a function that takes a string with a placeholder tag and a value, then replaces the placeholder with the given value. Here's a Python function that accomplishes this:
```python
def replace_tag(text: str, value: str) -> str:
placeholder = "{{name}}"
return text.replace(placehol... | 24,101 |
To search for a value in a dictionary and return the corresponding key and value if found, we need to iterate through the dictionary using a for loop. We can use the `items()` method to get the key-value pairs, and then check if the value matches the given value. If it does, we can return the key-value pair as a tuple.... | Write a Python function to perform a search on a dictionary, returning a tuple of the key and value if found, or None and None when not found. You may assume the dictionary only has unique values (no duplicate keys or values). If the value is not found, your function should return None and None. If the value is found, ... | You can implement a function called `search_dictionary` which iterates through the dictionary's items to find the specified value. If the value is found, it will return the corresponding key and value as a tuple; otherwise, it will return `(None, None)`. Here's the implementation:
```python
def search_dictionary(dicti... | 24,102 |
Here's how you could implement the `is_truthtable_equal` function:
```python
def is_truthtable_equal(table1, table2):
rows1 = {(row[0], row[1]) for row in table1}
rows2 = {(row[0], row[1]) for row in table2}
return rows1 == rows2
```
The `is_truthtable_equal` function takes in two truth tables and convert... | You're working with a truth table that represents a Boolean expression. The truth table is represented by a list of rows, where each row is a list of boolean values representing the inputs and the output of the Boolean expression.
Write a function `is_truthtable_equal` that takes in two truth tables and returns True i... | To determine whether two truth tables are equal while disregarding the order of the rows, we can take advantage of Python's set data structure, which allows for easy comparison of collections.
We'll define the function `is_truthtable_equal` that converts each truth table into a set of tuples (since lists cannot be add... | 24,103 |
```python
db = ["john", "mary", "ann"]
def taken_by_default(user, db):
return user in db
def check_username_availability(user, db, taken=taken_by_default):
return not taken(user, db)
user = "bob"
print(check_username_availability(user, db)) # Output: True
user = "mary"
print(check_username_availability(user, db... | Write a Python function `check_username_availability(user, db, taken=taken_by_default)` that takes a user name, a database, and an optional first-class function `taken` as an argument. `taken` is a predicate that takes a username and returns True if the username has already been taken. The function should return True i... | Here's how you can implement the `check_username_availability` function along with the provided `taken_by_default` function. The function will check if a given username is available based on the criteria provided.
Here is the complete code:
```python
def taken_by_default(user):
"""
Return True if user is in d... | 24,104 |
Here's how you can do it in two lines of Python code:
```python
def symmetric_diff(set_a, set_b):
return set_a.symmetric_difference(set_b) - set_a.intersection(set_b)
```
The `-` operator performs set subtraction, which removes the elements from the left set that are also present in the right set. By subtracting ... | Design a Python function that takes two sets (sets of integers) `A` and `B` and returns a set (set of integers) that contains all the elements that are either in `A` or `B` but not both. In other words, the function should return the symmetric difference of the two sets.
Your code should pass the following assertions:... | You can create a function to calculate the symmetric difference of two sets in Python by using the built-in set operations. The symmetric difference can be obtained using the `^` operator or the `symmetric_difference` method provided by Python's set data type. Here's how you can implement the `symmetric_diff` function:... | 24,105 |
Here's how you can implement it:
```python
def restructure_data(data, key):
return {item[key]: item for item in data}
``` | Create a Python function that takes a list of dictionaries and a key as input, and returns a new dictionary where the keys are the values of the given key from the input dictionaries, and the values are the corresponding dictionaries from the input list. For example, given the input:
```python
data = [
{'key1': 'v... | You can achieve this in Python by defining a function that iterates through the list of dictionaries, extracts the value for the specified key, and constructs a new dictionary based on that value. Here's a sample implementation of the function:
```python
def transform_list_to_dict(data, key):
result = {}
for i... | 24,106 |
Here is the implementation of the function:
```python
def multiply_signed_integers(n: int, factor: int = 1) -> int:
"""
Multiply two signed integers and return the result.
Args:
n: A signed integer.
factor: A signed integer with a default value of 1.
Returns:
An integer result... | Develop a Python function with the following requirements:
* The function takes a required argument `n` and an optional named argument `factor` with a default value of `1`.
* The function returns an integer result.
* The function should be documented using a docstring.
Within the function, the following steps are per... | Here's a Python function that meets the specified requirements:
```python
def multiply_signed_integers(n, factor=1):
"""
Multiply two integers while handling their signs.
Parameters:
n (int): The first integer to multiply.
factor (int, optional): The second integer to multiply, default is 1.
... | 24,107 |
To extract the variable names from Python code, we can use the `ast` module to parse the code and traverse the abstract syntax tree (AST) in a top-down fashion. The `ast` module provides a set of classes and methods for working with Python abstract syntax trees.
By using the `ast` module, we can readily parse the code... | Write a Python function `extract_variable_names` that takes a string containing Python code and returns a list of variable names that are assigned a value within the code. The function should traverse the code in a top-down fashion and include the variable names in the returned list only if they are assigned a value wi... | To create a function `extract_variable_names` that extracts variable names from Python code, we can utilize the Abstract Syntax Tree (AST) module in Python. This allows us to parse the code into a tree structure where we can navigate to find assignments.
Here's how you can implement the function:
```python
import ast... | 24,108 |
Here's how you can do it in Python:
```python
import re
def transform_file_names(file_names):
pattern = r"^[\w]+[-_]"
return [re.sub(pattern, "", name).capitalize() for name in file_names]
``` | Assume you have a list of file names containing both alphanumeric characters and other special characters such as underscores and dashes. For example, you may have file names like `["file-A.txt", "file_B.txt", "file-c.txt", "file_d.txt"]`. Write a Python function that takes a list of file names as input and returns a l... | Certainly! Below is a Python function that takes a list of file names and transforms them as per your requirements. It removes any leading alphanumeric characters followed by an underscore or a dash and capitalizes the first letter of the remaining part of each file name.
```python
def transform_file_names(file_names)... | 24,109 |
Here's how you can do it in Python:
```python
import re
def extract_first_digit(input_string):
first_digit = re.search(r"\d", input_string)
return first_digit.group(0) if first_digit else ""
```
You use a regular expression to match a digit in the string and extract it using the `group` method. If no digit i... | Write a Python function to check if a given string contains any of the digits 0-9. If so, the function should return the substring of the first digit it encounters. Otherwise, it should return an empty string. The function should not raise any exceptions.
Your code should pass the following assertions:
```python
asser... | You can achieve this by iterating through the given string and checking each character to see if it is a digit. If a digit is found, the function should return that digit immediately. If no digits are found, it should return an empty string. Here's a Python function that accomplishes this:
```python
def extract_first_... | 24,110 |
We can fix this bug by using parentheses to group the conditions properly:
```python
def is_one_of_fixed(x):
return (x == 1 or x == 2) and (x != 3)
```
By wrapping the second condition in parentheses, we ensure that it is evaluated after the first condition, ensuring that the function only returns True when the inp... | The following function is supposed to determine whether the input value is equal to 1, 2, or 3. However, it does not work as intended. Modify the function to fix the bug so it returns True only when the input is 1, 2, or 3.
```python
def is_one_of(x):
return (x == 1 or x == 2) and x != 3
```
Your code should pass t... | The issue in your function is the incorrect logic used to check if `x` is equal to 1, 2, or 3. The current expression will return `True` for 1 and 2, but it will return `False` for 3 incorrectly, as the logic `(x == 1 or x == 2) and x != 3` means it will be `True` for 1 and 2, but will return `False` for 3 since it wil... | 24,111 |
To implement this function, you will need to consider the following steps:
1. Check if the target length is smaller than or equal to the length of the input sequence.
2. If the target length is smaller than the length of the input sequence, truncate the sequence to the target length by slicing the sequence.
3. If the ... | Write a Python function to truncate a sequence to a given length and pad it with zeros if the sequence is shorter than the given length. The function should return a new sequence with the required length.
For example, if the sequence is `[1, 2, 3]` and the target length is 5, the function should return `[1, 2, 3, 0, 0... | You can achieve this by creating a function that checks the length of the input sequence and modifies it accordingly. Here's how you can implement the function:
```python
def truncate_and_pad(sequence, target_length):
# Truncate the sequence if it's longer than the target length
truncated_sequence = sequence[:... | 24,112 |
To extract unique email addresses from a string using regular expressions, you can use a regular expression pattern that matches valid email addresses. You can also use `set()` to ensure that no duplicates are included in the output list.
To handle any exceptions that occur while parsing the string, you can use a `try... | Write a Python function to extract all unique email addresses from a text string using regular expressions. The function should take a string argument and return a list of unique email addresses.
If an exception occurs while parsing the string, the function should return an empty list.
Your code should pass the follo... | To extract unique email addresses from a text string using regular expressions in Python, we can define a function called `extract_unique_emails`. This function will handle the parsing using a regex pattern to find all email addresses. If any exception occurs during the parsing process, it will return an empty list.
H... | 24,113 |
To clean up the given text, we can use regular expressions to remove all newlines, tabs, and replace all sequences of multiple spaces with a single space. To support Unicode characters, we can use the `re` module's `sub()` function with the `re.UNICODE` flag.
Here is a Python function that implements the above using r... | Write a Python function `get_clean_text(text)` to clean up the given text. The function should remove all newlines, tabs, and replace all sequences of multiple spaces with a single space. Additionally, it should support Unicode characters. Implement the function using regular expressions and include the following test ... | You can implement the `get_clean_text` function using the `re` module in Python, which provides support for regular expressions. The function will need to perform the following steps:
1. Remove all newlines and tabs from the text.
2. Replace sequences of multiple spaces with a single space.
Here's how you can impleme... | 24,114 |
Here's how we can implement `exp_v2` using the square-and-multiply approach:
```python
def exp_v2(x, n):
if n <= 1:
return x
elif n % 2 == 0:
return exp_v2(x, n // 2) * exp_v2(x, n // 2)
else:
return x * exp_v2(x, n - 1)
```
In this implementation, we define a function `exp_v2(x, n... | Given a Python function `exp(x, n)` that computes $x^n$ for any integer $n$ and float $x$, write a new function `exp_v2(x, n)` that computes $x^n$ in fewer than $n$ multiplications.
You may assume that `exp(x, n)` is already defined and works correctly. For example, `exp_v2(2, 3)` should return `8` and `exp_v2(5, 10)`... | To compute \( x^n \) using fewer than \( n \) multiplications, we can use the "Exponential by Squaring" method. This method allows us to recursively compute \( x^n \) efficiently by leveraging the properties of exponents:
- If \( n \) is even, \( x^n = (x^{n/2})^2 \)
- If \( n \) is odd, \( x^n = x \cdot x^{n-1} \)
B... | 24,115 |
To implement this function, we can iterate through the items in the dictionary `d` and check if the value of the item is equal to `v`. If it is, we add the corresponding key to the list we're returning. If we don't find any keys with the value `v`, we return an empty list.
Here's one way to implement the function:
``... | Write a Python function that takes a dictionary `d` and a value `v` and returns a list of all keys that have `v` as their value in `d`. The function should return an empty list if there are no keys with `v` as their value.
Your code should pass the following test case:
```python
d = {"key1": "value1", "key2": "value2"... | You can achieve this by iterating through the dictionary and checking for keys that have the specified value. Here's a Python function that implements this logic:
```python
def get_keys_from_value(d, v):
return [key for key, value in d.items() if value == v]
# Test case
d = {"key1": "value1", "key2": "value2", "k... | 24,116 |
We can use `copy.deepcopy` to create a deep copy of the dictionary and use `json.dumps` to serialize it into a JSON string. Then, we can use a clever dictionary comprehension to replace the large byte strings with a smaller representation.
```python
import copy
import json
def reduce_file_size(input_dict):
result... | Write a Python function `reduce_file_size` that takes a dictionary as input. The function should iterate through the dictionary and check if any keys contain large byte strings. If so, it should use `copy.deepcopy` to create a deep copy of the dictionary and replace the byte strings with a smaller representation. Then,... | Certainly! Below is a Python function `reduce_file_size` that performs the specified operations. The function takes a dictionary as input, checks for large byte strings, creates a deep copy if necessary, reduces the size of the byte strings, and then serializes the dictionary to a JSON string.
```python
import copy
im... | 24,117 |
You can achieve this functionality by first splitting the input string by commas to get a list of strings. Then, use a `try-except` block to handle any invalid inputs, where the strings cannot be converted to integers. Finally, return the list of integers if no errors occur.
Here's how you can do it in three lines of ... | Write a Python function to convert a text input representing a list of values separated by commas into a list of integers. The function should handle invalid inputs, where the input is not a list of valid integers, and return an empty list. For example, the input `'1,2,3'` should return `[1, 2, 3]`, and the input `'1,2... | You can accomplish this by defining a function that takes a string input, splits it by commas, and tries to convert each element to an integer. If it encounters any value that cannot be converted to an integer, it will return an empty list. Here’s how you could implement this in Python:
```python
def convert_to_int_li... | 24,118 |
Here's how you can implement this:
```python
def get_top_n_pairs_from_dict(d, n):
sorted_dict = sorted(d.items(), key=lambda item: item[1], reverse=True)
pairs = [(key, value) for key, value in sorted_dict]
return pairs[:n]
``` | Write a Python function `get_top_n_pairs_from_dict` that takes two arguments: a dictionary `d` and an integer `n`. The function should return a list of the top `n` key-value pairs in the dictionary `d` where each pair is a tuple of the form `(key, value)`.
The function should work as follows:
1. Sort the dictionary `... | Certainly! Below is the implementation of the `get_top_n_pairs_from_dict` function in Python:
```python
def get_top_n_pairs_from_dict(d, n):
# Sort the dictionary by values in descending order and create a list of tuples
sorted_pairs = sorted(d.items(), key=lambda item: item[1], reverse=True)
# Return... | 24,119 |
To deduplicate a list in Python, you can use the `set` data type to create a new set with unique elements. By using the `in` operator to check if an element is in the set, you can determine whether it has been seen before.
Here's how you can implement the `dedupe_and_count` function:
```python
def dedupe_and_count(ls... | Write a Python function `dedupe_and_count(lst)` that returns a tuple consisting of a deduped list and the number of unique elements in the original list. Use a `set` to store the unique elements and check membership to determine whether an element has been seen before.
Your code should pass the following assertion:
``... | To create the function `dedupe_and_count(lst)` that returns a deduplicated list along with the count of unique elements, we can follow these steps:
1. Use a set to keep track of unique elements.
2. Use a list to store the deduplicated elements in their original order.
3. Iterate through the input list, checking if eac... | 24,120 |
Here is the implementation of a Python function `check_line_segment_inside_rectangle` that checks if a given 2D line segment lies within a rectangle or not:
```python
def check_line_segment_inside_rectangle(p1, p2, p3, p4, p5, p6):
def cross_product(p1, p2, p3):
return (p2[0] - p1[0]) * (p3[1] - p1[1]) - (... | Write a Python function to check if a given 2D line segment lies within a rectangle or not.
Consider a line segment $L = (p_1, p_2)$ and a rectangle $R = (p_3, p_4, p_5, p_6)$, where $p_1, p_2, p_3, p_4, p_5, p_6$ are 2D points. The task is to check if $L$ lies within $R$. Assume that:
- The rectangle $R$ has distinc... | To check if a given 2D line segment lies entirely within a rectangle, we need to employ some geometric checks. The provided formula can be used to determine if a point lies within the rectangle; specifically, it applies to the cross-product to establish the relative position of points with respect to the sides of the r... | 24,121 |
```python
def calculate_bpm(song_length_sec, num_beats):
minutes_in_a_second = 1/60
song_length_minutes = song_length_sec * minutes_in_a_second
bpm = num_beats / song_length_minutes
return bpm
``` | Write a Python function to calculate the BPM (beats per minute) of a song given its length in seconds and the number of beats it has. | You can calculate the BPM (beats per minute) of a song using the following formula:
\[
\text{BPM} = \left( \frac{\text{number of beats}}{\text{length in seconds}} \right) \times 60
\]
Here's a Python function that takes the length of the song in seconds and the number of beats as input and returns the BPM:
```python... | 24,122 |
To combine elements from two sets into pairs, you can use the `zip()` function in Python. The `zip()` function iterates over the two sets and creates tuples containing corresponding elements from each set. However, the returned list of tuples will have the same size as the smallest of the two sets.
Here's how you coul... | Write a Python function `zip_sets` that accepts two sets as arguments and returns a list of tuples with each tuple containing one element from each set. The returned list of tuples should be the same size as the smallest of the two sets. | Certainly! Below is a Python function named `zip_sets` that takes two sets as arguments and returns a list of tuples. Each tuple contains one element from each set, and the size of the returned list will match the size of the smaller set.
```python
def zip_sets(set1, set2):
# Convert sets to lists to enable zippin... | 24,123 |
To implement the `select_first` function, you can follow these steps:
1. Check if the given string is empty or contains only whitespace. If so, return `None`.
2. Iterate through the characters in the string using a `for` loop.
3. If the current character is not a whitespace character, return that character.
4. If the ... | Implement the `select_first` function, which takes a string as an argument and returns the first non-whitespace character in the string. If the given string is empty or contains only whitespace, the function should return `None`.
Your code should pass the following assertions:
```python
assert select_first(" ") is Non... | You can implement the `select_first` function in Python as follows:
```python
def select_first(s):
# Check if the input is None
if s is None:
return None
# Loop through each character in the string
for char in s:
# Check if the character is not a whitespace character
if not... | 24,124 |
To write a function that takes a list of `Person` objects and returns the sum of their ages, follow these steps:
1. Validate the input: Ensure the input is a list of `Person` objects. If it's not, raise a `TypeError` with a detailed error message.
2. Validate each `Person` object: Iterate over the list and validate ea... | Write a Python function that takes a list of `Person` objects and returns the sum of their ages. Each `Person` object has an `age` attribute, which is an integer. Ensure the function validates that the `age` attribute is an integer before summing it. If the `age` attribute is not an integer, the function should raise a... | To create a function that sums the ages of `Person` objects with the necessary validations, we first need a definition for the `Person` class. Then, we'll define the function that processes a list of `Person` instances.
Here's how you can implement this:
```python
class Person:
def __init__(self, age):
se... | 24,125 |
```python
import pandas as pd
def compare_dataframes(df1, df2):
if df1.columns.tolist() != df2.columns.tolist():
return False
for col in df1.columns:
if df1[col].dtype != df2[col].dtype:
return False
return True
``` | Write a Python function that takes two Pandas DataFrames as input and checks if they have the same column names and data types. The function should return `True` if the DataFrames are identical, and `False` otherwise. | You can achieve this by comparing the column names and their corresponding data types in the two DataFrames. Below is a Python function that accomplishes this task:
```python
import pandas as pd
def are_dataframes_identical(df1: pd.DataFrame, df2: pd.DataFrame) -> bool:
# Check if the columns are the same
if ... | 24,126 |
Here is a Python function that implements this approach:
```python
from typing import List
def matrix_to_vector(matrix: List[List[int]], row_offset: int) -> List[int]:
"""
Converts a matrix to a vector in row-major order.
"""
vector = []
for row in range(row_offset, len(matrix)):
for col i... | Design a Python function named `matrix_to_vector` that returns a vector containing all the elements of the given matrix in row-major order. The function should accept two arguments, `matrix` and `row_offset`, and return a vector.
The `matrix` argument is a two-dimensional list representing the input matrix, and the `r... | Here's how you can implement the `matrix_to_vector` function in Python to convert a specified portion of a two-dimensional list (matrix) into a one-dimensional list (vector) in row-major order, based on a specified row offset:
```python
def matrix_to_vector(matrix, row_offset):
# Check if the row_offset is within ... | 24,127 |
To generate a random tensor with the Bernoulli distribution, we can use the `torch.distributions.Bernoulli` class from PyTorch. The `torch.distributions.Bernoulli` class provides the ability to sample random values from a Bernoulli distribution, which can be used to generate a tensor of the desired shape with values sa... | Given a 4D tensor with shape `(batch_size, height, width, channels)`, create a function that generates a tensor of the same shape with random values sampled from a Bernoulli distribution with probability `p = 0.2`.
Your code should pass the following test case:
```python
test_data = [(1, 2, 3, 4), (4, 3, 2, 1)]
for sh... | You can create a function to generate a 4D tensor filled with random values sampled from a Bernoulli distribution by using libraries like NumPy or TensorFlow. Here's how you can implement this function using NumPy:
```python
import numpy as np
def generate_bernoulli_tensor(shape, p=0.2):
"""
Generate a 4D ten... | 24,128 |
Here is the implementation of the `camel_case` function:
```python
def to_camel_case(word):
return word.lower().capitalize()
def camel_case(string):
if not isinstance(string, str):
return ''
words = string.split()
camel_case_words = [to_camel_case(word) for word in words]
return ''.join(ca... | Write a Python function `camel_case` that takes a string as input and returns a new string with each word in camel case. The function should perform the following steps:
- Split the string into individual words based on whitespace characters.
- Convert each word to camel case by capitalizing the first letter and lower... | Sure! Below is a Python function called `camel_case` that follows the specified requirements. It first checks if the input is a valid string, then processes it to return the camel-cased version of the words.
```python
def camel_case(input_string):
# Check if the input is a valid string
if not isinstance(input_... | 24,129 |
To extract the text content from all HTML tags that match a specific tag name, you can use a regular expression to match the tag name and its contents, including nested tags. The regular expression should start with an opening tag, match the tag name, then match any content within the tag, including nested tags, and fi... | Write a Python function to extract the text content from all HTML tags that match a specific tag name, including nested tags. For example, if the input HTML string is `<body><h1>Hello World!</h1><p>This is a paragraph.</p><div><h2>Another Heading</h2><p>This is another paragraph.</p></div></body>`, the output should be... | You can achieve this by using the `BeautifulSoup` library from the `bs4` package in Python. This library makes it easy to parse HTML and extract elements based on their tags.
Here's a function that extracts text content from all tags that match a specific tag name, including nested tags:
```python
from bs4 import Bea... | 24,130 |
Here is a Python function that implements this approach:
```python
def get_min_max_value(nums):
if not nums:
return None, None
min_value = max_value = nums[0]
for num in nums[1:]:
if num < min_value:
min_value = num
elif num > max_value:
max_value = num
... | Write a Python function `get_min_max_value` that takes a list of numbers as an input and returns the minimum and maximum values from the list. The function should return a tuple of two values, where the first value is the minimum and the second value is the maximum. If the list is empty, the function should return `Non... | You can implement the `get_min_max_value` function in Python as follows. This function will check if the input list is empty and, if not, will find the minimum and maximum values using the built-in `min()` and `max()` functions.
Here's the code for the function:
```python
def get_min_max_value(numbers):
if not nu... | 24,131 |
Here's how we can implement this:
```python
def getattr_path(obj, path):
path_parts = path.split('.')
for attr in path_parts:
try:
obj = getattr(obj, attr)
except AttributeError:
return None
return obj
```
In this implementation, we first split the string path into ... | Implement a Python function `getattr_path` that takes an object and a list of attribute names as a string path and returns the value of that attribute. If the path is invalid or the attribute does not exist, return `None`. | Certainly! Below is a Python function called `getattr_path` that implements the functionality you described. The function takes an object and a path (represented as a list of attribute names) and attempts to retrieve the value of the specified attribute. If any attribute in the path does not exist, it will return `None... | 24,132 |
```python
def binary_tree_depth(root):
if root is None:
return 0
return max(binary_tree_depth(root.left), binary_tree_depth(root.right)) + 1
```
The function checks whether the root is `None`, which means the tree is empty. If so, it returns 0. Otherwise, it recursively calls itself with the left and r... | Write a Python function to calculate the depth of a binary tree. The function should take the root node of the tree as an argument and traverse the tree using a recursive algorithm. | To calculate the depth (or height) of a binary tree, you can use a recursive function that determines the depth by visiting each node and computing the maximum depth of its left and right subtrees.
Here is a Python implementation of a function to calculate the depth of a binary tree:
```python
class TreeNode:
def... | 24,133 |
```python
from itertools import permutations
def permutations_functional(nums):
return list(permutations(nums))
```
The `permutations_functional` function takes in a list of numbers and returns a list of all possible permutations of the input list using the `permutations` function from the `itertools` module. It ... | Write a Python function that takes a list of numbers and returns a list of all possible permutations of the input list using only functional programming techniques. Implement error handling for invalid inputs.
### Instruction
Write a Python function that takes a list of numbers and returns a list of all possible permu... | To create a Python function that generates all possible permutations of a list of numbers using functional programming techniques, we can utilize `itertools.permutations` while also implementing proper error handling for invalid inputs.
Below is an implementation that meets your requirements:
```python
from itertools... | 24,134 |
Computing the prefix sum of an array involves the following steps:
1. Initialize an empty array to hold the prefix sums.
2. Iterate over the input array from the beginning:
- For each element, add it to the current sum.
- Append the current sum to the prefix sums array.
3. Return the prefix sums array.
Here's... | Write a Python function `prefix_sum(arr)` that takes in a numpy array of any numeric data type and returns the prefix sum of the array. The prefix sum of an array is a new array where each element is the sum of all elements from the beginning to the current index of the original array. | Certainly! You can calculate the prefix sum of a NumPy array using a simple function. The prefix sum at each position `i` in the resulting array is the sum of all previous elements including the current one from the input array.
Here's how you can implement this in Python using the NumPy library:
```python
import num... | 24,135 |
```python
def format_freq_signal(freq_signal):
formatted_freq_signal = [f"{freq:.2f}: {signal}" for freq, signal in freq_signal]
return formatted_freq_signal
```
This implementation uses list comprehension to efficiently create a list of formatted strings. The `f-string` is used to insert the frequency and sig... | Design a Python function that receives a list of tuples containing a frequency and its corresponding signal and prints the formatted strings in the form of `frequency: signal`. The frequency should be rounded to two decimal places and the signal is represented by a bar graph. The function should return a list of string... | You can create the desired function by iterating through the list of tuples, formatting each frequency to two decimal places, and constructing the output string for each tuple. Here's a complete example of how such a function can be implemented:
```python
def format_frequencies(freq_signal):
formatted_output = []
... | 24,136 |
Here is an example of a decorator that applies the original function to the arguments:
```python
def decorator_generator(func):
def decorator(*args):
return func(*args)
return decorator
``` | I want to create a decorator to define a function that generates a decorator. The decorator should only take one argument, a function, and return a function with the same number of arguments as the input function. The decorator should apply the original function to the arguments and return the result. | To create a decorator that generates decorators, you can define a higher-order function that takes a function as an argument and returns a new function that wraps the original function. This wrapper will be able to handle any number of arguments, and it will return the result of calling the original function with those... | 24,137 |
Here is how you can implement the `int_floor_div` function:
```python
def int_floor_div(a, b):
return a // b
```
The `int_floor_div` function simply uses the `//` operator to return the floor of the result of dividing the first argument `a` by the second `b`. | Implement a Python function `int_floor_div` that returns the floor of the result of dividing the first argument by the second. For example, `int_floor_div(11, 3)` should return `3`, and `int_floor_div(-11, 3)` should return `-4`. | To implement the function `int_floor_div` that calculates the floor division of two integers, we can leverage Python's built-in integer division operator `//`, which already performs floor division for integers. However, we should handle the case where the second argument is zero to avoid division by zero errors.
Here... | 24,138 |
To solve this problem, we can use a dictionary to store the counts of each action type. We can iterate over the input list, extract the action type from each string, and increment the corresponding count in the dictionary. After processing all the strings, we can find the most frequent action type by finding the maximu... | Develop a Python function `determine_action_type` that takes a list of string inputs and returns the most frequent action type in the list. The input list contains a sequence of strings that represent actions, where each string is in the form of "action_type:action_details". For example: "shopping:purchased product A".... | To develop the `determine_action_type` function, we can follow these steps:
1. Parse each string in the input list to extract the action type, which is the substring before the colon (`:`).
2. Count the occurrences of each action type using a dictionary.
3. Determine which action type has the highest count.
4. Return ... | 24,139 |
```python
def find_top_k_movies(ratings, top_k):
top_k_movies = []
movie_names = [rating["movie_name"] for rating in ratings]
movie_ratings = [rating["rating"] for rating in ratings]
sorted_movie_ratings = sorted(movie_ratings, reverse=True)
for rating in sorted_movie_ratings[:top_k]:
movie... | Write a Python function `find_top_k_movies(ratings, top_k)` to find the top-k movies in a list of dicts with a key-value pair of "movie_name" and "rating". The function should return a list of the top-k movies in descending order of rating. | Certainly! Below is a Python function named `find_top_k_movies` that accepts a list of dictionaries containing movie names and their corresponding ratings. It returns the top-k movies in descending order of their ratings.
Here's the implementation:
```python
def find_top_k_movies(ratings, top_k):
# Sort the list ... | 24,140 |
To achieve the desired result, you can use list comprehension to construct a new list of lists. Inside the list comprehension, you can use the `split()` method to split the input name into a list of tokens, and then use conditional processing (if-else) to determine which tokens should be included in the abbreviated nam... | Given a list of names, write a Python function to return a list of lists, where each sublist provides a full name and its abbreviated form. The abbreviated form should only contain the first letter of the first name and the last name. For example, given `names = ["", "", ""]`, the function should return `[["", ""], [""... | You can achieve this by defining a function that processes the given list of names and creates the desired output using list comprehension. Below is a Python function that does exactly that:
```python
def abbreviate_names(names):
return [[name, (name.split()[0][0] + '. ' + name.split()[-1]) if name else ''] for na... | 24,141 |
Here's an example implementation of a function that converts a string to a JSON object:
```python
import json
def string_to_json(string):
return json.loads(string)
``` | Write a Python function that converts a string to a JSON object. The string may contain a single JSON object or an array of JSON objects. | To convert a string to a JSON object in Python, you can use the `json` module, which provides a method called `json.loads()` that parses a JSON-formatted string. Here is a Python function that takes a string and tries to convert it to a JSON object, handling both a single JSON object and an array of JSON objects.
```p... | 24,142 |
Here's an example implementation:
```python
def map_interval(interval, f):
start, end = interval
return (f(start), f(end))
def map_intervals(intervals, f):
mapped_intervals = []
for interval in intervals:
mapped_interval = map_interval(interval, f)
mapped_intervals.append(mapped_interv... | Write a Python function `map_intervals` that takes a list of intervals and a function `f` and returns a new list of intervals where each interval's range is mapped to a new range using `f`. For example, an interval `[1, 5]` can be mapped to the range `[f(1), f(5)]`.
The function `f` should be a one-line lambda functio... | Here’s a Python function `map_intervals` that maps each interval using a provided transformation function. In this case, the function `f` is a one-line lambda function that squares the input and adds one.
```python
def map_intervals(intervals, f):
return [(f(start), f(end)) for start, end in intervals]
# Define ... | 24,143 |
Here's how you can implement the `predict_score` function in Python:
```python
def predict_score(features, coefficients):
score = 0
for feature, coefficient in zip(features, coefficients):
score += feature * coefficient
return score
```
This function takes two arguments: `features` and `coefficien... | Develop a Python function named `predict_score` that takes an array of features and returns a single number representing the weighted sum of those features. Each feature may have a different weight, defined as a coefficient in the following formula:
$$
f(x) = a_1 x_1 + a_2 x_2 + ... + a_n x_n
$$
Where $x_1, x_2, ...,... | You can define the `predict_score` function in Python as follows. This function will take two lists: `features` and `coefficients`, and compute the weighted sum according to the formula you provided:
```python
def predict_score(features, coefficients):
# Ensure that both lists are of the same length
if len(fea... | 24,144 |
To write a Python function that takes a single argument `x` and returns its absolute value, there are three cases to consider:
* `x` is an integer: In this case, we simply return the absolute value of `x` using `abs(x)`.
* `x` is a float: In this case, we return the absolute value of `x` using `abs(x)`.
* `x` is a com... | Write a Python function `get_abs_val` that takes a single argument `x` and returns its absolute value. Ensure that `x` is of a valid type (integer, float, or complex) and is not a string. | You can create the `get_abs_val` function as follows:
```python
def get_abs_val(x):
# Validate that x is not a string and is of a valid type (int, float, or complex)
if isinstance(x, str):
raise ValueError("Input should not be a string.")
elif isinstance(x, (int, float, complex)):
return ab... | 24,145 |
Here's how you could implement the `sinc(x)` and `sinc_pi(x)` functions in Python:
```python
import math
def sinc(x: float) -> float:
if x == 0:
return 1.0
return math.sin(x) / x
def sinc_pi(x: float) -> float:
if x == 0:
return 1.0
return math.sin(math.pi * x) / (math.pi * x)
``` | Implement Python functions `sinc(x)` and `sinc_pi(x)` to return the sinc function values at `x` for `sinc(x)` and `sinc(pi*x)` for `sinc_pi(x)`, respectively. Use the formulas:
$$
sinc(x) = \frac{\sin x}{x}
$$
$$
sinc(\pi x) = \frac{\sin(\pi x)}{\pi x}
$$
Your functions should handle zero-division errors gracefully ... | To implement the `sinc` and `sinc_pi` functions in Python, we need to take care of the division by zero case gracefully, as both functions can encounter this situation when their argument is zero. We can use `numpy` to efficiently handle array operations and mathematical functions, which will also ensure numerical stab... | 24,146 |
Here's a Python function that takes in a string, a substring to replace, and a replacement string as arguments, and returns the modified string:
```python
import re
def replace_instances(string, substring, replacement):
return re.sub(re.escape(substring), replacement, string)
```
The `replace_instances` function... | Given a string, write a Python function to replace all instances of a substring with another string. The function should take in three arguments: the original string, the substring to replace, and the replacement string. You should use regular expression patterns to handle complex replacements. | Certainly! You can use the `re` module in Python, which provides support for regular expressions, to replace all instances of a substring with another string. Below is a Python function that accomplishes this by taking in three arguments: the original string, the substring to be replaced, and the replacement string.
H... | 24,147 |
To develop this function, we need to understand how to open a file and read its contents as a stream of text. The `open` function in Python allows you to open a file and return a file object, which can be used to read the file's contents.
Here is a Python function that implements this behavior:
```python
from io impo... | Develop a Python function `stream_text_from_file` that takes a file name and reads the file's content into a string I/O stream. The function should validate the file name to ensure it exists and can be opened for reading.
Write a test function to validate this behavior using an example file. | You can use the `os` module to check if the file exists and the `io` module to create a string I/O stream. Below is the implementation of the `stream_text_from_file` function along with a test function that demonstrates its usage.
```python
import os
import io
def stream_text_from_file(file_name):
"""
Reads t... | 24,148 |
To implement a learning rate scheduler that starts with a constant learning rate and decreases it exponentially every epoch, we can define a function that takes the current epoch as input and returns the decayed learning rate. The decayed learning rate should be computed as the product of the initial learning rate and ... | Implement a learning rate scheduler for a neural network that starts with a constant learning rate and decreases it exponentially every epoch. The learning rate scheduler should be a simple function taking the current epoch as input and returning the decayed learning rate.
Your code should pass the following test case... | You can implement a learning rate scheduler that starts with a constant learning rate and decreases it exponentially each epoch using a simple function. Below is the implementation in Python that fulfills the requirement.
```python
def learning_rate_scheduler(initial_lr, decay_rate, epoch):
"""
Calculate the d... | 24,149 |
Here's an implementation of the `is_http_response_code` function:
```python
import re
def is_http_response_code(response_code: str) -> bool:
if not re.match(r"^[234]\d{2}$", response_code):
return False
return True
```
The `is_http_response_code` function checks if the response_code string matches th... | Write a Python function to determine whether a given string is a valid HTTP response code. The function should take a string argument and return a boolean value indicating whether the string is a valid HTTP response code.
A valid HTTP response code is a string of three digits, starting with "2", "3", or "4". For examp... | You can create a Python function that checks whether a given string is a valid HTTP response code by following these rules. Specifically, it should check if the string consists of exactly three digits and starts with '2', '3', or '4'. Here’s a simple implementation of such a function:
```python
def is_valid_http_respo... | 24,150 |
Here's how we can implement this:
```python
def multiply_complex(a, b):
ar, ai = a
br, bi = b
cr = ar * br - ai * bi
ci = ar * bi + ai * br
return (cr, ci)
```
In this implementation, we use the formula given in the instruction to multiply two complex numbers `a` and `b`. The `ar, ai, br, bi` elem... | Write a Python function to multiply two complex numbers `a` and `b` represented as tuples `a=(ar, ai)` and `b=(br, bi)`, where `ar, ai, br, bi` are real numbers. The function should return the complex number `c=(cr, ci)` as a tuple, where `cr, ci` are the real and imaginary parts of the result, respectively.
Your code... | To multiply two complex numbers represented as tuples, we can implement the multiplication formula for complex numbers. Given two complex numbers \( a = (ar, ai) \) and \( b = (br, bi) \), the result of their multiplication is given by:
\[ c = a \times b = (ar \times br - ai \times bi, ar \times bi + ai \times br) \]
... | 24,151 |
You can create a Python function that iterates through the integer list and checks each value to determine if it is a positive number or not. If it is not a positive number, it is filtered out.
Here's how you could do it:
```python
def filter_positive_numbers(integer_list):
filtered_list = []
for value in in... | Write a Python function to filter a list of integers by removing any values that are not positive numbers.
Assume the input list may contain integers or None values. You can assume all other input values are valid integers or None values. Also, do not use any external libraries.
Your code should pass the following te... | You can create a function called `filter_positive_numbers` which will go through the given list and keep only those integers that are positive, while ignoring `None` values. Here is how you can implement it:
```python
def filter_positive_numbers(integer_list):
return [num for num in integer_list if isinstance(num,... | 24,152 |
Here's how you can implement this:
```python
def fasta_formatter(sequences):
fasta_string = ''
for sequence_id, sequence in sequences:
fasta_string += f'>{sequence_id}\n{sequence}\n'
return fasta_string
``` | Write a Python function that takes a list of sequences as input and returns a string in the FASTA format (https://en.wikipedia.org/wiki/FASTA_format). The first line of each sequence should start with a `>` character followed by the sequence ID, and the second line should contain the sequence. Each sequence should be s... | Certainly! To convert a list of sequences into the FASTA format, you can define a function that iterates over the list and formats each sequence accordingly. Below is a Python function that does exactly that:
```python
def sequences_to_fasta(sequences):
"""
Convert a list of tuples containing sequence ID and t... | 24,153 |
The get_max_min_value function is designed to take in a tuple containing two elements, where the elements can be of any data type. The function then converts the tuple elements to integers if they are not already integers, and returns the maximum and minimum values of the tuple.
Here's a possible implementation of the... | Write a Python function named `get_max_min_value` that returns the maximum and minimum values of a tuple containing two elements. Convert the input tuple elements to integers if they are not already integers.
Example: `get_max_min_value((None, 6))` should return the tuple `(6, None)` because the first and second eleme... | To accomplish the task of creating the `get_max_min_value` function, we need to handle the conversion of tuple elements to integers. If the elements cannot be converted (for instance, if they are not numeric or `None`), we should ensure that they default to `0` during the comparison. Here's how we can implement this:
... | 24,154 |
To solve this problem, we can create a binary search function that returns the last index where target appears in the array.
Here's one way to implement a binary search function that returns the last index where target appears in the array:
```python
def binary_search_last_index(array, target):
left = 0
right... | Develop a Python function `get_last_index(array, target)` that takes a sorted array and a target value, and returns the last index where target appears in the array. If target does not appear in the array, the function should return -1.
For example, given `array = [1, 2, 3, 3, 5, 5, 7]` and `target = 3`, the function ... | You can solve the problem of finding the last index of a target value in a sorted array by utilizing a binary search approach. This allows for efficient searching in O(log n) time complexity. Here's how you can implement the `get_last_index` function in Python:
```python
def get_last_index(array, target):
low, hig... | 24,155 |
```python
import copy
def deep_copy_matching_keys(dictionary, keys):
new_dictionary = copy.deepcopy(dictionary)
for key in list(new_dictionary.keys()):
if key not in keys:
del new_dictionary[key]
return new_dictionary
```
This implementation uses the `copy.deepcopy` function to create ... | Write a Python function that takes a dictionary as input and returns a deep copy that only contains the keys that match the given keys in the dictionary. | To create a function that performs a deep copy of a dictionary while selectively retaining keys that match a given set of keys, you can use the Python standard library's `copy` module along with a simple filtering technique. Here's how you can implement this:
```python
import copy
def selective_deepcopy(original_dict... | 24,156 |
To write a Python function `integer_list_generator(n)` that generates a list of `n` integers using a list comprehension, you need to understand the following:
- List comprehensions are a concise way to create a new list from an iterable, such as a range of numbers in this case.
- The iterable used in a list comprehens... | Write a Python function `integer_list_generator(n)` that generates a list of `n` integers, where `n` is a positive integer. The function should use a list comprehension to generate the list. If `n` is 0, the function should return an empty list. The function should have the following assertion:
```python
assert intege... | You can define the function `integer_list_generator(n)` to generate a list of integers from 1 to `n` using a list comprehension. If `n` is 0, the function will return an empty list. Here is the complete code:
```python
def integer_list_generator(n):
# Ensure n is a positive integer; if n is 0, return an empty list... | 24,157 |
To remove all characters from the input string that are not valid in a URL, we can define a set of valid URL characters and then iterate through the input string and only append the characters that are valid to the output string.
Here's how we can implement this:
```python
def remove_invalid_url_chars(input_string):
... | Write a Python function that accepts a string as an input, and returns a string as an output. The output string should contain only the characters from the input string that are valid in a URL. In other words, it should remove all characters from the input string that are not valid in a URL. | You can create a Python function that filters characters from the input string based on the valid URL character set. The valid characters for a URL generally include:
- Letters (A-Z, a-z)
- Digits (0-9)
- Special characters: `-`, `_`, `.`, `~`
- Other characters such as `:`, `/`, `?`, `#`, `&`, `=` are also valid in s... | 24,158 |
To get information about the calling function and its location, we can use the `__name__` attribute for the function name and the `sys` module's `stack` function to get the frame object of the caller's stack frame. Then, we can use the `getframeinfo()` function from the `traceback` module to retrieve information about ... | Write a Python function `get_caller_location` that gets information about the calling function and its location (filename and line number). The function should return a string containing the caller's name and the filename and line number where it was called.
Use the `__name__` attribute for the function name, and the ... | You can create a function called `get_caller_location` that uses the `inspect` module in Python to retrieve information about the calling function, including its name, filename, and line number. Below is an implementation of the function you are looking for:
```python
import inspect
def get_caller_location():
# G... | 24,159 |
To implement a map function using a function pointer as the mapping function, we can utilize the `map` function in Python's standard library. The `map` function takes a function and an iterable, applies the function to each element in the iterable, and returns an iterator that yields the results.
One challenge with us... | Create a Python function `map_with_func_ptr` that implements a map function using a function pointer as the mapping function. This function should accept a list `values` and a function `func` as arguments, where `func` is the mapping function to apply to each element of `values`. Additionally, `map_with_func_ptr` shoul... | You can create a function `map_with_func_ptr` that takes a list of values and a function pointer as well as an optional identity default argument. The function will apply the mapping function to each element in the list and return a new list with the results. Here's how you can implement this in Python:
```python
def ... | 24,160 |
To implement a stable sorting algorithm in Python, we can use the built-in `sorted` function with the `key` parameter. This parameter accepts a function that takes an element and returns a value to be used for comparison. Thus, we can provide a custom key function that extracts the desired attribute or value from the l... | Implement a Python function that takes a list of elements and returns a new list with the elements sorted by a given key. The key can either be a string or a function that takes an element and returns a value to be used for comparison. The function should use a stable sorting algorithm such as merge sort or tim sort. | You can implement a sorting function in Python that allows sorting a list of elements based on a given key. This function will accept either a string (indicating an attribute of the elements) or a callable (a function to generate a comparison value). The built-in `sorted()` function in Python, which uses Timsort, is st... | 24,161 |
```python
def gen_dict(n):
d = {}
for i in range(1, n + 1):
d[str(i)] = f"{{}}".format(i)
return d
```
This implementation uses the `format()` method to format the numbers with the placeholder `{}`. The dictionary `d` is initialized as an empty dictionary before the loop to store the key-value pair... | Devise a function `gen_dict()` that takes an integer `n` as input and returns a dictionary `d` in the following format:
```python
d = {
"1": "1",
"2": "2",
"3": "3",
...
"n": "n"
}
```
Specifically, the keys are the integers from 1 to n represented as strings, and the values are the keys formatted... | You can create the `gen_dict()` function as described by using a dictionary comprehension. This function will iterate over the range from 1 to `n`, converting each integer to a string for both keys and values. Here's how to implement this:
```python
def gen_dict(n):
return {str(i): str(i) for i in range(1, n + 1)}... | 24,162 |
Here's a sample implementation of the `both_positive` function:
```python
def both_positive(a, b):
return a > 0 and b > 0
```
This function returns `True` if both `a` and `b` are positive, and `False` otherwise. The `and` operator ensures that both conditions must be satisfied to return `True`. | Define a Python function `both_positive` that takes two numbers as inputs and returns `True` if both numbers are positive. Otherwise, return `False`. Leverage the `and` and `or` operators to compose the function.
Your code should pass the following assertions:
```python
assert both_positive(1, -1) == False
assert both... | You can define the function `both_positive` in Python as follows. The function will check if both input numbers are greater than zero using the `and` operator. Here's how you can implement it:
```python
def both_positive(num1, num2):
return num1 > 0 and num2 > 0
# Test assertions
assert both_positive(1, -1) == Fa... | 24,163 |
The `convert_filename` function serves the purpose of converting a path-like object to a filename string. It checks the type of the input using `isinstance` and handles different cases accordingly, including `str`, `bytes`, `os.PathLike`, and `pathlib.Path` objects. It then extracts the filename from the path or raises... | Create a Python function `convert_filename(path_like)` that converts a path-like object into a filename string. Your function should handle compatibility with different types of path objects, such as `str`, `bytes`, `os.PathLike`, and `pathlib.Path`. Use a try-except block to handle the different cases, and raise a `Ty... | Certainly! Below is a Python function `convert_filename` that converts a path-like object into a filename string. The function handles different types of input, including `str`, `bytes`, `os.PathLike`, and `pathlib.Path`. If the input is not recognized, it raises a `TypeError`.
```python
import os
import pathlib
def ... | 24,164 |
Here's a sample implementation of the function:
```python
def get_input(n=None, s=None, f=None):
if n is None:
n = int(input("Enter an integer: "))
if s is None:
s = input("Enter a string: ")
if f is None:
f = float(input("Enter a float: "))
if not isinstance(n, int):
ra... | Write a Python function named `get_input()` that prompts users for i) an integer (n), ii) a string (s), and iii) a float (f). The function should use default arguments when those arguments are not provided by the user. The function should reject invalid input. | Certainly! Below is a Python function named `get_input()` that prompts the user to input an integer, a string, and a float. If the user doesn't provide a valid input, it will continue to prompt until valid input is received. The function also uses default arguments.
```python
def get_input(default_n=0, default_s="defa... | 24,165 |
Here's how you can implement this:
```python
def find_symmetric_difference_of_lists(list1, list2):
if not isinstance(list1, list) or not isinstance(list2, list):
raise ValueError("Both inputs should be lists.")
symmetric_difference = []
for element in list1:
if element not in list2:
... | Implement a Python function `find_symmetric_difference_of_lists` that finds the symmetric difference of two lists. Here is the definition of symmetric difference:
- The symmetric difference of two sets A and B is the set of elements which are in either A or B, but not in their intersection.
- The symmetric difference ... | To implement the `find_symmetric_difference_of_lists` function, we can utilize Python's set operations to efficiently compute the symmetric difference between two lists. We will check if the provided inputs are indeed lists and raise a `ValueError` if they are not. Here's how the implementation can be structured:
```p... | 24,166 |
You can create a Python function that determines the intersection of two lines in the Cartesian plane by checking their slopes and intercepts.
Here's how you could do it:
```python
def line_intersection(line1, line2):
slope1, intercept1 = line1[0], line1[1]
slope2, intercept2 = line2[0], line2[1]
if slop... | Write a Python function to determine the intersection of two lines in the Cartesian plane. The function should return the x- and y-coordinates of the intersection point if they exist, or raise an exception if the lines are parallel or coincide. | To find the intersection of two lines in the Cartesian plane given by the equations in the slope-intercept form \(y = m_1 x + b_1\) and \(y = m_2 x + b_2\), you can use the following approach:
1. **Check for Parallel Lines**: Lines are parallel if their slopes are equal (\(m_1 = m_2\)).
2. **Check for Coinciding Lines... | 24,167 |
Here's an implementation of the `expand_scalar_to_vector` function using Python:
```python
def expand_scalar_to_vector(s, v):
if not isinstance(s, (int, float)):
raise TypeError("s must be a scalar value.")
if not isinstance(v, (list, tuple)):
raise TypeError("v must be a vector.")
if not a... | Implement a Python function `expand_scalar_to_vector` that takes a scalar value `s` and a vector `v`, and returns a new vector `v_out` where each element of `v_out` is equal to the dot product of `s` and the corresponding element in `v`.
For example, given `s = 5` and `v = [3, 4, 5]`, the function should return `v_out... | You can implement the `expand_scalar_to_vector` function by using a simple list comprehension to multiply each element of the input vector `v` by the scalar `s`. Below is the implementation:
```python
def expand_scalar_to_vector(s, v):
"""
Multiplies each element of the vector v by the scalar value s.
Par... | 24,168 |
To design a Python function `read_score` to read a score from a plain text file and output it as a formatted string, you can follow these steps:
1. Open the file in read mode using the `with` statement to ensure it is properly closed after use.
2. Read the first line from the file using the `readline` method.
3. Conve... | Design a Python function `read_score` to read a score from a plain text file and output it as a formatted string. The function takes two arguments: the file path and the score precision (number of decimal places). Given the following input file:
```
9.3
```
The function should output the following:
```
The score is ... | You can create the `read_score` function to read a score from a file, format it to a specified precision, and then output it as a formatted string. Below is the implementation of the function:
```python
def read_score(file_path, precision):
"""
Reads a score from a text file and returns a formatted string.
... | 24,169 |
To validate the input type, you need to compare the actual type of the input with the expected type. You can use the `type()` function to get the type of an object.
Here is the implementation of the `validate_input_type` function:
```python
def validate_input_type(input, expected_type):
if type(input) != expected... | Write a function named `validate_input_type` that takes two parameters: `input` and `expected_type`. The function should validate that the type of `input` is the same as `expected_type`. If the types do not match, the function should raise a `TypeError`.
Your code should pass the following test case:
```python
try:
... | You can create the `validate_input_type` function to check if the type of the `input` matches the `expected_type`. If they don't match, it will raise a `TypeError` with a descriptive error message. Here's how you can implement this function:
```python
def validate_input_type(input, expected_type):
if not isinstanc... | 24,170 |
To solve the problem, we can use the `filter` function from the `itertools` module to filter out objects based on a specific condition. This condition is defined using a lambda function, which checks if all the specified attributes are present in an object.
Here's the implementation of the `filter_objects_with_attribu... | Write a Python function named `filter_objects_with_attributes` that takes a list of objects and a list of attribute names, and returns a list of objects that have all the specified attributes. If any attribute is missing in an object, it should not be included in the returned list. | You can achieve this by defining a function that checks for the presence of all specified attributes in each object. Here's how you can implement the `filter_objects_with_attributes` function in Python:
```python
def filter_objects_with_attributes(objects, attributes):
"""
Filters the list of objects to return... | 24,171 |
To check if a GPU device is available on a machine, we can utilize the `torch.cuda.is_available()` method from the PyTorch library. This method returns True if a CUDA-capable GPU device is available, and False otherwise.
Here is a Python function that checks for the availability of a GPU device:
```python
import torc... | Write a function to check if a GPU device is available on a machine, and return a boolean value to indicate the presence (True) or absence (False) of a GPU.
Your code should pass the following test case:
```python
if check_gpu_availability():
assert torch.cuda.get_device_name() == 'Your GPU Device Name'
assert... | To check for the availability of a GPU device on a machine in Python using the PyTorch library, you can create a function called `check_gpu_availability()`. This function will return `True` if a GPU is available and `False` otherwise.
Here's how you can implement this function:
```python
import torch
def check_gpu_a... | 24,172 |
To create a file from a template, you need to read the contents of the template file and write them to a new file with the specified name. The `create_file_from_template` function takes two arguments: `filename` (string) and `template_name` (string). The `template_name` argument is optional and defaults to a specific t... | Write a Python function `create_file_from_template(filename, template_name)` that creates a file with the specified name based on a given template. The function should take two inputs: `filename` (string) and `template_name` (string). The `template_name` argument is optional and defaults to a specific template if not p... | Here is a Python function that meets your requirements. It creates a file using a specified template file. The function reads the contents of the template file and writes those contents to a new file with the specified name in the same directory as the template.
```python
import os
def create_file_from_template(filen... | 24,173 |
To find the intersection of two rectangles, you first need to find the intersection of their x-coordinates and y-coordinates, separately. If the intersection of both x and y coordinates is not empty, then the two rectangles intersect.
Here is one possible implementation of the function:
```python
def find_intersectio... | Write a Python function that takes two rectangles, each represented by a list of four numbers: `[x1, y1, x2, y2]` where `(x1, y1)` is the top-left coordinate, and `(x2, y2)` is the bottom-right coordinate. The function should return the intersection of the two rectangles as a list of four numbers, or `None` if there is... | Certainly! Below is a Python function that computes the intersection of two rectangles represented by their top-left and bottom-right coordinates. The function checks if there is an intersection and returns the coordinates of the intersection rectangle or `None` if there is no intersection.
```python
def intersect_rec... | 24,174 |
To format a string with an optional header in the specified way, we need to check the length of the string and the existence of the header. We can implement the required logic using an if-else statement, as shown below:
Here's how we can implement this:
```python
def format_header_string(string, header):
if len(s... | Create a Python function to format an arbitrary string with a given header in the following way: if the header exists, add a blank space (' ') before the header. If the string is empty, return an empty string. If the string is not empty, add a colon (`:`) after the header.
Your code should pass the following assertion... | To create the function `format_header_string` as described, we need to handle a few conditions based on the input arguments: the content string and the optional header. Here’s how we can implement the function:
```python
def format_header_string(content: str, header: str) -> str:
if not content:
return ''
... | 24,175 |
```python
def check_if_number_is_odd(number_string):
number = int(number_string)
if number % 2 == 0:
return False
else:
return True
``` | Create a Python function named `check_if_number_is_odd` that accepts a string and determines whether the number represented by the string is odd or not. If the number is odd, return `True`, otherwise return `False`. | You can create a Python function called `check_if_number_is_odd` that takes a string as input, converts it to an integer, and checks if it's odd. Here's how you can implement this function:
```python
def check_if_number_is_odd(number_str):
try:
# Convert the string to an integer
number = int(number... | 24,176 |
To implement this function, we need to handle three different cases:
1. If `obj` is an instance of a class, we can access its attribute `a` using `obj.a`.
2. If `obj` is a dictionary, we can access its value for key `a` using `obj['a']`.
3. If `obj` is a string, we should raise an exception as it is not possible to acc... | Implement a Python function that takes a single argument, `obj`, and returns the value of the attribute `a` of `obj`. If the `obj` object does not have an attribute named `a`, return the default value provided by the keyword argument `default`. If `obj` is a string, the function should raise an exception. | You can implement the function as follows:
```python
def get_attribute_a(obj, default=None):
if isinstance(obj, str):
raise TypeError("Input object cannot be a string")
return getattr(obj, 'a', default)
```
### Explanation:
1. **Type Checking**: The function first checks if `obj` is of type stri... | 24,177 |
To validate the input is a sequence and return the last element of the sequence, we can leverage the built-in `isinstance` function and `collections.abc.Sequence`.
`isinstance` checks if an object is an instance of a given class. In this case, we use it to check if the input is an instance of `collections.abc.Sequence... | Write a Python function to validate the input is a sequence, such as a tuple, list, or string. If the input is a sequence, return the last element of the sequence. If the input is not a sequence, raise a `TypeError`. | You can use the following Python function to validate if the input is a sequence (like a list, tuple, or string) and return the last element if it is. If the input is not a sequence, the function will raise a `TypeError`.
Here's how you can implement this function:
```python
def get_last_element(sequence):
# Chec... | 24,178 |
```python
def format_datetime_iso8601(dt):
"""
Format a datetime object in ISO 8601 format (YYYY-MM-DDTHH:MM:SSZ).
Params:
dt (datetime): The datetime object to be formatted.
Returns:
str: The formatted datetime string in ISO 8601 format.
Raises:
ValueError: If the datetim... | Create a Python function to format a datetime object in ISO 8601 format: YYYY-MM-DDTHH:MM:SSZ. The function should accept a datetime object, and raise a ValueError if it is not provided. Additionally, provide example usages in the docstring. | Certainly! Below is a Python function that formats a `datetime` object in ISO 8601 format (YYYY-MM-DDTHH:MM:SSZ). The function checks if the provided argument is indeed a `datetime` object and raises a `ValueError` if it's not.
```python
from datetime import datetime
def format_datetime_iso8601(dt):
"""
Forma... | 24,179 |
To handle the data stream as an input and return a file descriptor that can be used to read data from the stream, you can:
1. Create a temporary file to store the data from the stream. This can be done by creating a new file using a random name and writing the data from the stream to the file.
2. Return a file descrip... | Write a Python function that takes a data stream as an input and returns a file descriptor that can be used to read data from the stream. The function should use a temporary file to store the data from the stream, and then return a file descriptor that can be used to read from the file. | To create a Python function that takes a data stream and returns a file descriptor for reading from a temporary file, you can use the `tempfile` module to create a temporary file and the `os` module to work with file descriptors. Below is a sample implementation of such a function:
```python
import os
import tempfile
... | 24,180 |
To solve this problem, you can create a function that accepts a string as an argument and returns all possible rotations of that string. The following steps will guide you to a solution that efficiently rotates the string in memory without creating new strings:
1. Initialize an empty list to store the rotated strings.... | Write a Python function that takes a string and returns all possible rotations of the string. For example, given the input string `"abc"`, the function should return a list of strings `["abc", "bca", "cab"]`.
Implement your function such that it efficiently rotates the string in memory rather than creating new strings... | You can create a function in Python to generate all possible rotations of a given string efficiently. Below is an implementation that achieves this by manipulating the indices of the string rather than creating new string objects for each rotation, thus optimizing memory usage.
Here is a Python function that returns a... | 24,181 |
Here is a Python function that implements this approach:
```python
from datetime import datetime
def format_string_to_standard_time(string_time):
"""
Takes a string in the format "HH:mm:ss" and returns a string with the time in standard time format "hh:mm:ss AM/PM".
"""
try:
dt = datetime.strp... | Write a Python function `format_string_to_standard_time` that takes a string in the format "HH:mm:ss" as its argument and returns a string with the time in standard time format "hh:mm:ss AM/PM". | Certainly! Below is a Python function `format_string_to_standard_time` that converts a string in the "HH:mm:ss" format to a standard time format "hh:mm:ss AM/PM".
```python
def format_string_to_standard_time(time_str):
# Split the time string into hours, minutes, and seconds
hours, minutes, seconds = map(int, ... | 24,182 |
Here is a Python program that implements this approach:
```python
import math
def convert_to_radians(degrees, minutes, seconds):
"""
Converts a set of degrees, minutes, and seconds to radians.
"""
return (degrees + minutes / 60 + seconds / 3600) * math.pi / 180
def determine_if_angles_are_equal(angle... | Write a Python program to determine if two angles are equal. The angles are represented by the length of their arcs. You will be given two lists, each containing three integers that represent the arcs of two angles. The three integers in each list represent the lengths of the arcs of the angle in degrees, minutes, and ... | To determine if two angles are equal based on the lengths of their arcs given in degrees, minutes, and seconds, you can follow these steps:
1. Convert each angle into a single unit. A common approach is to convert everything into degrees, where 1 degree = 60 minutes = 3600 seconds.
2. Compare the two angles after conv... | 24,183 |
To check if two chess pieces are equal, you can first check if they have the same color. Then, you can check if they have the same piece type, which can be obtained from the class name or a unique identifier for each piece type. Additionally, you can handle the case where one of the pieces is a pawn that is promoted to... | Write a Python function that checks if two objects are equal in the context of a chess game. The function should take the following arguments:
- `obj1`: An object representing the first chess piece.
- `obj2`: An object representing the second chess piece.
The function should return `True` if the two pieces are equal,... | To implement the function that checks if two chess pieces are equal based on their type and color, including the case of a pawn being promoted, we can define the following logic:
1. Each chess piece can be represented as an object (or class) which contains attributes for its color and type.
2. For equality, we'll chec... | 24,184 |
Here's an example of how you can implement this function:
```python
import string
def format_string_with_args(format_string, arguments):
formatter = string.Formatter()
for key, value in arguments.items():
format_string = format_string.replace("{" + key + "}", str(value))
return formatter.format(fo... | Create a Python function that takes a string and a dictionary of arguments and returns a formatted string. Use the `string` module's `Formatter` class, and iterate over the dictionary to insert the values into the string using the keys as placeholders.
Your code should pass the following assertions:
```python
assert f... | You can achieve this by using the `Formatter` class from the `string` module to format the string with the provided dictionary of arguments. Below is a Python function that accomplishes this:
```python
from string import Formatter
def format_string_with_args(s, args):
formatter = Formatter()
return formatter.... | 24,185 |
Here is a Python function that implements this logic:
```python
from typing import Optional, Tuple
import datetime
resource_access_db = {
(1, 1): datetime.datetime(2023, 1, 1, 10, 0, 0), # user_id=1, resource_id=1, start_time=2023-01-01 10:00:00
(1, 2): datetime.datetime(2023, 1, 1, 12, 0, 0), # user_id=1, r... | Write a Python function named `get_allowed_time_range_for_user` that calculates the time range for which a user is allowed to use a certain resource.
The input arguments are:
- `user_id: int`: the unique ID of a user.
- `resource_id: int`: the unique ID of a resource.
The return value is a tuple of two `datetime` ob... | To implement the `get_allowed_time_range_for_user` function, we will need some context about how we represent the allowed usage for users and resources. Generally, this information might come from a database or a predefined set of rules.
For the sake of this function, let's assume we have a simple dictionary structure... | 24,186 |
The challenge requires us to replace all instances of a floating-point number enclosed in square brackets with a formatted string. The precision of the formatted string should be 2 decimal places and the value should be rounded to the nearest integer. Let's break down the steps:
1. Define a regular expression pattern ... | Write a Python function that replaces all instances of a floating-point number enclosed by square brackets, e.g. `[1.23]`, with a formatted string. The string should have a precision of `2` decimal places, and the value should be rounded to the nearest integer. For example, `[1.23]` would become `[1]` and `[1.56]` woul... | You can achieve the desired functionality by using regular expressions to find the floating-point numbers enclosed in square brackets and then replacing them with the formatted string. Below is a Python function that accomplishes this:
```python
import re
def replace_floating_point_numbers(text):
# Define a funct... | 24,187 |
To write a function that returns a list of all functions and methods of an object, we can utilize Python's built-in `inspect` module. This module provides functions for inspecting objects and their attributes.
Specifically, we can use the `dir` function to get a list of all attributes of an object. We then need to fil... | Write a Python function that takes an object as an input and returns a list of all functions and methods of the object. The function should take into account whether the object is an instance or a class. Additionally, the function should be able to detect whether an object is a function or a method. | You can create a Python function that inspects objects to retrieve all functions and methods associated with them. This function will utilize the `inspect` module to differentiate between functions, methods, and other callable objects. Here's how you can implement it:
```python
import inspect
def list_functions_and_m... | 24,188 |
To delete the kth element from a singly linked list, you can maintain two pointers, `prev` and `curr`, where `prev` points to the element immediately before `curr`. As you iterate through the list, you can keep track of the number of elements traversed. If the number of elements is equal to `k`, you can unlink `curr` f... | Implement a Python function to delete the kth element from a singly linked list. The function should take the head of the list and the position `k` as input parameters. The function should modify the list in-place and return the head of the updated list. The linked list is represented by a `ListNode` class with a `val`... | To implement a function that deletes the kth element from a singly linked list represented by a `ListNode` class, we first need to define the `ListNode` class. Then, we'll implement the function that traverses the list, identifies the kth node, and removes it. Below is the complete code for the `ListNode` class and the... | 24,189 |
To write a Python function that parses a call stack string and returns a list of dictionaries, you can follow these steps:
1. Define a regular expression pattern to match and extract the required information from each stack frame.
2. Use the `re` module to find all matches of the pattern in the input string.
3. For ea... | Write a Python function `parse_call_stack` that takes a string representing a call stack as an argument and returns a list of dictionaries representing each stack frame with keys "function_name", "file_name", and "line_number". Each dictionary should represent a single stack frame and should include the function name, ... | Certainly! Below is a Python function called `parse_call_stack` that takes a string representing a call stack and returns a list of dictionaries, each containing the function name, file name, and line number. The function also includes error handling to manage cases where the input string does not follow the expected f... | 24,190 |
Here is the implementation of the `is_url_valid` function in Python:
```python
import re
def is_url_valid(url):
pattern = re.compile(r"^(http|https)://.*/$")
return pattern.match(url) is not None
```
The `is_url_valid` function uses regular expression to check if the URL starts with `http://` or `https://`, ... | Write a Python function to check that the given URL is valid, and if so, return `True`, otherwise `False`. The URL should end with a `/`, and start with either `http://` or `https://`.
Your code should pass the following assertions:
```python
assert is_url_valid("http://example.com/") is True
assert is_url_valid("http... | You can create a function to check the validity of a URL according to the specified requirements by using basic string operations. Here’s how you can implement the function:
```python
def is_url_valid(url):
# Check if the URL starts with 'http://' or 'https://'
if not (url.startswith("http://") or url.startswi... | 24,191 |
To solve this problem efficiently, we can use a recursive approach. We can write a helper function that takes a list and a flattened list as arguments, and then use recursion to iterate through each element of the given list.
If the element is not a list itself, we can simply append it to the flattened list. If the el... | Write a Python function `flatten_list(lst)` that recursively flattens a list of nested lists, returning a one-dimensional list.
Additionally, make sure the function works for any type of nested lists, including mixed types.
Your code should pass the following assertion:
```python
assert flatten_list([[1, [2, 3]], 4, ... | You can flatten a nested list in Python using a recursive function. Below is the implementation of the `flatten_list` function that can handle any type of nested lists, including mixed types:
```python
def flatten_list(lst):
flattened = [] # Initialize an empty list to hold the flattened elements
for item in ... | 24,192 |
To create such a function, we can use the `format` function to format the parameter values to four decimal places and enclose them in square brackets. We can also use the `join` function to combine the parameter names and values into a single string. Finally, we can use the `strip` function to remove any leading or tra... | Write a Python function `format_cosmo_params` that takes a dictionary of cosmological parameters as input and returns a formatted string with the parameter values and names. The function should format the parameter values to four decimal places and enclose them in square brackets. The parameter names should be formatte... | You can achieve this by defining a function `format_cosmo_params` that processes the input dictionary. Below is the implementation of the function as per your specifications:
```python
def format_cosmo_params(params):
formatted_params = []
for key, value in params.items():
# Replace underscores with hy... | 24,193 |
Here is the implementation:
```python
class WeekDay:
def __init__(self, day):
self.day = day
@classmethod
def is_weekend(cls, day):
return day in ['Saturday', 'Sunday']
```
In this implementation:
- The `__init__` method initializes the `day` attribute of the object.
- The `is_weekend` me... | Write a Python class `WeekDay` that represents a weekday and has a class method `is_weekend` that takes a string representing a weekday (e.g., 'Monday') and returns a boolean indicating whether the day is a weekend day. | Certainly! Below is a Python class named `WeekDay` that includes a class method `is_weekend`. This method checks if the provided weekday string represents a weekend day (Saturday or Sunday).
```python
class WeekDay:
@classmethod
def is_weekend(cls, day: str) -> bool:
# Normalize the input day to lower ... | 24,194 |
Here's the function to remove the first and last characters of a string:
```python
def remove_first_and_last_chars(input_string):
translation_table = str.maketrans('', '', input_string[0] + input_string[-1])
return input_string.translate(translation_table)
```
This function `remove_first_and_last_chars` takes... | Create a Python function that takes a string and returns a new string with the first and last characters removed. Use `string.maketrans` to create the translation table and `string.translate` to perform the actual translation.
Your code should pass the following test case:
```python
input_string = 'hello'
expected_out... | You can create the function `remove_first_and_last_chars` that uses `string.maketrans` and `string.translate`. However, it's important to note that `string.maketrans` and `string.translate` are typically used for character mapping and replacement, not necessarily for removing characters at specific positions.
Neverth... | 24,195 |
Here is an example implementation of the `is_equal_within` function in Python:
```python
def is_equal_within(a: float, b: float, eps: float) -> bool:
if abs(a - b) <= eps:
return True
relative_diff = abs(a - b) / ((a + b) / 2)
if relative_diff <= eps:
return True
return False
``` | Create a Python function named `is_equal_within` that takes three inputs: `a`, `b`, and `eps`. Return True if the relative difference between `a` and `b` is less than or equal to `eps`, or if the absolute difference between `a` and `b` is less than or equal to `eps`.
Your code should pass the following assertions:
```... | You can create the `is_equal_within` function as specified. The function will compute both the relative difference and the absolute difference between `a` and `b`, and check if either of those differences is within the defined tolerance `eps`. Here's how you can implement it:
```python
def is_equal_within(a, b, eps):
... | 24,196 |
To traverse a generic XML tree and find all text values from nodes with the given tag, we can utilize the built-in `xml.etree.ElementTree` module in Python. The `ElementTree.iter()` method provides an iterator that recursively traverses the tree and returns all elements with the given tag. We can iterate over these ele... | Design a Python function `scrape_xml(tree, tag)` that recursively traverses an XML tree and returns all text values from nodes with the given tag. Your function should not assume a specific structure of the XML tree and should be able to handle arbitrary nesting levels and multiple occurrences of the same tag. | To solve the problem of scraping text values from an XML tree based on a specified tag, we can use Python's `xml.etree.ElementTree` module, which provides a way to parse and interact with XML data.
Here is a Python function `scrape_xml(tree, tag)` that will recursively traverse an XML tree and gather all text values f... | 24,197 |
Here is the implementation of the Python function to convert a Unicode string to an encoded byte string, using the "UTF-8" encoding:
```python
def convert_to_utf8_bytes(unicode_string: str) -> bytes:
return unicode_string.encode("UTF-8")
```
The `convert_to_utf8_bytes` function takes a Unicode string as input and... | Define a Python function to convert a Unicode string to an encoded byte string, using the "UTF-8" encoding.
Your code should pass the following assertions:
```python
assert convert_to_utf8_bytes("Hello, world!") == b"Hello, world!"
assert convert_to_utf8_bytes("こんにちは、世界!") == b"\xe3\x81\x93\xe3\x82\x93\xe3\x81\xab\xe3... | To convert a Unicode string to an encoded byte string in Python using the "UTF-8" encoding, you can define a simple function. Below is the implementation of the `convert_to_utf8_bytes` function that satisfies the provided assertions:
```python
def convert_to_utf8_bytes(unicode_string):
# Convert the Unicode string... | 24,198 |
Here is a Python function that takes a list of functions and executes them asynchronously in order:
```python
import asyncio
async def async_execute(functions):
results = []
for func in functions:
result = await func()
results.append(result)
return results
```
This function takes a list o... | Create a Python function that takes a list of functions and executes them asynchronously in order. The function should return a list of results from each function in the same order. The function should be executed asynchronously using the `asyncio` module, which requires the functions to be written as coroutines. To en... | To create a Python function that executes a list of asynchronous functions (coroutines) in order using the `asyncio` module, you can define a coroutine that takes a list of coroutines, executes them in order, and returns the results. Here's how you can do that:
```python
import asyncio
from typing import List, Callabl... | 24,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.