response_seed stringlengths 53 5.17k | instruction_seed stringlengths 29 4.02k | response stringlengths 121 11.9k | __original_row_idx int64 0 50k | conversations listlengths 2 2 |
|---|---|---|---|---|
Here's how we can implement this:
```python
def anagram_check(str1, str2):
counts = {}
for letter in str1:
counts[letter] = counts.get(letter, 0) + 1
for letter in str2:
if letter not in counts or counts[letter] == 0:
return False
else:
counts[letter] -= 1
... | Write a Python function that takes two strings as input and checks if they are anagrams. An anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
The function should return a boolean value indicating whether the two strings a... | You can check if two strings are anagrams by sorting the characters in each string and comparing the sorted results. Here is a Python function that implements this approach:
```python
def are_anagrams(str1, str2):
# Step 1: Sort both strings
sorted_str1 = sorted(str1)
sorted_str2 = sorted(str2)
# ... | 48,100 | [
{
"from": "human",
"value": "Write a Python function that takes two strings as input and checks if they are anagrams. An anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.\n\nThe function should return a boolean... |
To serialize instances of a custom class called `Instance`, you need to check each instance for the existence of an `id` attribute. If it exists, append the `id` to a list of IDs. Otherwise, append the `name` attribute to a list of names. Next, sort these lists and return a dictionary containing the `id` and `name` lis... | Develop a Python function `serialize_instances(instances)` that serializes a list of instances of a custom class called `Instance`. First, check each instance for the existence of an `id` attribute. If it exists, append the `id` to a list of IDs. Otherwise, append the `name` attribute to a list of names. Next, sort the... | Certainly! Below is the implementation of the `serialize_instances` function, which processes a list of instances of a custom class `Instance`, checking for the existence of an `id` attribute and collecting either `id`s or `name`s into respective lists, followed by sorting those lists and returning them in a dictionary... | 48,101 | [
{
"from": "human",
"value": "Develop a Python function `serialize_instances(instances)` that serializes a list of instances of a custom class called `Instance`. First, check each instance for the existence of an `id` attribute. If it exists, append the `id` to a list of IDs. Otherwise, append the `name` att... |
To create a Python function that adds one to each element of a list, you can follow these steps:
1. Define the function `add_one` with the following arguments:
- `numbers`: A list of numbers. This can be either a list of integers or a list of floats.
2. Use the `+` operator to add one to each element of the list. T... | Implement a Python function `add_one` that takes a list of numbers and adds one to each element. The function should support both integer and float types. Use type declaration to enforce the input and output types. Overload the `+` operator for the function to achieve the desired behavior. | To implement the `add_one` function that takes a list of numbers (both integers and floats) and adds one to each element, we can define the function with type annotations. However, Python does not support operator overloading directly for functions. Instead, we can define a class that overloads the `+` operator and use... | 48,102 | [
{
"from": "human",
"value": "Implement a Python function `add_one` that takes a list of numbers and adds one to each element. The function should support both integer and float types. Use type declaration to enforce the input and output types. Overload the `+` operator for the function to achieve the desire... |
Here's a basic implementation of a heuristic function that calculates the distance between two nodes in a graph. It considers the number of edges between the two nodes and the cost of traveling between them:
```python
import math
def heuristic_function(n1, n2):
distance = math.sqrt((n1.x - n2.x)**2 + (n1.y - n2.y... | Implement a heuristic function to estimate the distance between two nodes in a graph. The function should accept two arguments `n1` and `n2` representing two nodes in the graph, and return an integer value representing the estimated distance between them. The heuristic function should take into account the following fa... | To implement a heuristic function for estimating the distance between two nodes in a graph, we can take into account the following parameters:
1. **Actual distance**: This can be derived from the graph structure if we have access to the weights of edges.
2. **Number of edges**: We can count how many edges exist betwee... | 48,103 | [
{
"from": "human",
"value": "Implement a heuristic function to estimate the distance between two nodes in a graph. The function should accept two arguments `n1` and `n2` representing two nodes in the graph, and return an integer value representing the estimated distance between them. The heuristic function ... |
Here's an example implementation of the recursive helper function:
```python
def find_parent_by_name_helper(element, name):
if element['name'] == name:
return element
if element['parent_id'] is not None:
parent = next(e for e in tree if e['id'] == element['parent_id'])
return find_paren... | Write a Python function `find_parent_by_name` that takes a root element of a tree and a string as input. The function should return the first parent node that has the given name, or `None` if no such parent node exists. The tree is a dictionary with all nodes stored in a list, and each node is a separate dictionary wit... | To accomplish the task of finding the first parent of a specified name in a tree structure represented as a list of dictionaries, we can implement the `find_parent_by_name` function with a recursive helper function. The helper function will traverse the tree to find the parent of the given element by checking its `pare... | 48,104 | [
{
"from": "human",
"value": "Write a Python function `find_parent_by_name` that takes a root element of a tree and a string as input. The function should return the first parent node that has the given name, or `None` if no such parent node exists. The tree is a dictionary with all nodes stored in a list, a... |
Here's how you can implement this:
```python
def get_features(dataset, feature_list):
extracted_features = {}
for feature in feature_list:
extracted_features[feature] = dataset[feature]
return extracted_features
```
This implementation iterates over the `feature_list` and extracts the correspondin... | Develop a Python function to extract specific features from an H5 dataset. The function should have the following signature: `get_features(dataset, feature_list)`. The `dataset` argument represents a H5 dataset. The `feature_list` is a list of strings containing the names of features to extract. The function should ret... | To create a Python function that extracts specific features from an HDF5 (H5) dataset, you'll typically use the `h5py` library, which allows for reading and writing HDF5 files easily. Below is the implementation of the `get_features` function as per your requirements:
```python
import h5py
def get_features(dataset, f... | 48,105 | [
{
"from": "human",
"value": "Develop a Python function to extract specific features from an H5 dataset. The function should have the following signature: `get_features(dataset, feature_list)`. The `dataset` argument represents a H5 dataset. The `feature_list` is a list of strings containing the names of fea... |
To create a function `wrapper` similar to `func` with a different argument order, we can use the `functools.wraps` decorator to copy the function signature and docstring of `func` to `wrapper`. We will also define a new wrapper function that accepts `x`, `y`, `z`, `m`, and `foo` as arguments. The wrapper function will ... | I have a Python function `def func(x, y, z, m):` which takes 4 arguments. I want to create a similar function `def wrapper(x, y, z, m, foo=False):` which calls `func` with `m` as the first argument if `foo` is `False`, and passes `x` as the first argument if `foo` is `True`.
Write a Python script to generate `wrapper`... | Certainly! Below is a Python script that defines the `func` function, generates the `wrapper` function according to your specifications, and includes a test function to verify the functionality of `wrapper`.
```python
def func(x, y, z, m):
return f"func called with: x={x}, y={y}, z={z}, m={m}"
def wrapper(x, y, z... | 48,106 | [
{
"from": "human",
"value": "I have a Python function `def func(x, y, z, m):` which takes 4 arguments. I want to create a similar function `def wrapper(x, y, z, m, foo=False):` which calls `func` with `m` as the first argument if `foo` is `False`, and passes `x` as the first argument if `foo` is `True`.\n\n... |
Here's how you could do it:
```python
def normalize_string(string):
words = string.split() # Split the string into a list of words
return ' '.join(words) # Join the words with a single space as the separator
def normalize_list_strings(strings):
normalized_strings = []
for string in strings:
... | You are given a list of strings. Each string contains multiple words, and each word is separated by one or more forms of white space (space, tab, etc.). Write a function that takes a list of strings as input and returns a new list of strings, where each string is normalized to have only a single space between words.
Y... | To normalize the list of strings such that each string has only a single space between words, we can create a function that uses the string methods to split the string into words and then join them back together with a single space.
Here's a Python function to achieve this:
```python
def normalize_list_strings(string... | 48,107 | [
{
"from": "human",
"value": "You are given a list of strings. Each string contains multiple words, and each word is separated by one or more forms of white space (space, tab, etc.). Write a function that takes a list of strings as input and returns a new list of strings, where each string is normalized to h... |
Here's how you can implement this:
```python
def calculate_age(year_of_birth, year_to_calculate, month_of_birth, day_of_birth, month_to_calculate, day_to_calculate):
"""Calculate the age of a person in a specific year, given the year of birth and the year to calculate the age.
Args:
year_of_birth (int... | Define a Python function to calculate the age of a person in a specific year, given the year of birth and the year to calculate the age. The function should adhere to the following formula:
age = (year_to_calculate - year_of_birth) - ((month_to_calculate, day_to_calculate) < (month_of_birth, day_of_birth))
where the ... | Here's a Python function that calculates a person's age in a specific year based on the year of birth and the person's birth date. The function takes into account the month and day to determine if the birthday has occurred yet during the year. The function includes appropriate docstrings for clarity and understanding.
... | 48,108 | [
{
"from": "human",
"value": "Define a Python function to calculate the age of a person in a specific year, given the year of birth and the year to calculate the age. The function should adhere to the following formula:\n\nage = (year_to_calculate - year_of_birth) - ((month_to_calculate, day_to_calculate) < ... |
To replace all occurrences of a specific word with another word in a string while handling cases where the original word is enclosed in single or double quotes, you can follow these steps:
1. Define a regular expression pattern to match the original word enclosed in single or double quotes, including any surrounding w... | Write a Python function to replace all occurrences of a specific word with another word in a string, but make sure to handle cases where the original word is enclosed in single or double quotes.
Assume that the string may contain single or double quotes and that the original word may be enclosed with any of them. Also... | To create a Python function that replaces all occurrences of a specific word while considering various quote scenarios and whitespace, we can use regular expressions. The `re` module in Python allows us to craft a pattern that will match the original word even when it is surrounded by quotes or whitespace.
Here's the ... | 48,109 | [
{
"from": "human",
"value": "Write a Python function to replace all occurrences of a specific word with another word in a string, but make sure to handle cases where the original word is enclosed in single or double quotes.\n\nAssume that the string may contain single or double quotes and that the original ... |
Here's a Python implementation:
```python
def extract_weights(parameters, layer_name):
if layer_name not in parameters:
raise ValueError(f"Layer '{layer_name}' not found in parameters")
weights = parameters[layer_name]['weights']
weights_dict = {}
for i, filter_weights in enumerate(weights):
... | Given a dictionary of parameters loaded from a matconvnet model, extract the weights corresponding to the specified layer and return them as a dictionary. The keys of the dictionary should be the names of the filters and the values should be the weights. | To extract weights from a specific layer of a MatConvNet model, you'll typically have a dictionary structure that contains layers as keys and their corresponding parameters (weights and biases) as values. The exact structure may vary depending on how the model was saved, but the general approach remains similar.
Here’... | 48,110 | [
{
"from": "human",
"value": "Given a dictionary of parameters loaded from a matconvnet model, extract the weights corresponding to the specified layer and return them as a dictionary. The keys of the dictionary should be the names of the filters and the values should be the weights."
},
{
"from": "g... |
To implement the desired behavior of the function, we can use the `reversed()` function from the Python standard library and the `isinstance()` function to check if the argument is an iterable. The `reversed()` function returns a reverse iterator, which can be passed directly to the `list()` function to create a revers... | Write a Python function that takes an iterable and a boolean flag `reverse`, and returns a reversed copy of the iterable if `reverse` is `True`, or the iterable itself if `reverse` is `False`. The function should validate the type of the iterable and raise a `TypeError` if the argument is not iterable. | Certainly! Below is a Python function that implements the specified behavior. The function checks if the provided argument is iterable and then either returns a reversed copy or the original iterable based on the boolean flag `reverse`.
```python
def reverse_iterable(if_iterable, reverse):
# Check if the input is ... | 48,111 | [
{
"from": "human",
"value": "Write a Python function that takes an iterable and a boolean flag `reverse`, and returns a reversed copy of the iterable if `reverse` is `True`, or the iterable itself if `reverse` is `False`. The function should validate the type of the iterable and raise a `TypeError` if the a... |
Here is the implementation:
```python
import math
def sqrt_rounded(number):
if number < 0:
raise Exception('Input must be a positive number.')
square_root = math.sqrt(number)
rounded_root = round(square_root)
return rounded_root
```
In this implementation:
- The `sqrt_rounded` function acce... | Write a Python function that accepts a number and returns its square root, rounded to the nearest integer. If the input is not a positive number, throw an exception. | Certainly! Below is a Python function that takes a number as input, checks if it is a positive number, and returns its square root rounded to the nearest integer. If the input is not a positive number, it raises a `ValueError`.
Here's the implementation:
```python
import math
def square_root_rounded(num):
if num... | 48,112 | [
{
"from": "human",
"value": "Write a Python function that accepts a number and returns its square root, rounded to the nearest integer. If the input is not a positive number, throw an exception."
},
{
"from": "gpt",
"value": "Certainly! Below is a Python function that takes a number as input, ch... |
To encode a string of characters into a list of integers, we can use a dictionary to map each unique character in the input string to an integer value. The integer values can be generated by iterating over the unique characters in the input string and assigning them a value incrementally.
Here's one possible implement... | Design a Python function to encode a string of characters into a list of integers. The function should map each character to an integer value based on its position in a list of unique characters in the input string.
For example, if the input string is "hello" and the unique characters are ['h', 'e', 'l', 'o'], the fun... | To encode a string of characters into a list of integers based on their positions in a list of unique characters, you can follow these steps:
1. Create a list of unique characters from the input string.
2. Create a mapping of each character to its corresponding index in the unique characters list.
3. Use this mapping ... | 48,113 | [
{
"from": "human",
"value": "Design a Python function to encode a string of characters into a list of integers. The function should map each character to an integer value based on its position in a list of unique characters in the input string.\n\nFor example, if the input string is \"hello\" and the unique... |
Here's how you can implement the function:
```python
def validate_message_length(message: str, max_length: int) -> None:
if len(message) > max_length:
raise ValueError(f"Message length exceeds maximum length of {max_length}. Current length: {len(message)}.")
```
The function raises a `ValueError` exceptio... | Write a Python function that takes a string representing a message and an integer representing a maximum length of the message. If the message's length exceeds the maximum length, the function should raise an exception with a specific error message. The error message should include the maximum length and the actual len... | Certainly! Below is a Python function that implements the requested functionality. It checks if the length of the input message exceeds the specified maximum length and raises a `ValueError` if it does, including the maximum and actual lengths in the error message.
```python
def check_message_length(message: str, max_... | 48,114 | [
{
"from": "human",
"value": "Write a Python function that takes a string representing a message and an integer representing a maximum length of the message. If the message's length exceeds the maximum length, the function should raise an exception with a specific error message. The error message should incl... |
Here's how you would add a docstring to the `calculate_averages` function:
```python
def calculate_averages(student_ages):
"""
Calculates the average age of all students.
Args:
student_ages (list[tuple[str, int]]): A list of tuples where each tuple represents a student's name and age.
Returns... | Add a docstring to the `calculate_averages` function, which takes in a list of tuples where each tuple represents a student's name and age, and returns a dictionary where the keys are the names and the values are the average age of all students. The name format should be "Name (Age)".
Here's an example of using this f... | Certainly! Here’s a Python function `calculate_averages` with an appropriate docstring that outlines its purpose, parameters, and return value:
```python
def calculate_averages(students):
"""
Calculate the average age of students and return a dictionary.
This function takes a list of tuples where each tup... | 48,115 | [
{
"from": "human",
"value": "Add a docstring to the `calculate_averages` function, which takes in a list of tuples where each tuple represents a student's name and age, and returns a dictionary where the keys are the names and the values are the average age of all students. The name format should be \"Name ... |
Here is the implementation of the function:
```python
import platform
import sys
def format_platform_string():
platform_name = sys.platform
python_version = '.'.join(map(str, sys.version_info[:3]))
if platform_name == 'linux':
distribution, version, _ = platform.linux_distribution()
platfo... | Write a Python function to format a string containing the current platform's name and Python version, based on the `sys.platform` and `sys.version_info` attributes. If the platform name is `linux`, include the system's distribution name in the string as well. | To create a Python function that formats a string containing the current platform's name and Python version, we'll use the `sys` module to access `sys.platform` and `sys.version_info`. Additionally, for Linux distributions, we can use the `platform` module to retrieve the distribution name.
Here’s a function that does... | 48,116 | [
{
"from": "human",
"value": "Write a Python function to format a string containing the current platform's name and Python version, based on the `sys.platform` and `sys.version_info` attributes. If the platform name is `linux`, include the system's distribution name in the string as well."
},
{
"from... |
To find the lowest common ancestor (LCA) of two nodes in a binary tree, we can use the parent pointers. The problem can be solved in two steps:
1. Find the depth of each node, measured as the number of edges between the node and the root.
2. Traverse upward from the deeper node until we reach a node that is at the same... | In a binary tree, each node has a parent pointer that points to its parent node. Write a Python function to find the lowest common ancestor of two nodes in such a tree. The function should return the parent node of the lowest common ancestor. | To find the lowest common ancestor (LCA) of two nodes in a binary tree where each node has a pointer to its parent, we can approach the problem by following the parent pointers from both nodes to the root of the tree, tracking the path taken by each node. Once we have the paths for both nodes, we can find the last comm... | 48,117 | [
{
"from": "human",
"value": "In a binary tree, each node has a parent pointer that points to its parent node. Write a Python function to find the lowest common ancestor of two nodes in such a tree. The function should return the parent node of the lowest common ancestor."
},
{
"from": "gpt",
"va... |
Here's how you could implement the `get_sex_chromosomes` function in Python:
```python
def get_sex_chromosomes(num_chromosomes, include_sex_chromosomes):
num_sex_chromosomes = num_chromosomes // 2
chromosomes = [f'chr{i}' for i in range(1, num_chromosomes + 1)]
if include_sex_chromosomes:
chromosom... | Develop a Python function `get_sex_chromosomes` that returns a list of chromosome names for a given number of chromosomes and a boolean to indicate whether the sex chromosomes should be included. The chromosome names should follow the convention of the format `chrX` for the X chromosome, `chrY` for the Y chromosome, an... | To achieve the given requirements, we can create a Python function `get_sex_chromosomes`. This function will take two parameters: `num_chromosomes` (the total number of chromosomes) and `include_sex_chromosomes` (a boolean indicating whether to include sex chromosomes). Based on the specifications, the function will re... | 48,118 | [
{
"from": "human",
"value": "Develop a Python function `get_sex_chromosomes` that returns a list of chromosome names for a given number of chromosomes and a boolean to indicate whether the sex chromosomes should be included. The chromosome names should follow the convention of the format `chrX` for the X ch... |
To write a Python function that removes any consecutive whitespace characters in a given string, you can follow these steps:
1. Define a function that takes a string as input and returns a new string with any consecutive whitespace characters replaced with a single space character.
2. Use the `re` module to replace co... | Write a Python function `remove_multiple_whitespace(s)` that takes a string `s` as input, and returns a new string with any consecutive whitespace characters in `s` replaced with a single space character.
Example:
```python
assert remove_multiple_whitespace("hello world") == "hello world"
assert remove_multiple_whit... | Certainly! You can achieve the functionality of replacing multiple consecutive whitespace characters with a single space character using the `re` module in Python, which provides support for regular expressions.
Here is a function `remove_multiple_whitespace(s)` that does exactly that:
```python
import re
def remove... | 48,119 | [
{
"from": "human",
"value": "Write a Python function `remove_multiple_whitespace(s)` that takes a string `s` as input, and returns a new string with any consecutive whitespace characters in `s` replaced with a single space character.\n\nExample:\n\n```python\nassert remove_multiple_whitespace(\"hello world... |
To create such a function, we can use a loop to iterate through the given list of date objects and append each date to a string, separated by a comma and space. We can use the `strftime` method of the `datetime` library to format each date as a string in the specified format.
```python
def format_date_list(date_list):... | Write an efficient Python function to format a list of date objects (e.g. `01-01-2000`, `02-01-2000`, ..., `31-12-2000`) into a single string that represents all dates in the format `01-01-2000, 01-02-2000, ..., 31-12-2000` (no spaces, no double quotes). | To format a list of date objects into a single string in the desired format, you can use the `strftime` method to convert each date object to a string and then join them together. Here’s a concise and efficient Python function to achieve this:
```python
from datetime import datetime, timedelta
def format_dates(date_l... | 48,120 | [
{
"from": "human",
"value": "Write an efficient Python function to format a list of date objects (e.g. `01-01-2000`, `02-01-2000`, ..., `31-12-2000`) into a single string that represents all dates in the format `01-01-2000, 01-02-2000, ..., 31-12-2000` (no spaces, no double quotes)."
},
{
"from": "g... |
```python
import torch
def reshape_x(x, y):
x_reshaped = x.view(x.shape[0], x.shape[1], 1)
return x_reshaped
``` | Write a Python function that takes a Pytorch tensor `x` with shape `(batch_size, input_dim)` and a target `y` with shape `(batch_size,)` and performs dimension reshaping to return a new tensor with shape `(batch_size, input_dim, 1)`. The function should also preserve the semantics of the original tensor `x` and `y`. | You can achieve the desired reshaping of a PyTorch tensor while preserving its semantics. Here’s a simple function that takes a tensor `x` with shape `(batch_size, input_dim)` and a target tensor `y` with shape `(batch_size,)`, and then reshapes `x` to the shape `(batch_size, input_dim, 1)`.
Here’s how you can impleme... | 48,121 | [
{
"from": "human",
"value": "Write a Python function that takes a Pytorch tensor `x` with shape `(batch_size, input_dim)` and a target `y` with shape `(batch_size,)` and performs dimension reshaping to return a new tensor with shape `(batch_size, input_dim, 1)`. The function should also preserve the semanti... |
To combine a string with an object, we can use the built-in formatting methods in Python. We can first extract the object's keys and values, and then use the string formatting syntax to construct the desired output string.
Here is a Python function that implements this approach:
```python
def combine_string_and_objec... | Write a Python function that takes two arguments: a string and an object, and returns a string that combines the two. The result should be formatted as follows: `[string]: [object.key1], [object.key2], ...`. For example, given the string `"Hello"` and the object `{"key1": "value1", "key2": "value2"}`, the function shou... | You can create a function that takes a string and an object (in Python, you can use a dictionary to represent the object) and formats the output as specified. Here’s how you can implement such a function:
```python
def format_string_with_object(input_string, obj):
# Extract values from the object
values = obj.... | 48,122 | [
{
"from": "human",
"value": "Write a Python function that takes two arguments: a string and an object, and returns a string that combines the two. The result should be formatted as follows: `[string]: [object.key1], [object.key2], ...`. For example, given the string `\"Hello\"` and the object `{\"key1\": \"... |
Here's an example of how you can implement this function:
```python
import doctest
import inspect
def create_module_interface(file_path):
"""
Generate a module interface file for the given Python file.
Parameters:
file_path (str): Path to the Python file.
Returns:
module_interface (str): Mod... | Write a Python function that takes a Python file path as input and generates a module interface file. The module interface file should contain a list of all the functions, classes, and other objects defined in the module. For each object, include the full name, type, and docstring.
Write a test function to validate th... | To achieve the functionality of generating a module interface file that lists all functions, classes, and other objects along with their types and docstrings, we can utilize the `ast` module. The following code provides the implementation for the required functionality along with a corresponding test function using the... | 48,123 | [
{
"from": "human",
"value": "Write a Python function that takes a Python file path as input and generates a module interface file. The module interface file should contain a list of all the functions, classes, and other objects defined in the module. For each object, include the full name, type, and docstri... |
Here is the Python implementation of the above approach:
```python
def greet(name, capitalized, first_time):
greeted = {}
def is_greeted(name):
return name in greeted and greeted[name]
def format_greeting(name):
return f'Hello, {name}' if first_time else f'Hello, {name}, nice to see you ag... | Write Python code to format a string "Hello, {name}" with different styles based on whether it's the first time the user has greeted them, and whether the string should be capitalized. For example:
```
"Hello, Rachel" => "Hello, Rachel"
"Hello, rachel" => "Hello, rachel"
"Hello, Rachel" => "Hello, Rachel, nice to see y... | You can achieve this by creating a function that takes the name, whether it's the first greeting, and whether the string should be capitalized as parameters. Here's an example of how to implement this in Python:
```python
def format_greeting(name, first_time=True, capitalize=False):
# Create the base greeting
... | 48,124 | [
{
"from": "human",
"value": "Write Python code to format a string \"Hello, {name}\" with different styles based on whether it's the first time the user has greeted them, and whether the string should be capitalized. For example:\n```\n\"Hello, Rachel\" => \"Hello, Rachel\"\n\"Hello, rachel\" => \"Hello, rac... |
Here's how you could implement the `masked_loss` function:
```python
import numpy as np
def masked_loss(prediction: np.ndarray, target: np.ndarray, mask: np.ndarray) -> float:
differences = np.square(prediction - target)
masked_losses = np.where(mask, differences, np.zeros_like(differences))
sum_masked_lo... | Write a Python function `masked_loss` that computes the loss between `prediction` and `target` with `mask` applied. The `mask` is a list of booleans where `True` indicates that the corresponding loss should be included in the total loss. Make sure to ignore the masked losses by not summing them in the calculation. The ... | You can create the `masked_loss` function by using NumPy for efficient computation of the predictions and targets along with the mask. Here's how you can implement it:
```python
import numpy as np
def masked_loss(prediction, target, mask):
"""
Computes the masked loss between prediction and target.
Param... | 48,125 | [
{
"from": "human",
"value": "Write a Python function `masked_loss` that computes the loss between `prediction` and `target` with `mask` applied. The `mask` is a list of booleans where `True` indicates that the corresponding loss should be included in the total loss. Make sure to ignore the masked losses by ... |
Here's how you can implement the `dynamic_cast` function:
```python
def dynamic_cast(obj, target_type):
if isinstance(target_type, int):
return obj.__cast__(target_type)
elif hasattr(obj, '__cast__'):
return obj.__cast__(target_type)
else:
raise TypeError("Type casting not supported... | Write a Python function `dynamic_cast(obj, target_type)` that performs dynamic type casting for a Python object `obj` to a specified type `target_type`. The function should be able to handle any type of object, including custom classes and built-in types.
Assume that the `target_type` class has a type conversion metho... | To implement the `dynamic_cast` function as described, we can utilize Python's built-in features, such as the `hasattr` function to check for the existence of the `__cast__` method on the object, as well as type checking for built-in types. Below is the implementation of the `dynamic_cast` function:
```python
def dyna... | 48,126 | [
{
"from": "human",
"value": "Write a Python function `dynamic_cast(obj, target_type)` that performs dynamic type casting for a Python object `obj` to a specified type `target_type`. The function should be able to handle any type of object, including custom classes and built-in types.\n\nAssume that the `tar... |
Here's how you can implement this function in Python:
```python
def rotate_2d_list_180(lst):
return [list(reversed(sublist)) for sublist in reversed(lst)]
```
The `rotate_2d_list_180` function takes a 2D list as input and returns a new list that has been rotated by 180 degrees clockwise. It reverses the order of ... | Given a 2D list, rotate the list by 180 degrees clockwise.
Your code should pass the following assertions:
```python
assert rotate_2d_list_180([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) == [[9, 8, 7], [6, 5, 4], [3, 2, 1]]
assert rotate_2d_list_180([[1, 2], [3, 4]]) == [[4, 3], [2, 1]]
assert rotate_2d_list_180([[]]) == [[]]
... | To rotate a 2D list (matrix) by 180 degrees clockwise, you can follow these steps:
1. Reverse the order of the rows in the list.
2. Reverse the order of the elements within each row.
Here's the Python function to accomplish this:
```python
def rotate_2d_list_180(matrix):
# Step 1: Reverse the order of the rows
... | 48,127 | [
{
"from": "human",
"value": "Given a 2D list, rotate the list by 180 degrees clockwise.\n\nYour code should pass the following assertions:\n```python\nassert rotate_2d_list_180([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) == [[9, 8, 7], [6, 5, 4], [3, 2, 1]]\nassert rotate_2d_list_180([[1, 2], [3, 4]]) == [[4, 3], [2... |
To create a function that converts a hex color string to its RGB equivalent, we must validate the input string to ensure it follows the correct pattern and then extract the individual hexadecimal values for each color channel.
```python
import re
class InvalidHexColorError(Exception):
"""Exception raised when an ... | Create a Python function named `hex_to_rgb` to convert a hex color string to its RGB equivalent. The function should take a string of length 7, beginning with a hash character and followed by six hexadecimal digits. The function should validate the input string and return a 3-tuple of integers, each representing one of... | Here is an implementation of the `hex_to_rgb` function, complete with the necessary exception class and validation code as you described:
```python
import re
class InvalidHexColorError(Exception):
"""Exception raised when an invalid hex color string is provided."""
pass
def hex_to_rgb(hex_color):
"""Conv... | 48,128 | [
{
"from": "human",
"value": "Create a Python function named `hex_to_rgb` to convert a hex color string to its RGB equivalent. The function should take a string of length 7, beginning with a hash character and followed by six hexadecimal digits. The function should validate the input string and return a 3-tu... |
To compare two strings and return `True` if they are the same, but with their positions reversed, you can do the following:
1. Check if the lengths of the two strings are equal. If not, return `False` immediately, as the strings cannot be reversed if they are of different lengths.
2. Reverse the first string using `re... | Write a Python function to compare two strings and return `True` if they are the same, but with their positions reversed. For example, `is_reversed('abcd', 'bcda')` should return `True`, while `is_reversed('ab', 'abc')` should return `False`.
**Hint**: You can use the `==` operator to compare strings directly, and the... | You can create a function `is_reversed` to check if two strings are equal when one of them is reversed. Here's how you can implement this:
```python
def is_reversed(s1, s2):
# First, check if the lengths of the strings are the same
if len(s1) != len(s2):
return False
# Then, compare the first strin... | 48,129 | [
{
"from": "human",
"value": "Write a Python function to compare two strings and return `True` if they are the same, but with their positions reversed. For example, `is_reversed('abcd', 'bcda')` should return `True`, while `is_reversed('ab', 'abc')` should return `False`.\n\n**Hint**: You can use the `==` op... |
In order to convert a given string from camel-case to snake-case, we need to use regular expressions to find the upper case characters and insert underscores before them. The `re.sub` function allows us to use a regular expression to search for characters and then replace them with a string. However, the replacement st... | Write a Python function `camel_to_snake(word)` that takes a string and converts it from camel case to snake case. The function should make use of `re.sub`, and it should combine the result of calling `re.sub` with a lambda function, which takes a match object and returns a string with the first group (matched character... | You can convert a string from camel case to snake case in Python using the `re` module, specifically with the `re.sub` function. Below is a function `camel_to_snake` that implements this behavior. It uses a regular expression to identify uppercase letters and replaces them with an underscore followed by the lowercase v... | 48,130 | [
{
"from": "human",
"value": "Write a Python function `camel_to_snake(word)` that takes a string and converts it from camel case to snake case. The function should make use of `re.sub`, and it should combine the result of calling `re.sub` with a lambda function, which takes a match object and returns a strin... |
Here is the code:
```python
import numpy as np
def get_closest_vector_index(X):
normalized_X = [x / np.linalg.norm(x) for x in X]
average_vector = np.average(normalized_X, axis=0)
cosine_similarities = [np.dot(x, average_vector) / (np.linalg.norm(x) * np.linalg.norm(average_vector))
... | I have a list of vectors `X` (each vector is a list of floating point numbers), and I want to find the vector that is closest to the average vector in terms of cosine similarity. To do so, I will first need to normalize all vectors in `X`, and then compute the cosine similarity between each vector and the average vecto... | To solve the problem, we need to follow these steps:
1. Normalize each vector in the list `X`.
2. Compute the average vector from the normalized vectors.
3. Calculate the cosine similarity between each normalized vector and the average vector.
4. Identify the index of the vector with the highest cosine similarity to t... | 48,131 | [
{
"from": "human",
"value": "I have a list of vectors `X` (each vector is a list of floating point numbers), and I want to find the vector that is closest to the average vector in terms of cosine similarity. To do so, I will first need to normalize all vectors in `X`, and then compute the cosine similarity ... |
To accomplish this, we'll use the `groupby` method to group the dataframe by the values in the `cluster` column. Then, we'll iterate through the groups, and for each group, we'll create a list of tuples where each tuple contains the corresponding values from the `x`, `y`, and `z` columns. We'll add these tuples to the ... | Given a Pandas dataframe `df`, create a dictionary `cluster_dict` where the keys are the values in the `cluster` column and the values are lists of tuples containing `x`, `y`, and `z` values from the `x`, `y`, and `z` columns.
For example, if the dataframe contains these rows:
| cluster | x | y | z |
|------|---|---|... | To create the desired `cluster_dict` from a Pandas DataFrame `df`, you can use the following approach:
1. Use the `groupby()` function on the `cluster` column to group the rows by the cluster values.
2. For each group, extract the `x`, `y`, and `z` values and store them in a list of tuples.
3. Convert this data into a... | 48,132 | [
{
"from": "human",
"value": "Given a Pandas dataframe `df`, create a dictionary `cluster_dict` where the keys are the values in the `cluster` column and the values are lists of tuples containing `x`, `y`, and `z` values from the `x`, `y`, and `z` columns.\n\nFor example, if the dataframe contains these rows... |
To solve a system of linear equations `matrix * x = vector` using `numpy.ndarray` objects, we can use the `np.linalg.solve` function from Numpy's Linear Algebra module. This function takes two arguments, the coefficient matrix `matrix` and the dependent variable vector `vector`, and returns the solution vector `x` as a... | Write a Python function `matrix_equation_solver(matrix, vector)` to solve a system of linear equations `matrix * x = vector`. The matrix and vector are both `numpy.ndarray` objects. The function should return a numpy.ndarray object that represents the solution vector x. If the matrix is not square or the matrix has no ... | To solve a system of linear equations represented by the equation `matrix * x = vector`, we can use NumPy's linear algebra functionalities. Specifically, we can use the function `numpy.linalg.solve()` which is designed to solve linear equations.
Here's how to implement the function `matrix_equation_solver(matrix, vect... | 48,133 | [
{
"from": "human",
"value": "Write a Python function `matrix_equation_solver(matrix, vector)` to solve a system of linear equations `matrix * x = vector`. The matrix and vector are both `numpy.ndarray` objects. The function should return a numpy.ndarray object that represents the solution vector x. If the m... |
```python
import torch
def compute_quantile_prediction(predictions):
quantile_predictions = []
for event in predictions:
x_coords = event[:, 0] # Extract the x-coordinates of the particles
quantile_predictions.append(torch.quantile(x_coords, 0.5)) # Compute the 50th percentile
return torc... | Write a Python function that takes a PyTorch tensor of shape `(N, M, 3)` representing the particle predictions for each event in a dataset. Each particle prediction consists of a 3D vector representing its position in the (x, y, z) coordinate system. The function should return the quantile prediction of each particle's... | Certainly! To compute the quantile prediction of each particle's position in the x-axis over all events, we can leverage PyTorch's built-in functions. Specifically, we can use `torch.quantile` to compute the 50th percentile (which corresponds to the median) along the appropriate dimension.
Here is the implementation o... | 48,134 | [
{
"from": "human",
"value": "Write a Python function that takes a PyTorch tensor of shape `(N, M, 3)` representing the particle predictions for each event in a dataset. Each particle prediction consists of a 3D vector representing its position in the (x, y, z) coordinate system. The function should return t... |
Here's an example implementation of the function:
```python
import re
def display_valid_dates(date_list):
valid_dates = []
for date_string in date_list:
if not re.match(r'\d{4}-\d{2}-\d{2}', date_string):
raise ValueError('Invalid date format')
else:
valid_dates.append(... | Create a Python function to display a list of valid dates in a specific format. The function should accept a list of strings and return a formatted string representing the list of dates.
The expected input format for each date string is "YYYY-MM-DD", where YYYY represents the year, MM represents the month, and DD repr... | Here is a Python function that meets your requirements. This function checks the format of each date string in the input list, validates it, and returns a formatted string of valid dates:
```python
import re
from datetime import datetime
def format_dates(date_list):
# Define the regex pattern for the date format ... | 48,135 | [
{
"from": "human",
"value": "Create a Python function to display a list of valid dates in a specific format. The function should accept a list of strings and return a formatted string representing the list of dates.\n\nThe expected input format for each date string is \"YYYY-MM-DD\", where YYYY represents t... |
To create a string pattern in the form of a right triangle with the given base length, height, and character, you can follow these steps:
1. Initialize an empty string pattern.
2. Iterate through the height of the triangle: For each row, build a string with the specified character that is equal to the current row numb... | Write a Python function to create a string pattern in the form of a right triangle, with the given base length, height, and character. The function should return a string pattern with the specified base length, height, and character. The character should be repeated rather than concatenated for each row.
For example, ... | You can achieve this by using a simple for loop that constructs the right triangle pattern line by line. Below is a Python function that implements this logic:
```python
def create_right_triangle_pattern(base_length, height, character):
if base_length < 1 or height < 1:
return "" # Return an empty string ... | 48,136 | [
{
"from": "human",
"value": "Write a Python function to create a string pattern in the form of a right triangle, with the given base length, height, and character. The function should return a string pattern with the specified base length, height, and character. The character should be repeated rather than ... |
Here's how you can do it in Python:
```python
def sort_dict_descending(dictionary):
return sorted(dictionary.items(), key=lambda x: x[1], reverse=True)
``` | Write a Python function that takes a dictionary as input and returns a list of tuples, sorted based on the values of the dictionary in descending order. The tuples should contain the keys and values of the dictionary.
Your code should pass the following assertions:
```python
assert sort_dict_descending({'x': 4, 'y': 5... | You can achieve the desired functionality by using the `sorted()` function along with a lambda function to sort the items of the dictionary based on their values. The `reverse=True` parameter ensures that the sorting is done in descending order. Here's how you can implement the `sort_dict_descending` function:
```pyth... | 48,137 | [
{
"from": "human",
"value": "Write a Python function that takes a dictionary as input and returns a list of tuples, sorted based on the values of the dictionary in descending order. The tuples should contain the keys and values of the dictionary.\n\nYour code should pass the following assertions:\n```python... |
You can create a Python function that takes a dictionary of arbitrary function arguments and returns a new dictionary of argument values that are lists. For the elements that are not functions, return a list with a single value. For the elements that are functions, call them with all possible provided argument values a... | Create a Python function that takes a dictionary of arbitrary function arguments, and returns a new dictionary of argument values that are lists. For the elements of the original dictionary that are not functions, return a list with a single value. For the elements that are functions, call them with all possible provid... | To create a Python function that processes a dictionary of arbitrary function arguments and returns the desired output as specified, we can follow these steps:
1. Iterate over each key-value pair in the input dictionary.
2. Check if the value is a callable (function) or not.
3. For non-callable values, wrap them in a ... | 48,138 | [
{
"from": "human",
"value": "Create a Python function that takes a dictionary of arbitrary function arguments, and returns a new dictionary of argument values that are lists. For the elements of the original dictionary that are not functions, return a list with a single value. For the elements that are func... |
The function can be implemented as follows:
```python
def remove_last_element(input_container):
if not isinstance(input_container, (list, tuple, dict)):
raise TypeError("Input must be a list, tuple, or dict.")
elif len(input_container) == 0:
raise ValueError("Input cannot be empty.")
if is... | Implement a Python function that takes a list, tuple, or dict as input and returns a new list, tuple, or dict, respectively, with the last element removed. The function should handle the case when the input is empty. | Certainly! Below is a Python function that takes a list, tuple, or dictionary as input and returns a new list, tuple, or dictionary with the last element removed. It also handles the case when the input is empty.
```python
def remove_last_element(data):
if isinstance(data, list):
# Remove last element from... | 48,139 | [
{
"from": "human",
"value": "Implement a Python function that takes a list, tuple, or dict as input and returns a new list, tuple, or dict, respectively, with the last element removed. The function should handle the case when the input is empty."
},
{
"from": "gpt",
"value": "Certainly! Below is... |
To write a Python function `parse_custom_data` that parses a string with a custom data type and returns a Python object, you'll need to:
1. Define the different types that can be represented in the custom data type. These could be `int`, `float`, `str`, or `bool`.
2. Understand the format of the input string. In this ... | Write a Python function named `parse_custom_data` that parses a string with a custom data type and returns a Python object. The custom data type consists of a string of the format `"<type> <value>"` where type is one of "int", "float", "str", or "bool", and value is the corresponding value for that type.
For example, ... | Certainly! Below is a Python function named `parse_custom_data` that implements the requested features. It can parse strings of custom data types, support multiple values, and handle nested data types in a structured way.
```python
import json
def parse_custom_data(data_str):
# Remove any leading or trailing whit... | 48,140 | [
{
"from": "human",
"value": "Write a Python function named `parse_custom_data` that parses a string with a custom data type and returns a Python object. The custom data type consists of a string of the format `\"<type> <value>\"` where type is one of \"int\", \"float\", \"str\", or \"bool\", and value is th... |
We need to write a Python function that takes an input image represented by a list of lists of pixel values and a flag that determines whether the image should be reordered using a zigzag pattern.
Here's how we can do it:
```python
def reorder_pixels(image, zigzag):
flattened_image = [pixel for row in image for p... | Write a Python function `reorder_pixels` that takes an input image, represented by a list of lists of pixel values (each pixel is a tuple of red, green, and blue values), and a flag `zigzag` that determines whether the image should be reordered using a zigzag pattern. If the flag is set to `True`, the function should r... | You can implement the `reorder_pixels` function to reorder the pixels of an image in a zigzag pattern. Below is the function that takes an image and a flag `zigzag`. If the `zigzag` flag is set to `True`, the pixels are reordered in a zigzag manner; otherwise, the original image is returned.
Here's the implementation:... | 48,141 | [
{
"from": "human",
"value": "Write a Python function `reorder_pixels` that takes an input image, represented by a list of lists of pixel values (each pixel is a tuple of red, green, and blue values), and a flag `zigzag` that determines whether the image should be reordered using a zigzag pattern. If the fla... |
To write a Python function that takes an input of seconds and returns a formatted string representing the input interval, you can follow these steps:
1. Determine the number of days, hours, minutes, and seconds in the input interval. For example, if the input is 3600 seconds, the number of hours is 1.
2. Convert each ... | Write a Python function `format_time_interval(seconds)` that takes an input of seconds and returns a formatted string representing the input interval. The format should be "X days, Y hours, Z minutes, and N seconds".
Your code should pass the following assertion:
```python
assert format_time_interval(60) == "1 minute"... | Certainly! Below is a Python function `format_time_interval` that takes an input of seconds and returns a formatted string representing that interval in days, hours, minutes, and seconds. It also handles the specified format for singular and plural forms correctly.
Here's the implementation:
```python
def format_time... | 48,142 | [
{
"from": "human",
"value": "Write a Python function `format_time_interval(seconds)` that takes an input of seconds and returns a formatted string representing the input interval. The format should be \"X days, Y hours, Z minutes, and N seconds\".\n\nYour code should pass the following assertion:\n```python... |
To design a function that calculates the number of days in a given month, we need to consider the leap year rule. The leap year rule states that a year is a leap year if it is divisible by 4 but not divisible by 100, or if it is divisible by 400.
Here is an implementation of the `get_days_in_month` function in Python:... | Design a Python function `get_days_in_month(year, month)` to return the number of days in a given month of a calendar year. Your function should validate the input `year` and `month` and handle leap years correctly. If the input is invalid, it should raise an appropriate exception. | To design the function `get_days_in_month(year, month)`, we need to handle the validation of inputs and correctly determine the number of days in each month, including the handling of leap years for February.
Here's how to implement this:
1. Validate the input for `year` to be an integer and typically within a reaso... | 48,143 | [
{
"from": "human",
"value": "Design a Python function `get_days_in_month(year, month)` to return the number of days in a given month of a calendar year. Your function should validate the input `year` and `month` and handle leap years correctly. If the input is invalid, it should raise an appropriate excepti... |
To comment out a code snippet using block comments, let's follow these steps:
1. Remove any existing comments from the snippet using regular expressions, if any.
2. Split the snippet into lines and comment out each line by prepending `#`.
3. Join the commented lines with newlines and surround with block comments.
Her... | Write a Python function that takes a code snippet as a string and returns a string with the code commented out using block comments.
Example:
```
code_snippet = """
# This is a code snippet
def function():
pass
"""
```
Calling the function with the snippet above should return:
```
"""
# This is a code snippet
# ... | You can achieve this by defining a function that takes a code snippet as input and prepends `# ` to each line of the code. You can use the `splitlines()` method to split the snippet into individual lines, apply the comment addition, and then join the lines back together. Here is a function that does exactly that:
```p... | 48,144 | [
{
"from": "human",
"value": "Write a Python function that takes a code snippet as a string and returns a string with the code commented out using block comments.\nExample:\n\n```\ncode_snippet = \"\"\"\n# This is a code snippet\ndef function():\n pass\n\"\"\"\n```\n\nCalling the function with the snippet... |
```python
def get_names_of_base_classes(cls):
base_classes = cls.__bases__
names = set()
for base_class in base_classes:
name = getattr(base_class, '__name__', None)
if name is None:
name = base_class.__name__
names.add(name)
names.update(get_names_of_base_classes... | Write a Python function `get_names_of_base_classes` that takes a class object and returns a set containing the names of all its base classes. You can use `cls.__bases__` to get a tuple of base classes, `getattr(cls, '__name__', None)` to get its name, and `cls.__name__` to get the name of the base class. | Certainly! Below is a Python function `get_names_of_base_classes` that takes a class object as an argument and returns a set containing the names of all its base classes:
```python
def get_names_of_base_classes(cls):
# Initialize an empty set to hold the names of base classes
base_class_names = set()
# It... | 48,145 | [
{
"from": "human",
"value": "Write a Python function `get_names_of_base_classes` that takes a class object and returns a set containing the names of all its base classes. You can use `cls.__bases__` to get a tuple of base classes, `getattr(cls, '__name__', None)` to get its name, and `cls.__name__` to get t... |
Here is an implementation of the `create_div_element` function in Python:
```python
def create_div_element(content, classes=None):
if classes is None:
classes = []
class_attr = ' '.join(classes)
if class_attr:
class_attr = f' class="{class_attr}"'
return f'<div{class_attr}>{content}</di... | Write a Python function `create_div_element` that takes a string `content` and an optional keyword argument `classes` (a list of strings) as input. The function should return a string representing a `<div>` element with the `content` as its inner HTML and the given classes assigned to its `class` attribute. The functio... | You can create the function `create_div_element` in Python as follows. The function will accept a string `content` and an optional keyword argument `classes` (a list of strings). It will construct and return a string representation of an HTML `<div>` element.
Here's the implementation:
```python
def create_div_elemen... | 48,146 | [
{
"from": "human",
"value": "Write a Python function `create_div_element` that takes a string `content` and an optional keyword argument `classes` (a list of strings) as input. The function should return a string representing a `<div>` element with the `content` as its inner HTML and the given classes assig... |
To create a function that takes a string containing a list of integers in the given format and returns a list of integers, we can use the `eval` function, which evaluates a string as a Python expression. We can also use the `json` module to parse the string and convert it to a Python list.
Here is a Python function th... | Create a Python function to take a string containing a list of integers in the format `"[1, 2, 3, 4, 5]"` and return a list of integers. You can assume that the string is always in the correct format. | You can create a Python function to convert a string representation of a list into an actual Python list of integers using the `ast.literal_eval` function. This is a safe way to evaluate the string, assuming it's well-formed. Here's how you can do it:
```python
import ast
def string_to_int_list(s):
# Evaluate the... | 48,147 | [
{
"from": "human",
"value": "Create a Python function to take a string containing a list of integers in the format `\"[1, 2, 3, 4, 5]\"` and return a list of integers. You can assume that the string is always in the correct format."
},
{
"from": "gpt",
"value": "You can create a Python function ... |
To assign a new value to a column in a Pandas dataframe based on the value of another column, we can use the `.loc` accessor to select the rows in the dataframe where the reference column's value matches a given key in the mapping dictionary, and assign the new value to the target column.
Here's a Python function that... | Write a Python function to assign a new value to a column in a Pandas dataframe based on the value of another column. The function should take the dataframe as the first argument, the name of the column to modify as the second argument, and the value to assign as the third argument. The function should also take a four... | You can achieve this by creating a function that utilizes the Pandas `map` method to assign new values to the specified column based on the mapping provided in the dictionary. Below is the implementation of the `assign_value_to_col` function that satisfies your requirements:
```python
import pandas as pd
def assign_v... | 48,148 | [
{
"from": "human",
"value": "Write a Python function to assign a new value to a column in a Pandas dataframe based on the value of another column. The function should take the dataframe as the first argument, the name of the column to modify as the second argument, and the value to assign as the third argum... |
The conditional probability of a random variable given a continuous random variable can be estimated in Python using the following steps:
1. **Define the probability density functions:**
The first step is to define the probability density functions for X and Y. In this case, we have provided two probability density fu... | Develop a function in Python that estimates the conditional probability of a random variable, given a continuous random variable. The function should take two arguments: a conditional probability distribution function P(Y|X=x) and a probability density function P(X). Your function should return the conditional probabil... | To achieve this, we can define a Python function that constructs a conditional probability distribution \( P(Y|X) \) based on the provided conditional probability distribution function \( P(Y|X=x) \) and the probability density function \( P(X) \).
Assuming the conditional distributions are normal as specified in you... | 48,149 | [
{
"from": "human",
"value": "Develop a function in Python that estimates the conditional probability of a random variable, given a continuous random variable. The function should take two arguments: a conditional probability distribution function P(Y|X=x) and a probability density function P(X). Your functi... |
To count the total number of specific data types in a nested dictionary, we can use a recursive function that traverses the dictionary and its nested levels. The function should take the input dictionary and the specific data type as parameters. We can then use a counter variable to keep track of the occurrences of the... | Write a Python function to count the total number of specific data types in a nested dictionary. The function should accept the input dictionary and the specific data type as parameters. Traverse the dictionary and its nested levels to count the occurrences of the specified data type. | Certainly! You can achieve this by writing a recursive function that will traverse the nested dictionary and count the occurrences of the specified data type. Below is an example implementation of such a function in Python:
```python
def count_data_type(data_dict, data_type):
"""
Count the total number of spec... | 48,150 | [
{
"from": "human",
"value": "Write a Python function to count the total number of specific data types in a nested dictionary. The function should accept the input dictionary and the specific data type as parameters. Traverse the dictionary and its nested levels to count the occurrences of the specified data... |
Here's how you could implement the `convert_unix_to_datetime` function:
```python
import datetime
import pytz
def convert_unix_to_datetime(unix_timestamp, timezone=None):
if unix_timestamp is None or not isinstance(unix_timestamp, int):
return None
if timezone is None:
timezone = pytz.timezon... | Develop a Python function `convert_unix_to_datetime` that takes two arguments: `unix_timestamp` (a UNIX timestamp) and `timezone` (a timezone string like `"America/Chicago"`). The function should convert the UNIX timestamp to a datetime object (with the given timezone) and return it. If `unix_timestamp` is `None` or if... | To implement the function `convert_unix_to_datetime`, we can make use of the `datetime` module for handling date and time and the `pytz` library for timezone management. Below is the code for the function, followed by explanations of its components.
First, ensure you have the `pytz` library installed. You can install ... | 48,151 | [
{
"from": "human",
"value": "Develop a Python function `convert_unix_to_datetime` that takes two arguments: `unix_timestamp` (a UNIX timestamp) and `timezone` (a timezone string like `\"America/Chicago\"`). The function should convert the UNIX timestamp to a datetime object (with the given timezone) and ret... |
To group the tests by their name patterns, we need to identify the pattern and match it against the test names. We can use a regular expression to match the pattern and extract the name components.
The following Python code example demonstrates how we can implement this:
```python
import re
def group_tests_by_patter... | Write a Python function that takes a list of test names as input and returns a new list of test cases, where each test case is a list of tests that match a specific pattern. The pattern is identified by a regular expression that matches the following pattern:
```
"^test_[a-zA-Z0-9]+_[0-9]+"
```
The pattern matches te... | You can achieve this functionality by using the `re` module in Python for regular expression matching. Below is a Python function that takes a list of test names and groups them into separate lists based on the specified pattern:
```python
import re
from collections import defaultdict
def group_test_cases(test_names)... | 48,152 | [
{
"from": "human",
"value": "Write a Python function that takes a list of test names as input and returns a new list of test cases, where each test case is a list of tests that match a specific pattern. The pattern is identified by a regular expression that matches the following pattern:\n\n```\n\"^test_[a-... |
Here is a Python function that implements this approach:
```python
def sum_list_of_lists(lst: list) -> int:
"""
Takes a list of lists of numbers and returns the sum of all numbers in the list.
For example, given [[1, 2, 3], [4, 5, 6], [7, 8, 9]], the function should return 45.
"""
if not isinstance... | Create a Python function that takes a list of lists of numbers and returns the sum of all numbers in the list. For example, given `[[1, 2, 3], [4, 5, 6], [7, 8, 9]]`, the function should return `45`. Make sure to check the type of the input to ensure it is a list of lists before iterating over it. | You can create the function as follows. This function checks if the input is a list of lists, then iterates through each sublist and sums up the numbers.
Here's the implementation:
```python
def sum_of_numbers(nested_list):
# Check if the input is a list
if not isinstance(nested_list, list):
raise Val... | 48,153 | [
{
"from": "human",
"value": "Create a Python function that takes a list of lists of numbers and returns the sum of all numbers in the list. For example, given `[[1, 2, 3], [4, 5, 6], [7, 8, 9]]`, the function should return `45`. Make sure to check the type of the input to ensure it is a list of lists before... |
To implement the `is_same_word` function, we need to take into account several considerations outlined in the instructions.
First, the function should consider case-insensitive comparison, which means that strings should be compared regardless of their letter case. One way to achieve this is by converting both strings... | Implement a Python function named `is_same_word(word1, word2)` that takes two strings `word1` and `word2` as input and returns True if the strings are the same word, False otherwise. The function should consider the following:
- Case-insensitive comparison
- Unicode-aware comparison
- Unicode normalization
- Whitespac... | To implement the `is_same_word` function according to your specifications, we need to perform several tasks to ensure that the comparison of the two words is accurate. This includes normalizing case, removing whitespace and punctuation, and ensuring Unicode normalization. We can utilize the `unicodedata` library for no... | 48,154 | [
{
"from": "human",
"value": "Implement a Python function named `is_same_word(word1, word2)` that takes two strings `word1` and `word2` as input and returns True if the strings are the same word, False otherwise. The function should consider the following:\n\n- Case-insensitive comparison\n- Unicode-aware co... |
To convert a string of degrees in the format `34° 24' 52.804" N` to a floating point number, we can split the string into individual components: degrees, minutes, seconds, and direction. We can then calculate the number of degrees by combining these components.
Here is a Python function that implements this approach:
... | Create a Python function to convert a string of degrees in the format `34° 24' 52.804" N` to a floating point number representing the corresponding number of degrees. The input degrees may contain degrees (`°`), minutes (`'`), and seconds (`"`), and may be followed by either `N` or `S` to indicate North or South, respe... | You can create a function in Python that converts a string representation of geographic coordinates in the format `34° 24' 52.804" N` to a floating-point number representing the corresponding decimal degrees. The function will handle the conversion of degrees, minutes, and seconds, and will account for the direction (N... | 48,155 | [
{
"from": "human",
"value": "Create a Python function to convert a string of degrees in the format `34° 24' 52.804\" N` to a floating point number representing the corresponding number of degrees. The input degrees may contain degrees (`°`), minutes (`'`), and seconds (`\"`), and may be followed by either `... |
To filter out elements that contain "b" or "d", you can use a list comprehension with a conditional expression that checks if the element contains one of these substrings.
Here's a Python function that takes a list of strings and returns a new list with the filtered elements:
```python
def filter_b_or_d(strings):
... | I have a list of strings (e.g., `['a', 'b', 'c', 'd', ...]`) and I want to filter out any element that contains a substring "b" or "d" (i.e., I want to exclude "b" and "d" and also their substrings like "bd" and "db").
Write a Python function that takes a list of strings and returns a new list with these filtered elem... | You can create a Python function that filters out any elements from a list of strings that contain the substrings "b" or "d". Below is an example of such a function:
```python
def filter_strings(strings):
# Use a list comprehension to filter out strings containing 'b' or 'd'
filtered_list = [s for s in strings... | 48,156 | [
{
"from": "human",
"value": "I have a list of strings (e.g., `['a', 'b', 'c', 'd', ...]`) and I want to filter out any element that contains a substring \"b\" or \"d\" (i.e., I want to exclude \"b\" and \"d\" and also their substrings like \"bd\" and \"db\").\n\nWrite a Python function that takes a list of ... |
Here's how you could implement this function:
```python
import re
def match_and_split(pattern, sentence):
match = re.search(pattern, sentence)
if match:
return re.split(pattern, sentence)
else:
return []
```
The `match_and_split` function uses the `re.search` function to search for a matc... | Write a Python function `match_and_split` that takes two strings, `pattern` and `sentence`, and returns a list of strings. The function should match the `pattern` with the `sentence` using a regular expression. If the match is successful, it should split the sentence into subsequences based on the matched pattern and r... | Here is a Python function `match_and_split` that uses the `re` module to match the specified pattern with the input sentence and returns the result as specified:
```python
import re
def match_and_split(pattern, sentence):
# Compile the pattern for matching
regex = re.compile(pattern)
# Use the patter... | 48,157 | [
{
"from": "human",
"value": "Write a Python function `match_and_split` that takes two strings, `pattern` and `sentence`, and returns a list of strings. The function should match the `pattern` with the `sentence` using a regular expression. If the match is successful, it should split the sentence into subseq... |
To solve this problem, you can utilize list comprehension and tuple deconstruction to extract the first name from each tuple and capitalize it.
Here's a concise solution:
```python
def capitalize_first_names(employee_info):
return [name.capitalize() for name, _ in employee_info]
```
The `capitalize_first_names` ... | Given a list of tuples representing employee information, write a Python function that returns a list of all the employees' names with the first name being capitalized. For example, if the input is `[(“john”, “doe”), (“jane”, “doe”)]`, the function should return `[“”, “”]`.
Utilize list comprehension and tuple deconst... | You can achieve this using a list comprehension along with tuple unpacking. Below is a Python function that takes a list of tuples as input and returns a list of formatted employee names with the first names capitalized.
Here is the code:
```python
def capitalize_employee_names(employee_info):
return [f"{first.ca... | 48,158 | [
{
"from": "human",
"value": "Given a list of tuples representing employee information, write a Python function that returns a list of all the employees' names with the first name being capitalized. For example, if the input is `[(“john”, “doe”), (“jane”, “doe”)]`, the function should return `[“”, “”]`.\n\nU... |
To replace the `np.nan` values with the corresponding values from the other dictionary, we can iterate over the keys of the dictionaries and compare the values. If both values are `np.nan`, we will replace them with the values from the other dictionary.
Here is the implementation of the function:
```python
import num... | I have two dictionaries, `d1` and `d2`, each representing a data frame with the same set of columns. The values are all `np.nan` (missing values). I want to merge the two dictionaries and replace the `np.nan` values with the corresponding values from the other dictionary.
Write a function that takes `d1` and `d2` as i... | You can achieve this by creating a function that iterates through the keys and values of the two dictionaries. For each key, you can replace `np.nan` values from one dictionary with corresponding values from the other dictionary. Here's how you can implement this:
```python
import numpy as np
def merge_dicts(d1, d2):... | 48,159 | [
{
"from": "human",
"value": "I have two dictionaries, `d1` and `d2`, each representing a data frame with the same set of columns. The values are all `np.nan` (missing values). I want to merge the two dictionaries and replace the `np.nan` values with the corresponding values from the other dictionary.\n\nWri... |
To create a Python function that takes a string as an argument and returns a list of tuples containing the split words and their lengths in the string, you can follow these steps:
1. Split the string into individual words using the built-in `str.split()` method.
2. Use a list comprehension to iterate over the words an... | Create a Python function that takes a string as an argument and returns a list of tuples containing the split words and their lengths in the string. If the string includes a comma, parse it as a CSV. | You can create a function that checks for commas in the input string and splits the string accordingly. If commas are present, it will split by commas (treating it as CSV) and then measure the lengths of the resulting words. If no commas are present, it will just split the string into words based on whitespace. Here's ... | 48,160 | [
{
"from": "human",
"value": "Create a Python function that takes a string as an argument and returns a list of tuples containing the split words and their lengths in the string. If the string includes a comma, parse it as a CSV."
},
{
"from": "gpt",
"value": "You can create a function that check... |
The function could be implemented in Python like this:
```python
def get_effective_rate(nominal_rate: float, term: int) -> float:
"""
Calculate the effective rate from a given nominal rate.
Args:
nominal_rate (float): The nominal interest rate.
term (int): The number of years of the loan.
... | Write a Python function to calculate the effective rate from a given nominal rate. The function should be named `get_effective_rate`, accept parameters named `nominal_rate` and `term`, and return a float value.
Provide a docstring for the function that explains the function's role and parameter descriptions. | Here's a Python function named `get_effective_rate` that calculates the effective interest rate from a given nominal rate and compounding term. The function includes a descriptive docstring explaining its purpose and parameters.
```python
def get_effective_rate(nominal_rate, term):
"""
Calculate the effective ... | 48,161 | [
{
"from": "human",
"value": "Write a Python function to calculate the effective rate from a given nominal rate. The function should be named `get_effective_rate`, accept parameters named `nominal_rate` and `term`, and return a float value.\n\nProvide a docstring for the function that explains the function's... |
Here's an implementation in Python:
```python
import numpy as np
def compute_confidence_intervals(samples):
samples = np.sort(samples)
n_samples = len(samples)
lower_bound = np.percentile(samples, 5)
upper_bound = np.percentile(samples, 95)
return (lower_bound, upper_bound)
```
This function calc... | Given an array of posterior samples of a model, how would you compute the 5% and 95% confidence intervals of the posterior distribution?
Your code should pass the following test case:
```python
samples = np.random.normal(0, 1, 1000)
lower_bound, upper_bound = compute_confidence_intervals(samples)
assert lower_bound < ... | To compute the 5% and 95% confidence intervals of a posterior distribution represented by an array of samples, you can use the NumPy library. The 5th percentile and the 95th percentile can be obtained using the `np.percentile` function.
Here's how you can write the function `compute_confidence_intervals`:
```python
i... | 48,162 | [
{
"from": "human",
"value": "Given an array of posterior samples of a model, how would you compute the 5% and 95% confidence intervals of the posterior distribution?\n\nYour code should pass the following test case:\n```python\nsamples = np.random.normal(0, 1, 1000)\nlower_bound, upper_bound = compute_confi... |
Here's a sample implementation of the `parse_fitness_report` function using list comprehension to split each line in the file and convert the resulting strings to floats:
```python
def parse_fitness_report(filename):
report = {}
with open(filename, 'r') as file:
for line in file:
components... | I want to parse the report of a multiobjective genetic algorithm that contains the best fitness, the average fitness, and the worst fitness for each generation. The report is in a text file named `fitnesses.txt`, where each line is structured as `generation; best; average; worst`. I want to load these values into a dic... | Here’s a Python function that parses the fitness report from a text file in the specified format and returns a dictionary as you described:
```python
def parse_fitness_report(filename):
report = {}
with open(filename, 'r') as file:
for line in file:
generation, best, average, worst = l... | 48,163 | [
{
"from": "human",
"value": "I want to parse the report of a multiobjective genetic algorithm that contains the best fitness, the average fitness, and the worst fitness for each generation. The report is in a text file named `fitnesses.txt`, where each line is structured as `generation; best; average; worst... |
Here's how we can implement this function:
```python
def filter_letters(input_string):
result = ""
for char in input_string:
if char.isalpha() or char.isspace() or char == '-':
result += char
return result
``` | Create a Python function to take a string and return a new string with only its letters, spaces, and hyphens. The function should handle special characters such as commas, periods, and apostrophes, but not letters, spaces, and hyphens.
Your code should pass the following test case:
```python
input_string = "Hello, wor... | You can create the function `filter_letters` that processes the input string to retain only letters (both uppercase and lowercase), spaces, and hyphens. Any other characters, including special characters like commas, periods, and apostrophes, will be removed.
Here's how you can implement this function:
```python
def... | 48,164 | [
{
"from": "human",
"value": "Create a Python function to take a string and return a new string with only its letters, spaces, and hyphens. The function should handle special characters such as commas, periods, and apostrophes, but not letters, spaces, and hyphens.\n\nYour code should pass the following test... |
Here's how you can create a deep copy of a dictionary with some values as dictionaries:
```python
import copy
def deep_copy_with_dicts(original_dict):
"""
Creates a deep copy of a dictionary, where the values are also dictionaries.
If a non-dictionary value is encountered, it is converted to a dictionary
... | Write a Python function to create a deep copy of a dictionary, where the values are also dictionaries. The function should also include a docstring describing what the function does and any assumptions made about the inputs. For any key-value pairs in the original dictionary that are not dictionaries, the function shou... | Below is a Python function called `deep_copy_with_dicts` that creates a deep copy of a dictionary. The function handles the specified transformations of the values, ensuring that all values that are not dictionaries are converted into a dictionary with `None` as the key and value.
```python
def deep_copy_with_dicts(or... | 48,165 | [
{
"from": "human",
"value": "Write a Python function to create a deep copy of a dictionary, where the values are also dictionaries. The function should also include a docstring describing what the function does and any assumptions made about the inputs. For any key-value pairs in the original dictionary tha... |
To swap the opening and closing tags, you can use a regular expression to match opening and closing tags that have attributes and replace them with the corresponding opening and closing tags.
Here's the code:
```python
import re
def swap_tags(html_string):
match = re.match(r'<(?P<tag>\w+).*?>', html_string)
... | Write a Python function that accepts a string containing HTML tags and attributes as an argument and returns an equivalent string where the opening and closing tags are swapped. For example, the function should accept `<a href="https://example.com">Example</a>` as an input and return `<a>Example</a href="https://exampl... | To create a function that swaps the opening and closing tags of HTML elements in a given string, we need to carefully parse the HTML. This involves identifying the tags, extracting their attributes, and reconstructing the tags in the swapped form.
Here's a Python function that accomplishes this task:
```python
impor... | 48,166 | [
{
"from": "human",
"value": "Write a Python function that accepts a string containing HTML tags and attributes as an argument and returns an equivalent string where the opening and closing tags are swapped. For example, the function should accept `<a href=\"https://example.com\">Example</a>` as an input and... |
Here's how you could do it:
```python
import html
def escape_html_characters(text):
return html.escape(text)
```
This function uses the `html.escape()` function to escape the special characters in a string. The `html.escape()` function takes a string as input and returns the escaped version of the string, replac... | Write a Python function to escape HTML special characters in a string. The special characters and their corresponding HTML entities are:
- `&`: `&`
- `<`: `<`
- `>`: `>`
- `"`: `"`
- `'` (single quote): `'`
Your code should pass the following test case:
```python
text = "I love Python & Data Scienc... | You can achieve HTML escaping in Python by creating a function that replaces each special character with its corresponding HTML entity. Here's a function `escape_html_characters` that performs this task:
```python
def escape_html_characters(text):
"""Escape HTML special characters in the given text."""
html_es... | 48,167 | [
{
"from": "human",
"value": "Write a Python function to escape HTML special characters in a string. The special characters and their corresponding HTML entities are:\n\n- `&`: `&`\n- `<`: `<`\n- `>`: `>`\n- `\"`: `"`\n- `'` (single quote): `'`\n\nYour code should pass the following test c... |
Here's a Python function that meets these requirements:
```python
def count_chars(input_str):
def count_chars_helper(input_str, char_dict):
if len(input_str) == 0:
return char_dict
char = input_str[0]
if char in char_dict:
char_dict[char] += 1
else:
... | Design a Python function that takes a string or a list of characters and returns the number of times each character appears in the input. If the input is a string, ignore case. The output should be a dictionary with characters as keys and their counts as values. Sort the keys in alphabetical order.
Write your function... | Here's a solution that meets your requirements. The function `count_chars` is designed to handle both strings and lists of characters, counting the occurrences of each character recursively.
Here's the implementation:
```python
def count_chars(input_data):
# Initialize the dictionary to store character counts
... | 48,168 | [
{
"from": "human",
"value": "Design a Python function that takes a string or a list of characters and returns the number of times each character appears in the input. If the input is a string, ignore case. The output should be a dictionary with characters as keys and their counts as values. Sort the keys in... |
Here is a Python function that implements this approach:
```python
def create_dictionary_from_file(filename: str) -> dict:
"""
Creates a dictionary from a text file. The text file is a list of key-value pairs,
with each line containing a pair and separated by a colon (:).
"""
dictionary = {}
w... | Write a Python function to create a dictionary from a text file. The text file is a list of key-value pairs, with each line containing a pair and separated by a colon (:).
The function should read the file line by line, and for each line, split the line around the colon and add the resulting key-value pair to the dict... | Certainly! Below is a Python function that reads a text file containing key-value pairs separated by a colon (`:`) and constructs a dictionary from them.
```python
def create_dict_from_file(file_path):
"""
Reads a text file and returns a dictionary of key-value pairs.
Args:
file_path (str): The pa... | 48,169 | [
{
"from": "human",
"value": "Write a Python function to create a dictionary from a text file. The text file is a list of key-value pairs, with each line containing a pair and separated by a colon (:).\n\nThe function should read the file line by line, and for each line, split the line around the colon and a... |
Here is the implementation:
```python
from datetime import date
def date_to_days(date_string):
year, month, day = map(int, date_string.split("-"))
date_object = date(year, month, day)
unix_epoch = date(1970, 1, 1)
days_since_epoch = (date_object - unix_epoch).days
return days_since_epoch
``` | Write a Python function to convert a date string in the format `YYYY-MM-DD` to the number of days since the Unix epoch (1970-01-01). The function should return an integer.
Your code should pass the following assertions:
```python
assert date_to_days("1970-01-02") == 1
assert date_to_days("1970-01-03") == 2
assert date... | You can use the `datetime` module in Python to convert a date string to the number of days since the Unix epoch (January 1, 1970). Below is a function that accomplishes this, along with the assertions you've provided:
```python
from datetime import datetime
def date_to_days(date_str):
# Define the format for the ... | 48,170 | [
{
"from": "human",
"value": "Write a Python function to convert a date string in the format `YYYY-MM-DD` to the number of days since the Unix epoch (1970-01-01). The function should return an integer.\n\nYour code should pass the following assertions:\n```python\nassert date_to_days(\"1970-01-02\") == 1\nas... |
To solve this problem, you can follow these steps:
1. Check the input parameters and raise an error if they are not valid.
2. Slice the `data` list using `start` and `end` indexes.
3. Create a generator function that iterates over the sliced list and yields each item as a dictionary.
4. Return the generator object.
He... | Write a function named `load_data` that takes in a slice and returns a generator object. The function should take three parameters:
- `data`: A list of dictionaries.
- `start`: The starting index of the slice (default value: 0).
- `end`: The ending index of the slice (default value: `len(data)`).
The function should ... | You can create the `load_data` function as described. Below is a Python implementation of the specified function, which takes a list of dictionaries and returns a generator that yields dictionaries from the specified slice of the list.
```python
def load_data(data, start=0, end=None):
if end is None:
end =... | 48,171 | [
{
"from": "human",
"value": "Write a function named `load_data` that takes in a slice and returns a generator object. The function should take three parameters:\n\n- `data`: A list of dictionaries.\n- `start`: The starting index of the slice (default value: 0).\n- `end`: The ending index of the slice (defau... |
You can create a Python function that takes in a graph represented as a dictionary of nodes and a starting node, and returns all the parents of that node. The function should perform joint node validation, ensuring that both the parent and child nodes are present in the graph.
Here's how you could implement the `find_... | Implement a Python function `find_parents()` that, given a graph represented as a dictionary of nodes, returns all the parents of a given node. The function should perform joint node validation, ensuring that both the parent and child nodes are present in the graph.
Use a while loop to iterate over parent nodes, and u... | To implement the `find_parents()` function in Python, we can follow these steps:
1. Define the function which takes two parameters: the graph (as a dictionary) and the target node whose parents we want to find.
2. Verify if the target node exists in the graph. If not, return an empty list.
3. Initialize a list to keep... | 48,172 | [
{
"from": "human",
"value": "Implement a Python function `find_parents()` that, given a graph represented as a dictionary of nodes, returns all the parents of a given node. The function should perform joint node validation, ensuring that both the parent and child nodes are present in the graph.\n\nUse a whi... |
To write a Python function that takes a string and returns a list of lists of integers, you can follow these steps:
1. Split the input string into a list of strings using the `.split()` method.
2. Iterate over each string in the list, and split it into a list of strings using the `.split()` method again.
3. Iterate ov... | Write a Python function `parse_string_into_lists` that takes a string and returns a list of lists of integers. The input string consists of comma-separated characters that represent integers. Each comma-separated group of characters represents a list of integers. Integers may be separated by spaces or commas.
For exam... | To achieve the requirement of parsing a string into a list of lists of integers based on the described format, we can follow these steps:
1. Split the input string by commas to get groups of characters.
2. For each group, remove any leading or trailing whitespace.
3. Further split these groups by spaces or commas to e... | 48,173 | [
{
"from": "human",
"value": "Write a Python function `parse_string_into_lists` that takes a string and returns a list of lists of integers. The input string consists of comma-separated characters that represent integers. Each comma-separated group of characters represents a list of integers. Integers may be... |
Here's how you can implement the `derivate_legendre_polynomial` function in Python:
```python
from math import factorial # import the factorial function from the math module
def double_factorial(n):
"""Returns the double factorial of n."""
if n <= 1:
return 1
elif n % 2 == 0: # n is even
... | Create a Python function `derivate_legendre_polynomial` that differentiates a Legendre polynomial of degree `n`. A Legendre polynomial is a polynomial in the form of `P_n(x) = ((2n - 1)!! (x^2 - 1)^n) / (2^n n!)` where `!!` is the double factorial operator and `(x^2 - 1)^n` is the `n`th power of the polynomial `(x^2 - ... | To create a function that differentiates Legendre polynomials, we first need to understand the formula given for the Legendre polynomial \( P_n(x) \). The polynomial can be expressed in a more manageable format, and we can subsequently take its derivative.
Let's break down the function step by step:
1. **Define the L... | 48,174 | [
{
"from": "human",
"value": "Create a Python function `derivate_legendre_polynomial` that differentiates a Legendre polynomial of degree `n`. A Legendre polynomial is a polynomial in the form of `P_n(x) = ((2n - 1)!! (x^2 - 1)^n) / (2^n n!)` where `!!` is the double factorial operator and `(x^2 - 1)^n` is t... |
```python
def square_integers(nums, k):
return [num ** 2 for num in nums if num >= k]
``` | Write a Python function that accepts a list of integers `nums` and an integer `k` and returns a list of integers containing the square of each integer in `nums` that is greater than or equal to `k`. Use list comprehension and boolean masking, and assign the square of each integer to the corresponding element of the res... | You can create the desired function using list comprehension as follows. This function will iterate over each integer in the provided list `nums`, check if it is greater than or equal to `k`, and if it is, it will compute its square and add it to the result list.
Here’s how you can implement this in Python:
```python... | 48,175 | [
{
"from": "human",
"value": "Write a Python function that accepts a list of integers `nums` and an integer `k` and returns a list of integers containing the square of each integer in `nums` that is greater than or equal to `k`. Use list comprehension and boolean masking, and assign the square of each intege... |
Here is how you could implement such a function:
```python
class MyObject:
def __init__(self, value):
self.value = value
def to_string(self):
return f"{self.value} (from to_string)"
def to_string(obj):
if hasattr(obj, "to_string"):
return obj.to_string()
else:
return s... | Write a Python function `to_string` that converts any object to a string. If the object has a `to_string` method, it will use that. Otherwise, it will fallback to `str(obj)`. | Certainly! Below is the implementation of the `to_string` function that checks if the object has a `to_string` method. If it does, the method is called; otherwise, it falls back to the default string conversion using `str()`.
```python
def to_string(obj):
"""
Convert an object to a string.
If the object ha... | 48,176 | [
{
"from": "human",
"value": "Write a Python function `to_string` that converts any object to a string. If the object has a `to_string` method, it will use that. Otherwise, it will fallback to `str(obj)`."
},
{
"from": "gpt",
"value": "Certainly! Below is the implementation of the `to_string` fun... |
To check the validity of the formula, you can first check if the formula is a valid dictionary by performing a type check. Then, you can iterate through the elements in the formula dictionary and check if they meet the rules for a valid chemical formula.
Here's how you can implement the function in Python:
```python
... | I have a dictionary object that defines a chemical formula. Each key in the dictionary represents an element in the formula, and the corresponding value is the number of atoms of that element in the formula. Write a Python function that checks whether the given formula is valid. The function should return True if the f... | You can implement the function `is_valid_formula` that checks the validity of the chemical formula defined in a dictionary format according to the rules you've provided. Here’s one way to implement this function:
```python
def is_valid_formula(formula):
# Check if the formula contains at least one element
if n... | 48,177 | [
{
"from": "human",
"value": "I have a dictionary object that defines a chemical formula. Each key in the dictionary represents an element in the formula, and the corresponding value is the number of atoms of that element in the formula. Write a Python function that checks whether the given formula is valid.... |
```python
import re
def get_ascii_char_count(string):
if not string:
return 0
ascii_chars = re.findall(r"[ -~]+", string)
if not ascii_chars:
return 0
return len("".join(ascii_chars))
``` | Create a Python function `get_ascii_char_count(string)` that counts the number of ASCII characters in the input string, ignoring other Unicode characters and special symbols. The function should handle incorrect input gracefully and return 0 in that case. | Certainly! You can create a Python function `get_ascii_char_count(string)` that counts the number of ASCII characters in a given string, ignoring any non-ASCII characters. Below is an implementation of this function.
```python
def get_ascii_char_count(string):
# Ensure input is a string
if not isinstance(strin... | 48,178 | [
{
"from": "human",
"value": "Create a Python function `get_ascii_char_count(string)` that counts the number of ASCII characters in the input string, ignoring other Unicode characters and special symbols. The function should handle incorrect input gracefully and return 0 in that case."
},
{
"from": "... |
Here's how you can implement this function:
```python
import re
def palindrome_detector(string: str) -> bool:
stripped_string = re.sub(r'[^a-zA-Z0-9]', '', string)
lowercase_string = stripped_string.lower()
return lowercase_string == ''.join(reversed(lowercase_string))
```
This function processes the str... | Design a Python function to detect whether a string is a palindrome. A palindrome is a string that reads the same forward and backward. Your function should use regular expressions to remove all non-alphanumeric characters and then check if the resulting string is a palindrome.
Your code should pass the following asse... | You can create a function to detect palindromes by using the `re` module to filter out non-alphanumeric characters and then checking if the cleaned string reads the same forwards and backwards. Here's how you can implement this:
```python
import re
def palindrome_detector(s: str) -> bool:
# Use regular expression... | 48,179 | [
{
"from": "human",
"value": "Design a Python function to detect whether a string is a palindrome. A palindrome is a string that reads the same forward and backward. Your function should use regular expressions to remove all non-alphanumeric characters and then check if the resulting string is a palindrome.\... |
Here's an example of how you can extract the date and time components from a string using Python:
```python
from datetime import datetime
def extract_date_time_components(input_string):
date_time = datetime.strptime(input_string, '%Y-%m-%d %H:%M:%S.%f')
date = date_time.strftime('%Y-%m-%d')
time = date_ti... | Given a string of the form '2020-08-12 12:30:00.00012', write a Python function to extract the date and time components as separate strings. The input string is formatted according to the ISO 8601 standard, with the date in YYYY-MM-DD format and the time in HH:MM:SS.sss (millisecond precision) format.
Your code should... | You can achieve this by defining a function called `extract_date_time_components`. This function will take an ISO 8601 formatted string and split it into the date and time components. Here’s how the implementation would look:
```python
def extract_date_time_components(iso_string):
date_part, time_part = iso_string... | 48,180 | [
{
"from": "human",
"value": "Given a string of the form '2020-08-12 12:30:00.00012', write a Python function to extract the date and time components as separate strings. The input string is formatted according to the ISO 8601 standard, with the date in YYYY-MM-DD format and the time in HH:MM:SS.sss (millise... |
```python
from typing import Optional, Union
def generate_info(name: str, age: Optional[int] = None) -> str:
if age is not None:
return f"Name: {name}, Age: {age}"
else:
return f"Name: {name}, Age: age not provided"
``` | Create a Python function that takes a string `name` and an optional integer `age` as parameters and returns a string. The function should return a string that interpolates the name and age if age is provided, and interpolates the name and 'age not provided' otherwise. Use the `typing` module to specify the types of the... | Certainly! You can create a Python function that fulfills the described requirements using type annotations from the `typing` module. Here’s how you can implement it:
```python
from typing import Optional
def greet(name: str, age: Optional[int] = None) -> str:
if age is not None:
return f"Hello, {name}! Y... | 48,181 | [
{
"from": "human",
"value": "Create a Python function that takes a string `name` and an optional integer `age` as parameters and returns a string. The function should return a string that interpolates the name and age if age is provided, and interpolates the name and 'age not provided' otherwise. Use the `t... |
Here's how we can implement this:
```python
def split_on_delimiter(string, delimiter=None):
if delimiter is None:
return string.split()
if not string:
raise ValueError("Input string is empty.")
return string.split(delimiter)
```
In this implementation, we use the `.split()` method to split... | Write a Python function to split a string into a list of substrings based on a given delimiter character. If no delimiter is specified, the function should split on spaces. The function should ignore any leading or trailing empty substrings. Make sure it handles empty inputs and raises ValueError if none of the input c... | You can create a function named `split_on_delimiter` that takes two arguments: the string to split and the delimiter character. The function will handle the specified requirements, including handling empty inputs and raising a `ValueError` when the delimiter does not cause any splits. Here is how you can implement it:
... | 48,182 | [
{
"from": "human",
"value": "Write a Python function to split a string into a list of substrings based on a given delimiter character. If no delimiter is specified, the function should split on spaces. The function should ignore any leading or trailing empty substrings. Make sure it handles empty inputs and... |
Here's how you can implement this function:
```python
import urllib.parse
def extract_url_parts(url: str) -> dict:
parsed_url = urllib.parse.urlparse(url)
if not parsed_url.scheme or not parsed_url.netloc or not parsed_url.path:
raise ValueError('Invalid URL')
return {
'scheme': parsed_url.scheme,
... | Write a Python function that takes a URL string as input and returns a dictionary with the following keys: `scheme`, `netloc`, `path`, `query`, and `fragment`. For example, given the URL `http://example.com/path/to/file.html?key1=value1&key2=value2#fragment`, the function should return the following dictionary:
```pyt... | You can use the `urllib.parse` module from the Python standard library to achieve this. The `urlparse` function from this module can parse the URL and extract the necessary components. Here’s how you can implement the function:
```python
from urllib.parse import urlparse, parse_qs
def parse_url(url):
# Parse the ... | 48,183 | [
{
"from": "human",
"value": "Write a Python function that takes a URL string as input and returns a dictionary with the following keys: `scheme`, `netloc`, `path`, `query`, and `fragment`. For example, given the URL `http://example.com/path/to/file.html?key1=value1&key2=value2#fragment`, the function should... |
You can use the provided information to create a function that iterates over each dictionary in a list, extracts the values of its keys, and then creates a new dictionary with those values as keys and their corresponding counts as values. Then, you can loop over each dictionary in the list and update the new dictionary... | I'm working on a function that takes a dictionary as an argument. I want to extract the values of its keys, and then create a new dictionary with those values as keys and their corresponding counts as values. I want to do this for every dictionary in a list. Every time I do this, I end up with a list of dictionaries. I... | To achieve your goal, you can create a function that processes the list of dictionaries as follows:
1. Initialize an empty dictionary to hold the cumulative counts.
2. Iterate over each dictionary in the list.
3. For each dictionary, iterate over its values and update the cumulative counts in the result dictionary.
4.... | 48,184 | [
{
"from": "human",
"value": "I'm working on a function that takes a dictionary as an argument. I want to extract the values of its keys, and then create a new dictionary with those values as keys and their corresponding counts as values. I want to do this for every dictionary in a list. Every time I do this... |
To achieve this goal, you can use regular expressions to extract the phone number digits and then format them as a standardized phone number.
Here's how you can write the function in Python:
```python
import re
def standardize_phone_numbers(phone_numbers):
standardized_numbers = []
for phone_number in phone_... | Given a list of strings (phone numbers in various formats), write a Python function to standardize the phone numbers into a consistent format. The function should take the list of phone numbers as input and return a list of standardized phone numbers.
Your code should pass the following test case:
```python
phone_numb... | To standardize the phone numbers into a consistent format, we can create a function called `standardize_phone_numbers`. The function will remove any non-numeric characters from the input strings, ensure the phone numbers are in the correct international format, and add the country code if missing. We will also assume t... | 48,185 | [
{
"from": "human",
"value": "Given a list of strings (phone numbers in various formats), write a Python function to standardize the phone numbers into a consistent format. The function should take the list of phone numbers as input and return a list of standardized phone numbers.\n\nYour code should pass th... |
```python
def aggregate_dict(dicts):
aggregated = {}
for d in dicts:
for k, v in d.items():
if k not in aggregated:
aggregated[k] = []
aggregated[k].append(v)
return aggregated
```
The `aggregated` dictionary initially starts empty. The outer for loop iterate... | Write a Python function that takes a list of dictionaries as input and returns a single dictionary with aggregated values for each key. The dictionaries in the input list will have the same set of keys that may have different values for each dictionary. The function should group the values of each key and return a new ... | Certainly! Below is a Python function named `aggregate_dicts` that takes a list of dictionaries as input and returns a single dictionary with aggregated values for each key.
```python
def aggregate_dicts(dicts):
# Initialize an empty dictionary to store the aggregated values
aggregated = {}
# Iterate ... | 48,186 | [
{
"from": "human",
"value": "Write a Python function that takes a list of dictionaries as input and returns a single dictionary with aggregated values for each key. The dictionaries in the input list will have the same set of keys that may have different values for each dictionary. The function should group... |
To normalize a histogram, we need to divide each value in the list by the sum of all values in the list. We can achieve this by first calculating the sum of all values using the `sum()` function, and then dividing each value in the list by the sum. This normalized list will have values in the range [0, 1].
```python
d... | Design a Python function `normalize_histogram(histogram)` to normalize a list of numbers, represented as a histogram, by dividing each value by the sum of all values. This function should return a new list containing the normalized values without modifying the input list. | You can achieve normalization of a histogram by implementing a function that computes the sum of the histogram values and then divides each value by this sum. Here’s how you can implement this in Python:
```python
def normalize_histogram(histogram):
# Calculate the total sum of the histogram
total = sum(histog... | 48,187 | [
{
"from": "human",
"value": "Design a Python function `normalize_histogram(histogram)` to normalize a list of numbers, represented as a histogram, by dividing each value by the sum of all values. This function should return a new list containing the normalized values without modifying the input list."
},
... |
Here's how you can implement this in Python:
```python
import re
def extract_time_from_string(datetime_string):
pattern = r"(\w+) (\d+), (\d+) at (\d+):(\d+) (am|pm)"
match = re.search(pattern, datetime_string)
if match:
month = match.group(1)
day = match.group(2)
year = match.gro... | Write a Python function `extract_time_from_string(datetime_string)` that extracts the time from a given datetime string, formatted as "<month> <day>, <year> at <hour>:<minute> <am/pm>", such as "April 20, 2023 at 3:45 pm". The function should return the time as a string in 24-hour clock format ("<hour>:<minute>").
You... | To accomplish the task of extracting the time from a given datetime string and converting it into a 24-hour format, you can use the `datetime` module in Python. Below is the implementation of the `extract_time_from_string` function:
```python
from datetime import datetime
def extract_time_from_string(datetime_string)... | 48,188 | [
{
"from": "human",
"value": "Write a Python function `extract_time_from_string(datetime_string)` that extracts the time from a given datetime string, formatted as \"<month> <day>, <year> at <hour>:<minute> <am/pm>\", such as \"April 20, 2023 at 3:45 pm\". The function should return the time as a string in 2... |
Here's an example of how you might implement this function in Python:
```python
import json
def convert_images(input_string):
input_json = json.loads(input_string)
base64_images = input_json['images']
output_string = ''
for image in base64_images:
output_string += image + '\n\n'
return out... | Write a Python function to convert an input string representation of a list of base64-encoded images into a single base64-encoded string representation of a zip file containing the images.
The input string format should be:
```
{
"images": [
"base64:xxxxx",
"base64:yyyyy",
"base64:zzzzz",
…
]
}
``... | To create a function that converts a string representation of a list of base64-encoded images into a single base64-encoded string representation of a zip file containing those images, you will follow these steps:
1. Parse the input string to extract the base64-encoded images.
2. Convert the base64 strings into binary ... | 48,189 | [
{
"from": "human",
"value": "Write a Python function to convert an input string representation of a list of base64-encoded images into a single base64-encoded string representation of a zip file containing the images.\n\nThe input string format should be:\n\n```\n{\n \"images\": [\n \"base64:xxxxx\",\n ... |
Here is a function that checks whether the input type `T` is a generic type or a class:
```python
from typing import TypeVar, Generic
T = TypeVar("T")
def is_generic_class_or_type(T) -> bool:
"""
Returns True if the input is a generic type or a class, and False if it is not.
"""
return isinstance(T, ... | I want a function that returns True if the input is a generic type or a class, and False if it is not. This function takes a single argument, `T`, which is the type to be checked. | You can achieve this by creating a function that checks if the provided input is a subclass of `type`. In Python, types are instances of the `type` class, and classes are also objects of this type. Here's how you can define such a function:
```python
def is_generic_type_or_class(T):
return isinstance(T, type)
# E... | 48,190 | [
{
"from": "human",
"value": "I want a function that returns True if the input is a generic type or a class, and False if it is not. This function takes a single argument, `T`, which is the type to be checked."
},
{
"from": "gpt",
"value": "You can achieve this by creating a function that checks ... |
Here's how we can implement this:
```python
import re
class InvalidLogLineException(Exception):
pass
def parse_log_line(line):
pattern = r"^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{6})\s*(.*)$"
match = re.findall(pattern, line)
if match:
timestamp = match[0][0]
message = match[0][1]
... | Given a log file `example.log` that contains time-stamped messages, write a Python function `load_log_data(filepath)` to extract the timestamp and message from each line and return a list of dictionaries. The structure of each dictionary should be as follows:
```json
{
"timestamp": "2023-02-04T01:51:20.050566",
... | To achieve the desired functionality, we will implement a function `load_log_data(filepath)` that reads a log file line by line, extracts the timestamp and message, and returns a list of dictionaries containing this information. Additionally, we will create a custom exception to handle any lines that do not conform to ... | 48,191 | [
{
"from": "human",
"value": "Given a log file `example.log` that contains time-stamped messages, write a Python function `load_log_data(filepath)` to extract the timestamp and message from each line and return a list of dictionaries. The structure of each dictionary should be as follows:\n\n```json\n{\n ... |
Here is a Python function that implements this approach:
```python
def calculate_power_of_two(num: int):
"""
Calculates the power of two for a given integer. If the result exceeds the maximum
value of an integer, returns `None`.
"""
if num == 0:
return 0
elif num < 0:
return Non... | Write a Python function to calculate the power of two for a given integer. The function should handle cases where the input is negative, zero, or a power of two. If the result exceeds the maximum value of an integer, return `None`. The function should determine the appropriate bit width (8, 16, 32, or 64 bits) for the ... | Here's a Python function that implements the requirements you've described. The function calculates the power of two for a given integer input while considering various edge cases, including negative integers and zero. Additionally, it determines if the result exceeds the maximum allowable integer size based on the bit... | 48,192 | [
{
"from": "human",
"value": "Write a Python function to calculate the power of two for a given integer. The function should handle cases where the input is negative, zero, or a power of two. If the result exceeds the maximum value of an integer, return `None`. The function should determine the appropriate b... |
Here's how you can implement this function:
```python
def list_to_string_with_separator(items: list, sep: str = ', ') -> str:
result = []
for item in items:
if isinstance(item, str):
result.append(item)
else:
result.append(str(item))
return sep.join(result)
```
This... | Create a Python function that takes a list of any objects and returns a string representation of the list, where each element in the list is converted to its string representation, then concatenated together with intermediate separators. The separator should be specified as an optional argument with a default value of ... | Here is a Python function that meets the specified requirements and passes all the assertions:
```python
def list_to_string_with_separator(lst, sep=', '):
# Use str() for each element, keeping strings as they are
stringified_elements = [str(element) if not isinstance(element, str) else element for element in l... | 48,193 | [
{
"from": "human",
"value": "Create a Python function that takes a list of any objects and returns a string representation of the list, where each element in the list is converted to its string representation, then concatenated together with intermediate separators. The separator should be specified as an o... |
To validate the tuples in the input list, we need to check if each tuple has the correct format (three elements, year, month, and day) and if the date is valid. For example, we can check if the year is a positive integer, the month is an integer between 1 and 12, and the day is an integer between 1 and 31.
Here is a P... | Write a Python function that takes a list of tuples and returns a list of tuples. Each tuple in the input list has the format (year, month, day). The function should validate the data by checking if each tuple is in the correct format and if the date is valid. If any of the tuples are invalid, the function should raise... | To create a Python function that meets your requirements, we will use the following steps:
1. Validate the format of each tuple to ensure it contains three elements representing the year, month, and day.
2. Check if the year, month, and day are valid using the `datetime` module, which allows us to validate dates easil... | 48,194 | [
{
"from": "human",
"value": "Write a Python function that takes a list of tuples and returns a list of tuples. Each tuple in the input list has the format (year, month, day). The function should validate the data by checking if each tuple is in the correct format and if the date is valid. If any of the tupl... |
Here's a possible implementation of the function:
```python
def columnar_transposition_decrypt(ciphertext, key):
columns = [[] for _ in range(len(key))]
for i, char in enumerate(ciphertext):
columns[i % len(key)].append(char)
if not all(len(col) == len(columns[0]) for col in columns):
raise... | Write a Python function that performs columnar transposition decryption on a string. The input string is assumed to be a columnar transposition cipher composed of columns of equal length, separated by single spaces. The function should return the original message after performing the decryption. The function should rai... | To implement a function that performs columnar transposition decryption in Python, we need to first clarify how the decryption process works. Given a ciphertext organized into columns based on a key, we need to rearrange the characters back into the original order.
The steps involved include:
1. Validating the input ... | 48,195 | [
{
"from": "human",
"value": "Write a Python function that performs columnar transposition decryption on a string. The input string is assumed to be a columnar transposition cipher composed of columns of equal length, separated by single spaces. The function should return the original message after performin... |
Here's how you could do it:
```python
import asyncio
import inspect
class MyClass:
def __await__(self):
yield from (1, 2, 3)
async def coroutine_function():
instance = MyClass()
await instance
print(inspect.iscoroutinefunction(coroutine_function)) # True
```
The class `MyClass` defines a custo... | Create a Python function that overrides the `__await__` method of a class to make it asynchronously awaitable. Then, demonstrate that the class instance can be awaited using `await` or `await_for` and that the instance has inherited the method override. | To create a Python class that overrides the `__await__` method, we can define an asynchronous generator or an asynchronous iterable that yields a single item. The overridden method allows the instance of the class to be awaited.
Here's an example demonstrating this:
```python
import asyncio
class AwaitableClass:
... | 48,196 | [
{
"from": "human",
"value": "Create a Python function that overrides the `__await__` method of a class to make it asynchronously awaitable. Then, demonstrate that the class instance can be awaited using `await` or `await_for` and that the instance has inherited the method override."
},
{
"from": "gp... |
To convert a dictionary with string values to a dictionary with boolean values, the function should follow these steps:
1. Check if the provided value is a dictionary: Use `isinstance` to verify the type of the input value.
2. Process each key-value pair in the dictionary: Iterate through the items of the dictionary u... | Design a Python function to transform a dictionary with string values into a different dictionary with boolean values. The function should properly handle all possible input values, such as `'True'`, `'true'`, `'1'` and `1` for a `True` value, similarly for `False` values. Return `None` if the input is not a dictionary... | You can implement the `convert_dict_values_to_bool` function as follows. This function will check if the input is a dictionary and then transform each value according to the specified rules for boolean conversion:
```python
def convert_dict_values_to_bool(input_dict):
if not isinstance(input_dict, dict):
r... | 48,197 | [
{
"from": "human",
"value": "Design a Python function to transform a dictionary with string values into a different dictionary with boolean values. The function should properly handle all possible input values, such as `'True'`, `'true'`, `'1'` and `1` for a `True` value, similarly for `False` values. Retur... |
Here's a possible implementation:
```python
def is_jpeg_file(file_path):
extension = file_path.rsplit('.', 1)[-1].lower()
if extension not in ('jpg', 'jpeg'):
return False
with open(file_path, 'rb') as f:
contents = f.read(3)
if contents != b'\xff\xd8\xff':
return False
... | I need a Python function that takes a file path as input and returns a boolean indicating whether the file is an image in JPEG format. I don't want to use any external libraries or dependencies. The function must detect the file type based on the file name extension and the file contents.
Your code should pass the fol... | You can create a Python function that checks both the file extension and the contents of the file to determine if it is a JPEG image. JPEG files usually have either a `.jpg` or `.jpeg` extension, and their content should match specific byte signatures.
Below is a sample implementation of such a function:
```python
de... | 48,198 | [
{
"from": "human",
"value": "I need a Python function that takes a file path as input and returns a boolean indicating whether the file is an image in JPEG format. I don't want to use any external libraries or dependencies. The function must detect the file type based on the file name extension and the file... |
To implement a custom learning rate scheduler, you need to define a function that takes two arguments: `epoch` and `num_epochs`. The `epoch` argument represents the current epoch number, while the `num_epochs` argument represents the total number of epochs for the training process. The function should return the learni... | Write a Python function to implement a custom learning rate scheduler for a neural network training process. The scheduler should have the following properties:
- The learning rate should decrease linearly from its initial value at the beginning of each epoch to zero at the end of the epoch.
- The learning rate should... | Here's a Python function that implements the custom learning rate scheduler as described:
```python
def custom_lr_scheduler(epoch, num_epochs):
"""
A custom learning rate scheduler.
Args:
epoch (int): The current epoch number.
num_epochs (int): The total number of epochs.
Returns:
... | 48,199 | [
{
"from": "human",
"value": "Write a Python function to implement a custom learning rate scheduler for a neural network training process. The scheduler should have the following properties:\n\n- The learning rate should decrease linearly from its initial value at the beginning of each epoch to zero at the e... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.