response_seed stringlengths 53 5.17k | instruction_seed stringlengths 29 4.02k | response stringlengths 16 8.81k | __original_row_idx int64 0 50k |
|---|---|---|---|
Here is a Python function that implements `cached_gen` using a `deque` and the `yield` statement:
```python
from collections import deque
def cached_gen(func, cache_size):
"""
Returns a generator that takes a function `func` and a cache size `cache_size`.
The generator caches the current output of `func` ... | Write a Python function `cached_gen` that takes a function and a cache size as inputs. The function should return a generator that caches the current output of the function for the given cache size. The cache should be implemented using a list to store the previous outputs of the function. Whenever the cache is full, t... | Here’s a Python implementation of the `cached_gen` function that meets the specified requirements:
```python
def cached_gen(func, cache_size):
"""
A generator that caches outputs of a function with a specified cache size.
It prevents returning values that have already been seen or are in the cache.
Pa... | 44,200 |
Here is a possible solution:
```python
def pad_buffer(lst, n):
lst.reverse() # Reverse the list
lst_len = len(lst)
if lst_len % n != 0: # Check if the length is not a multiple of n
lst.extend([0] * (n - (lst_len % n))) # Append the required number of zeros
return lst
```
The `pad_buffer` fu... | Write a Python function called `pad_buffer` that takes two parameters: a list of integers and a positive integer `n`. The function should reverse the list of integers (if not already in reverse order) and then extend it with zeroes (0s) until the length of the list is a multiple of `n`.
For example, if the list is `[1... | Certainly! Below is a Python function named `pad_buffer` that fulfills the requirements you've specified. It takes a list of integers and a positive integer `n`, reverses the list if it's not already in reverse order, and pads it with zeros until its length is a multiple of `n`.
```python
def pad_buffer(int_list, n):
... | 44,201 |
Here's an implementation of the `convert_and_sum_strings` function:
```python
def convert_and_sum_strings(numbers):
if not isinstance(numbers, list):
raise TypeError("Input must be a list")
total = 0
for number in numbers:
try:
total += float(number)
except ValueError:
... | Develop a Python function `convert_and_sum_strings(numbers)` that takes a list of numbers represented as strings and returns their sum as a float. If any element cannot be converted to a float, the function should ignore that element and continue with the next. If all the elements fail to convert, the function should r... | You can create the function `convert_and_sum_strings(numbers)` as described using Python's built-in error handling and list comprehensions. Below is the implementation:
```python
def convert_and_sum_strings(numbers):
total = 0.0
valid_count = 0 # Count valid conversions
for number in numbers:
... | 44,202 |
Here's how you can implement the function in Python:
```python
import pickle
def dict_serialize(dict_to_serialize, file_path_to_write, file_path_to_read):
if dict_to_serialize is None and file_path_to_read is not None:
with open(file_path_to_read, 'rb') as f:
dict_to_serialize = pickle.load(f)... | Create a Python function to serialize a dictionary of objects into and from a file. The function should take three arguments: the dictionary to serialize, the file path to write to, and the file path to read from. If the dictionary is None and the file path to read from is not None, the function should load the diction... | Certainly! Below is a Python function that serializes a dictionary of objects to a file using the `pickle` module and also supports deserialization. If the dictionary is `None`, it attempts to read from the specified file path instead.
Here's the implementation:
```python
import pickle
from typing import Dict, Any, O... | 44,203 |
To develop a Python function `tuple_to_string` that takes a tuple as input and returns a string representation with each element separated by a comma, you can follow these steps:
1. Define a recursive function `tuple_to_string_helper` that takes a tuple and a comma-separated string as arguments.
2. Inside the function... | Develop a Python function `tuple_to_string` that takes a tuple as input and returns a string representation with each element separated by a comma. If the tuple contains nested tuples, the function should recursively call itself to flatten the tuple.
Here is an example of how the function should work:
```python
tuple... | You can create the `tuple_to_string` function that recursively handles nested tuples by checking the type of each element in the input tuple. If an element is a tuple, the function can call itself to process that element. Otherwise, it can simply convert the element to a string. Finally, you can join all the processed ... | 44,204 |
To determine if a number is even, odd, zero, not a number, or a floating point number, you can use the following rules:
- If a number is even, it is divisible by 2 with no remainder.
- If a number is odd, it is not even and has a remainder of 1 when divided by 2.
- If a number is zero, it is neither even nor odd, but i... | Write a function to determine whether a number is even or odd. If the number is even, return "even". If the number is odd, return "odd". If the number is zero, return "zero". If the number is not a number, return "not a number". If the number is a floating point number, return "floating point". | Certainly! Below is a Python function that checks if a number is even, odd, zero, a non-numeric value, or a floating point number, and returns the corresponding string:
```python
def check_number(n):
# Check if the input is a number (int or float)
if isinstance(n, (int, float)):
if isinstance(n, float)... | 44,205 |
Here's how you can implement the `serialize_to_json` function:
```python
import json
class MyClass:
def to_json(self):
return {"key1": "value1", "key2": "value2"}
def serialize_to_json(obj):
if isinstance(obj, MyClass):
return json.dumps(obj.to_json())
raise TypeError("obj is not an insta... | I have a class `MyClass` that has a method `to_json` that returns a JSON representation of the current object. Implement a function `serialize_to_json` that takes an object of type `MyClass` as an argument and returns the JSON representation as a string.
Your code should pass the following test case:
```python
obj = M... | To implement the `serialize_to_json` function that takes an object of type `MyClass` and returns its JSON representation as a string, we can utilize Python's `json` module along with the `to_json` method of `MyClass`. Below is the implementation:
```python
import json
class MyClass:
def to_json(self):
# E... | 44,206 |
To solve this problem, let's follow these steps:
1. Load the file contents: Use `open` with the `r` (read) mode to open the file. Handle any exceptions that may be raised during file opening.
2. Transform the file contents into a list of words: Use `read` to read the entire file content as a string. Then use `split()`... | Write a Python function that takes a file path, loads the contents of the file as a string, and returns a list of all words that appear more than once in the text. Make sure to handle any exceptions that may occur during file loading. | Certainly! Below is a Python function that takes a file path as an argument, reads the contents of the file, and returns a list of words that appear more than once in the text. It also handles exceptions that may occur during file loading.
```python
def find_repeated_words(file_path):
"""Loads a file and returns a... | 44,207 |
```python
def is_collision(shape_1, shape_2):
x1, y1, r1 = shape_1 # Coordinates of the first circle
x2, y2, r2 = shape_2 # Coordinates of the second circle
distance = ((x2 - x1)**2 + (y2 - y1)**2) ** 0.5
if distance >= r1 + r2:
return False
else:
return True
``` | Write a Python function to detect whether two geometric shapes are colliding or not, given their coordinates in the 2D plane. Build the necessary data structure based on the coordinate pairs to represent the shape. Use boolean algebra to determine the collision state. Apply your function to two circles, one with center... | To determine whether two geometric shapes are colliding, we can represent the geometric shapes as classes. In this case, we'll represent circles and use their centers and radii to check for collisions.
The collision detection between two circles can be done using the following condition:
1. Calculate the distance \(d\... | 44,208 |
Here is the implementation of the function:
```python
def get_valid_vectors(vectors):
valid_1 = [is_valid(x) for x in vectors]
valid_2 = [is_valid_2(x) for x in vectors]
valid_mask = [v1 and v2 for v1, v2 in zip(valid_1, valid_2)]
valid_indices = [i for i, v in enumerate(valid_mask) if v]
return ... | Given the following functions:
```python
def is_valid(x):
"""Checks if x is a valid vector."""
# ...
def is_valid_2(x):
"""Checks if x is a valid vector."""
# ...
```
Write a Python function to return a list of valid vectors (satisfying the requirements of both `is_valid` and `is_valid_2`) from a pro... | Certainly! You can create a function that takes a list of vectors and returns only those that satisfy the conditions set by both `is_valid` and `is_valid_2`. Below is an example implementation assuming that `is_valid` and `is_valid_2` are already defined:
```python
def get_valid_vectors(vectors):
"""Returns a list... | 44,209 |
Here's how you can implement this:
```python
def retrieve_attribute_values(obj, attributes):
values = []
for attribute in attributes:
if hasattr(obj, attribute):
values.append(getattr(obj, attribute))
else:
values.append("null")
return values
```
This implementation... | Given a dictionary with keys that are object attributes, write a Python function to retrieve the values of these attributes from an object and return them in a list. Additionally, if the attribute does not exist, the function should return a special value (e.g., "null") instead of throwing an AttributeError. | You can accomplish this by defining a Python function that takes an object and a dictionary of attribute names. The function retrieves the values of these attributes from the object and handles the case where an attribute doesn't exist gracefully. Below is a sample implementation of such a function:
```python
def retr... | 44,210 |
Here's the Python code for the `reverse_list_chunks` function:
```python
def reverse_list_chunks(lst, chunk_size):
reversed_lst = []
for i in range(0, len(lst), chunk_size):
chunk = lst[i:i+chunk_size]
reversed_chunk = chunk[::-1]
reversed_lst.extend(reversed_chunk)
return reversed_... | Write a Python function to reverse a list of integers in chunks of a given size, i.e., the first chunk is reversed, the second chunk is reversed, and so on, and the last chunk may be partially reversed. For example, given the list [1, 2, 3, 4, 5, 6, 7, 8, 9] and the chunk size 3, the reversed list would be [3, 2, 1, 6,... | Certainly! Below is a Python function that takes a list of integers and a chunk size, then reverses the list in chunks of that size:
```python
def reverse_in_chunks(lst, chunk_size):
reversed_list = []
for i in range(0, len(lst), chunk_size):
# Get the current chunk
chunk = lst[i:i + chunk_size... | 44,211 |
Here's how you could do it:
```python
def complete_file_path(partial_path, extension):
if partial_path[-1].endswith(extension):
return '/'.join(partial_path)
else:
return '/'.join(partial_path[:-1] + [partial_path[-1] + extension])
```
This function checks if the last string in the partial pat... | Develop a Python function to complete a file path from a partial path. The partial path is provided as a list of strings, where each string corresponds to a directory or file name. The function should return a completed file path as a string.
If the last string in the partial path represents a file name, return the co... | Certainly! Below is a Python function that accomplishes this task. This function, `complete_file_path`, takes a list of strings that represent directories and files, along with a required file extension as arguments. It constructs the complete file path based on whether the last item in the list represents a file or a ... | 44,212 |
To rotate a 2D matrix in-place by 90 degrees clockwise, we can use the following algorithm:
1. Transpose the matrix by swapping its rows and columns.
2. Reverse each row in the matrix.
Here is the implementation in Python:
```python
def rotate_matrix_90_cw(matrix):
n = len(matrix)
for i in range(n):
f... | Write a Python function to rotate a matrix in-place by 90 degrees clockwise.
Your code should pass the following test case:
```python
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
expected_output = [[7, 4, 1], [8, 5, 2], [9, 6, 3]]
rotate_matrix_90_cw(matrix)
assert matrix == expected_output
``` | To rotate a matrix in-place by 90 degrees clockwise, we can follow a two-step process: first, we transpose the matrix, and then we reverse each row.
Here's how we can implement the function `rotate_matrix_90_cw` in Python:
```python
def rotate_matrix_90_cw(matrix):
n = len(matrix)
# Step 1: Transpose the... | 44,213 |
In the context of symmetric cryptography, the ECB mode of operation for AES-128 involves using a 16-byte key to encrypt a single block of plaintext into a single block of ciphertext.
To decrypt the ciphertext using the ECB mode of operation for AES-128, we need to perform the following steps:
1. Decode the `encrypted... | Write a Python function to decrypt a ciphertext encrypted using the ECB mode of operation for AES-128. The function takes two arguments: a ciphertext `encrypted_msg` and a 16-byte key `key`. The function should decrypt the ciphertext and return the plaintext message as a string. Utilize the `AES.new()` method for AES e... | To decrypt a ciphertext that has been encrypted using the AES algorithm in ECB mode, you can use the `pycryptodome` library, which provides a straightforward interface for working with cryptographic operations in Python.
Here's the implementation of the `decrypt_aes_ecb` function:
```python
from Crypto.Cipher import ... | 44,214 |
In Python, a function `get_asset_names` accepting two arguments, an HTTP client instance and the API endpoint URL, can be implemented as follows:
1. The function will use the client to make an HTTP GET request to the specified endpoint.
2. The function will parse the JSON response received from the API.
3. The functio... | Write a Python function named "get_asset_names" to retrieve the asset names from the "assets" endpoint of a RESTful API service. The function should accept two arguments: an HTTP client instance and the API endpoint URL. The function should send an HTTP GET request to the specified endpoint and return a list of asset n... | To implement the `get_asset_names` function as you described, we will use the `requests` library, which provides an easy way to make HTTP requests in Python. The function will take an HTTP client instance and an API endpoint URL, send a GET request to that URL, and parse the response to extract the asset names.
Here's... | 44,215 |
To implement the function, we can use the following steps:
1. Extract the cookie value from the `cookie` string.
2. Decode the value from base64 to bytes.
3. Deserialize the bytes using the `pickle` module.
4. Compress the value using `zlib` compression.
5. Return the compressed value in JSON format.
Here is a Python... | Create a Python function to handle HTTP cookies. The function should receive a cookie and return the cookie value in JSON format. Here is an example of the function signature:
```python
def handle_cookie(cookie: str) -> str:
...
```
The function should do the following:
1. Extract the cookie value from the `cook... | To create a Python function that handles HTTP cookies as specified, we will follow the steps outlined in your request. We will need to:
1. Extract the cookie value from the provided cookie string (assumed to be in the format "key=value").
2. Decode the value from base64.
3. Deserialize it using the `pickle` module.
4.... | 44,216 |
Here's how you could do it:
```python
def read_and_write_filtered_text(file_path, output_file_path, filter_function):
try:
with open(file_path, 'r') as f, open(output_file_path, 'w') as g:
text = f.read()
filtered_text = filter_function(text)
g.write(filtered_text)
e... | Write a Python function that reads text from a file `f`, applies a filter to it, and then writes the output to another file `g`. If the function encounters any problems, it should raise an error and gracefully close both files. | Certainly! Below is a Python function that reads text from a file `f`, applies a simple filter to the text, and then writes the processed output to another file `g`. The function handles potential errors gracefully and ensures that both files are correctly closed, whether an error occurs or not.
Here's an example impl... | 44,217 |
To achieve the desired functionality, you can define a function that takes in the grid size, object type, and object arguments as parameters. The function will create a two-dimensional grid of the specified size and fill it with objects of the given type. Each object will be placed in a sequential rectangular pattern, ... | Create a Python function to create a two-dimensional grid of fixed size and fill it with objects of a given type. The objects should be placed sequentially in a rectangular pattern, starting from the upper left corner. The function should take three arguments: `grid_size`, `object_type`, and `object_arguments`. The `ob... | You can create a Python function to generate a two-dimensional grid filled with instances of a specified object type, using the provided arguments to customize each instance based on its position in the grid. The function will take in three parameters: `grid_size`, `object_type`, and `object_arguments`.
Here's a possi... | 44,218 |
You can create a Python function `convert_directional_string(directional_string, start_point=(0,0))` to convert a directional string into a list of coordinate pairs. The function should handle the following directions:
- 'U' for up, 'D' for down, 'R' for right, and 'L' for left.
- 'F' for forward, 'B' for backward, 'C... | Write a Python function `convert_directional_string(directional_string, start_point=(0,0))` to convert a directional string into a list of coordinate pairs. The directional string consists of a sequence of directions and distances separated by space, and each direction is represented by one of the following characters:... | To implement the `convert_directional_string` function, we need to parse the directional string and process each command. We'll translate the directions into movements on a 2D grid, updating the position accordingly.
Here's how we can implement this function:
```python
def convert_directional_string(directional_stri... | 44,219 |
The key steps in implementing the `add_list_or_tuple_element` function are as follows:
1. Validate the type of the first argument using the `isinstance` function, and raise an exception if the type is not `list` or `tuple`.
2. Use the `append` method of the `list` class to add an element to the end of a list.
3. Use t... | Create a Python function named `add_list_or_tuple_element` that adds an element to the end of a list or tuple. The function should accept a Python object of type `list` or `tuple` and an element of any type, and append the element to the end of the list or tuple. Additionally, the function should validate that the firs... | Here is a Python function named `add_list_or_tuple_element` that fulfills your requirements. The function checks if the first argument is a list or tuple, and if not, it raises a `TypeError`. If the first argument is valid, it appends the provided element to the end of the list or tuple (returning a new tuple since tup... | 44,220 |
To find the index of the first largest match between two strings, we can use a brute-force approach. We start by iterating over all possible substrings of the second string and find the largest match with the first string. Once we find a match, we return its index.
To efficiently find the largest match, we can use a s... | Write a Python function to find the index of the first occurrence of the largest match between two strings, where the first string is a substring of the second string. The function should return `-1` if no match is found.
For example, if the first string is `"abc"` and the second string is `"edcba1"`, then the functio... | To find the index of the first occurrence of the largest match between two strings, we can create a function that iterates through the second string and checks for matches with the first string. If a match is found, we can store its index and return it. If no match is found, we will return `-1`.
Here is a Python funct... | 44,221 |
Here's a possible implementation of the `calculate_zcdp_budget` function:
```python
from math import exp
def calculate_zcdp_budget(eps: float, n: int) -> float:
rho = exp(eps) - 1
zcdp_budget = rho ** (n / 2)
return zcdp_budget
``` | Write a Python function to calculate the zCDP privacy budget of a range query over a dataset, given the privacy budget of each individual record in the dataset and the number of records. Assume the function inputs are `eps` (privacy budget of each record) and `n` (number of records) and the output should be the zCDP pr... | To calculate the zCDP (zero-concentrated differential privacy) privacy budget of a range query over a dataset, you can use the formula derived from the composition of the individual privacy budgets. The zCDP budget is calculated using the exponential function in the form of \((e^{\epsilon} - 1)^{n/2}\), where \(\epsilo... | 44,222 |
```python
def get_attr_from_tree(tree, attr_names):
if not tree or not attr_names:
return None
attr_name = attr_names[0]
if len(attr_names) == 1:
return tree.get(attr_name, None)
subtree = tree.get(attr_name)
if isinstance(subtree, dict):
return get_attr_from_tree(subtree... | Write a Python function `get_attr_from_tree` that recursively finds an attribute value based on a tree of attribute names. The function should take two arguments: `tree` (a dictionary representing a tree of attribute names), and `attr_names` (a list of attribute names). The function should return the value of the speci... | To create a function that recursively traverses a tree (in the form of a nested dictionary) to find the value associated with a list of attribute names, you can follow the structure outlined below. The function will take into account that the tree can contain nested dictionaries and lists, and return `None` if an attri... | 44,223 |
Here is a Python function that implements this approach:
```python
def split_by_chars(s, chars):
"""Splits a string `s` by characters in `chars`.
Examples:
>>> split_by_chars('a-b-c', '-')
['a', 'b', 'c']
>>> split_by_chars('a_b_c', '_')
['a', 'b', 'c']
>>> split_by_chars('a b c', ' ')
... | Write a Python function `split_by_chars` that takes two strings `s` and `chars`, and splits `s` by characters in `chars`. The function should return a list of strings.
For example, `split_by_chars('a-b-c', '-')` should return `['a', 'b', 'c']`.
Write a function docstring that gives examples of how to use the function... | Here’s how you can implement the `split_by_chars` function in Python, along with a detailed docstring that includes examples and assertions for testing its correctness.
```python
def split_by_chars(s, chars):
"""
Splits the string `s` by any of the characters specified in `chars`.
Args:
s (str): The s... | 44,224 |
Here is the implementation of the function `save_results`:
```python
import csv
import json
def save_results(results: dict, model_name: str, file_format: str) -> bool:
if file_format == "csv":
with open(f"{model_name}_results.csv", "w", newline="") as csvfile:
writer = csv.writer(csvfile)
... | Write a Python function `save_results` that saves model results to disk. The function should take the following arguments:
- `results`: A dictionary of model results with keys 'val_loss' and 'val_acc', representing the validation loss and validation accuracy, respectively.
- `model_name`: A string representing the nam... | Here is a Python function `save_results` that meets your specifications. This function takes in model results, the model name, and the desired file format, and saves the results in the specified format.
```python
import pandas as pd
import json
import os
def save_results(results, model_name, file_format):
# Valid... | 44,225 |
Here is the implementation of the `check_database_feasibility` function:
```python
def check_database_feasibility(my_db):
"""
Function to check database feasibility.
Args:
my_db: A database object to check.
Returns:
A boolean indicating whether the database is feasible.
"""
if... | Define a Python function `check_database_feasibility` that takes a database object `my_db` and checks if the database is feasible. The function should return `True` if the database is feasible, and `False` otherwise. The function should raise a `TypeError` if the input is not a `dict` or a `list`.
The database is cons... | Here's a Python function `check_database_feasibility` that checks the feasibility of a database object as per the provided criteria:
```python
def check_database_feasibility(my_db):
if isinstance(my_db, dict):
# Check if all keys are strings and values are either int or None
for key, value in my_db... | 44,226 |
```python
import re
def validate_uuids(uuids):
uuid_pattern = r'^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$'
valid_uuids = [re.findall(uuid_pattern, uuid.lower()) for uuid in uuids]
return [True if valid_uuid else False for valid_uuid in valid_uuids]
```
You can write the following test... | I'm writing a Python function to validate a set of hex strings that are supposed to represent UUIDs. The function should take a list of hex strings as input and return a list of boolean values where `True` means the input is a valid UUID and `False` means it's not. Here are the criteria for a valid UUID:
- The string ... | Sure! Below is a Python function `validate_uuids` that checks whether a list of hex strings represents valid UUIDs according to your requirements. Additionally, I've included a test function `test_validate_uuids` to verify the correctness of the implementation.
```python
import re
def validate_uuids(hex_strings):
... | 44,227 |
To write a function that filters a list of dictionaries based on a specific key and value, you can use the built-in Python `filter` function. This function takes a function that returns a boolean value and applies it to each element in the list. The function you pass should return `True` if the element matches the give... | Write a Python function that takes in a list of dictionaries `data` and a string `key` as inputs. The function should return a list of dictionaries where the value of the element with the given `key` matches the given value. | Certainly! Below is a Python function that takes in a list of dictionaries and a string representing a key. The function will filter and return a new list containing only the dictionaries where the value associated with the specified key matches a given value.
However, your original request does not specify what the v... | 44,228 |
To asynchronously iterate over a collection, we will need to use the `async` and `await` keywords. This allows us to iterate over the collection in an asynchronous manner, which is useful when we want to perform multiple operations in parallel.
To handle any exceptions that may occur during the iteration, we can use t... | Develop a Python function to asynchronously iterate over all items in a collection, where the collection can be a list, a tuple, a set, a dictionary, or any other object that has an `__iter__` method. The function should apply some operation to each item in the collection and handle any exceptions that may occur during... | To create an asynchronous iterator function in Python that can handle various collection types (like lists, tuples, sets, and dictionaries), we can use `asyncio`. The function will iterate over the items, apply a given asynchronous operation to each item, and handle exceptions gracefully. Below is a sample implementati... | 44,229 |
To compare two tensors of arbitrary shape and type, you can use the `numpy.array_equal` function from the `numpy` package. This function takes two tensors as arguments and returns `True` if they are equal, `False` if they are not, and raises an exception if the tensors cannot be compared.
Here is an example implementa... | Write a Python function `tensor_eq` that compares two tensors of arbitrary shape and type. The function should support tensors with any dimension and any data type. The function should return `True` if the tensors are equal, and `False` if they are not. The function should raise an exception if the tensors cannot be co... | To compare two tensors of arbitrary shape and type in Python, we can use the `numpy` library, which provides a powerful array interface that supports n-dimensional arrays (also known as tensors). The `numpy.array_equal` function allows us to compare two arrays element-wise, accounting for their shapes and types.
Below... | 44,230 |
Here is a Python function that converts a dictionary to JSON while ensuring consistent results:
```python
import json
def dict_to_json_sorted(dictionary: dict) -> str:
return json.dumps(dictionary, sort_keys=True)
``` | Implement a Python function that takes a dictionary as an argument and returns a JSON string that represents the input dictionary. The function should support sorting keys alphabetically to ensure consistent results. | To implement a function that takes a dictionary and returns a JSON string with sorted keys, you can use the `json` module available in Python. The `json.dumps()` method allows you to convert a Python object (like a dictionary) into a JSON string, and it has an option to sort the keys.
Here's how you can define this fu... | 44,231 |
To generate a random integer array, we can utilize the Python standard library `random` module. Specifically, we can use the `random.randint(a, b)` function to generate a random integer between `a` and `b` (inclusive). Since the range for each element is `0` to `100 * n - 1`, we can use this function to generate each e... | Write a Python function to generate a random integer array of size n where where each element is within the range of [0, 100 * n). | You can generate a random integer array of size `n` with elements in the range of `[0, 100 * n)` using the `random` module in Python. Here’s a function that accomplishes this:
```python
import random
def generate_random_array(n):
"""Generate a random integer array of size n with each element in the range [0, 100*... | 44,232 |
To implement the function `compute_pmf` that computes the probability mass function (PMF) of the sum of two random variables `x` and `y`, you can follow these steps:
1. Enumerate all possible values of the sum of `x` and `y` by iterating over the possible values of `x` and `y`.
2. Calculate the probability of each pos... | Implement a Python function `compute_pmf` that takes two arguments, `x` and `y`, and returns a tuple `(p, mean)` where `p` is the probability mass function of the sum of `x` and `y` and `mean` is the mean of the distribution. The PMF should be represented as a dictionary where the keys are the possible values of the su... | To implement the `compute_pmf` function that computes the probability mass function (PMF) of the sum of two discrete random variables `x` and `y`, we can follow these steps:
1. Calculate the possible sums of each combination of values in `x` and `y`.
2. Count the occurrences of each possible sum.
3. Normalize these co... | 44,233 |
Here's the code in Python:
```python
def remove_quotes_and_brackets(strings):
cleaned_strings = []
for string in strings:
cleaned_string = string.strip().replace('"', '').replace("'", '').replace('[', '').replace(']', '')
cleaned_string = cleaned_string.strip()
cleaned_strings.append(cl... | Write a Python function to remove quotation marks and brackets surrounding strings in a list. For example:
* `['"hello"', '[world]', 'goodbye']` becomes `['hello', 'world', 'goodbye']`.
* `['"hello"', '["world"]', '[goodbye]']` becomes `['hello', 'world', 'goodbye']`.
Make sure to trim any leading and trailing whites... | You can achieve this by defining a function that iterates through the list and processes each string to remove the quotation marks and brackets. Here’s a Python function that implements this:
```python
def clean_strings(input_list):
cleaned_list = []
for item in input_list:
# Remove quotes and brackets... | 44,234 |
To design a Python function that takes a singly linked list and returns the sum of all positive nodes, we can define the following steps:
1. Define a `Node` class with value and next attributes.
2. Define a `LinkedList` class with a head attribute and a `print_list` method to print the contents of the list.
3. Define ... | Design a Python function that takes a singly linked list and returns the sum of all positive nodes. The function should traverse the list and check each node's value. If the value is less than zero, the function should stop the traversal and return the sum. | To create a function that sums the positive values of nodes in a singly linked list and stops when it encounters a negative value, we first need to define the structure of the linked list's nodes. Each node in a singly linked list typically contains a value and a reference to the next node.
Here’s how we can do this i... | 44,235 |
Here's how you can implement this function:
```python
import datetime
import random
def generate_random_datetime_list(count=10, start=None, end=None):
if start is None:
start = datetime.datetime(1970, 1, 1, 0, 0, 0)
if end is None:
end = datetime.datetime.now()
difference = (end - start).... | Write a Python function `generate_random_datetime_list(count=10, start=None, end=None)` to generate a list of random datetime objects. The `count` argument specifies the number of datetime objects to generate. The `start` and `end` arguments are optional to specify the inclusive range of datetime objects to generate. I... | You can create the `generate_random_datetime_list` function using the `random` module along with `datetime` to generate random datetime objects. Below is a sample implementation:
```python
import random
from datetime import datetime, timedelta
def generate_random_datetime_list(count=10, start=None, end=None):
# S... | 44,236 |
We can develop a Python function named `filter_for_image_files` that filters a list of file paths to only include image files by leveraging regular expressions and the `re` module. Regular expressions provide powerful pattern matching capabilities. We can use the `re.compile` function to compile a regular expression pa... | Develop a Python function named `filter_for_image_files` that filters a list of file paths to only include image files. The function should return a new list containing only the file paths that end in ".jpg", ".jpeg", ".png", or ".bmp". It should also handle cases where the file path does not have an extension, and not... | You can create a function named `filter_for_image_files` that filters a list of file paths to include only those that end with the specified image file extensions. You can do this by checking if the file path ends with any of the allowed extensions. Here's how you can implement this function:
```python
def filter_for_... | 44,237 |
To implement a natural sorting function in Python, we can use the `re` module to extract the numeric portions of the strings and then sort the results using `sorted` and `key`. The `key` argument of `sorted` allows us to specify a function that determines the sorting criterion for the input objects. In this case, the k... | Write a Python function `natural_sort` that takes a list of strings as an argument and returns a sorted copy of the list with the strings sorted according to their natural order. The function should utilize natural sorting, which is a method of sorting strings based on their lexicographical order but considering the nu... | To achieve natural sorting of a list of strings in Python, you can utilize the `re` module to create a custom sorting key that separates the strings into numeric and non-numeric parts. Here’s how you can implement the `natural_sort` function:
```python
import re
def natural_key(s):
"""Generate a key for natural s... | 44,238 |
Checking if a number is a multiple of 9 can be done by summing the digits of the number and checking if the total is a multiple of 9. We can leverage the properties of modulo arithmetic to achieve this.
To validate the input type, we can use the `isinstance()` built-in function. This allows us to determine if the inpu... | Create a Python function to check if a given number is a multiple of 9. The function should accept an integer as input and return a boolean value. Additionally, validate the input type and raise an error if the input is not an integer. If the number is out of the range [0, 1000000000], raise a ValueError. | Certainly! Below is a Python function that checks if a given number is a multiple of 9, along with input validation as specified:
```python
def is_multiple_of_9(number):
# Check if the input is an integer
if not isinstance(number, int):
raise TypeError("Input must be an integer.")
# Check if t... | 44,239 |
You can create a Python function that takes a string as input and uses the `re` module's `findall()` method to find all words matching a specific pattern. The pattern should define a specific sequence of characters, where each character can be either a letter or a digit.
Here's how you could do it:
```python
import r... | Create a Python function that takes a string as input and returns a list of words that contain a certain pattern. The function should use Python's `re` module to parse the input string and identify words that match a specific pattern. The pattern should define a specific sequence of characters, where each character can... | You can accomplish the task of finding words that match a specific pattern using Python's `re` module. Below is the implementation of the `find_words_with_pattern` function along with the provided test case. This function will search for words that match the specified pattern in the input string and return them in a li... | 44,240 |
To fetch log messages recorded after a certain date from a SQLite database, you can use Python's built-in SQLite library, `sqlite3`. The database should be created first, and a table should be created with the defined schema.
To retrieve the log messages, you need to write a SQL query that selects all the records from... | I have a SQLite database file called `database.db` that contains a table called `logs` with the following schema:
```
CREATE TABLE logs (
id INTEGER PRIMARY KEY,
timestamp INTEGER,
message TEXT
);
```
Write a Python function `fetch_logs_over_date(db_path, date)` that retrieves all the log messages from the `log... | To achieve this, you can use the `sqlite3` module in Python to interact with the SQLite database. You'll need to convert the `datetime` object to a timestamp that can be used in the SQL query since your logs table schema stores timestamps as integers.
Here's a Python function that implements the requirements you speci... | 44,241 |
Here is a Python function that implements this approach:
```python
def find_file_size(tree, path):
"""
Finds the size of a file in a suffix tree.
Args:
tree (dict): A suffix tree root node.
path (str): The path to the file.
Returns:
int: The size of the file, or -1 if the file i... | Design a Python function that takes a suffix tree root node and a string path to a file, and returns the size of the file. The suffix tree root is a dictionary with keys representing alphabet paths, e.g., `{'a': {}}` represents a file `a` with no content, `{'a': {'b': {}}}` represents a file `ab` with no content, `{'a'... | To design the required function that traverses a suffix tree represented as a nested dictionary structure and retrieves the size of a file based on the given path, we can follow these steps:
1. Start at the root of the suffix tree.
2. For each character in the string path, check if the character exists as a key in the... | 44,242 |
To calculate the degree of each vertex in a directed graph, we can iterate over each vertex in the graph and count the number of edges that start at that vertex as the out-degree, and the number of edges that end at that vertex as the in-degree. Then, we can compute the degree by adding the out-degree and the in-degree... | Implement a Python function to calculate the degree of each vertex in a directed graph. The graph is represented as a dictionary of adjacency lists. The function should return a dictionary that maps each vertex to its degree. The degree of a vertex is the sum of the in-degree and out-degree. The in-degree is the number... | To calculate the degree of each vertex in a directed graph represented by a dictionary of adjacency lists, we need to compute both the in-degree and out-degree for each vertex. The in-degree is the number of incoming edges to a vertex, while the out-degree is the number of outgoing edges from a vertex.
Here’s the impl... | 44,243 |
You can use Horner's method to evaluate a polynomial of degree n at a given point x. Horner's method reduces evaluation complexity from O(n^2) to O(n) by iteratively multiplying the coefficients and adding them to the previous term.
Here's how you could implement the Horner's method:
```python
def horner_eval(coeffic... | Develop a Python function to evaluate a polynomial of degree n at a given point x with the Horner's method, where n is a positive integer. The Horner's method employs a recurrence relation and a nested structure to evaluate the polynomial efficiently. It reduces evaluation complexity from O(n^2) to O(n). | To evaluate a polynomial using Horner's method, you can use a recursive or iterative approach. Below is a simple Python function that implements Horner's method iteratively to evaluate a polynomial at a given point `x`.
The polynomial is represented by its coefficients, where the coefficient of the highest degree term... | 44,244 |
To calculate the spatial area occupied by obstacles in a map represented by a 2D array, we can use a nested loop to iterate through each row and column of the array and count the number of obstacles. For each obstacle, we can add its area to a running total. In this case, we assume that all buildings and trees have the... | Write a Python function to calculate the spatial area occupied by obstacles in a map represented by a 2D array. The function should take the map as input and return a single number representing the area in squared meters. The map contains two types of obstacles: `1` for a building and `2` for a tree. Assume that all bu... | Here's a Python function that calculates the spatial area occupied by obstacles in a map represented by a 2D array. It recognizes `1` as buildings, `2` as trees, and counts them to determine the total area occupied by these obstacles. The function also checks for invalid values in the map and returns appropriate error ... | 44,245 |
Here is the implementation of `count_rolls`:
```python
def count_rolls(rolls, numbers):
return [sum(1 for roll in rolls if roll['die1'] == number or roll['die2'] == number) for number in numbers]
``` | Write a Python function `count_rolls(rolls, numbers)` that takes two arguments: `rolls` is a list of dictionaries where each dictionary represents a dice roll, and `numbers` is a list of integers between 1 and 6. The function should return a list of the counts of each `number` in `numbers` that occurred in the `rolls`.... | You can implement the `count_rolls` function to iterate over the list of dice roll dictionaries and count how many times each specified number appears across all the dice. Here's how you can do that:
```python
def count_rolls(rolls, numbers):
# Initialize a dictionary to hold counts for each number
counts = {n... | 44,246 |
We can leverage bitwise operations to determine if a given integer `n` is a power of two. By taking the base 2 logarithm of `n`, we can examine its exponent value. If `n` is a power of two, its exponent value will be an integer, and the fractional part of the logarithm will be 0.
Here's the implementation of the funct... | Write a Python function `bitwise_power_of_2` to check if a given integer `n` is a power of two. Use bitwise operations to calculate the base 2 logarithm of `n`, and then check if the fractional part of the result is zero. | To check if a given integer `n` is a power of two using bitwise operations, we can take advantage of the properties of the binary representation of powers of two. A number is a power of two if it has exactly one bit set in its binary representation. This can be checked using the expression `n > 0 and (n & (n - 1)) == 0... | 44,247 |
Here's how you can implement this in Python:
```python
def compose(f, g):
return lambda x: f(g(x))
def square(x):
return x ** 2
def generate_nested_function(n):
f = square
for _ in range(n - 1):
f = compose(f, square)
return f
``` | Develop a Python function that takes an integer `n` and returns a function `f` that is the composition of `n` nested functions. Each nested function should take a single integer argument and return its square. For example, if `n=3`, the returned function `f` would be equivalent to `lambda x: (x**2)**2**2` | You can create a function that returns a nested composition of functions as specified. Let's break it down step by step:
1. The outer function will take an integer `n` which indicates how many times we want to nest the squaring function.
2. We will use a closure to create the nested functions.
3. Each nested function ... | 44,248 |
Here's how you could do it:
```python
def factorial_trailing_zeros(n):
if not isinstance(n, int):
raise TypeError('n must be an integer')
factorial = 1
for i in range(1, n + 1):
factorial *= i
trailing_zeros = 0
while factorial % 10 == 0:
trailing_zeros += 1
factor... | Design a Python function that takes a number n and returns the number of trailing zeros in the factorial of n. If n is not a number, raise a TypeError.
Your code should pass the following test case:
```python
trailing_zeros = factorial_trailing_zeros(5)
assert trailing_zeros == 1
``` | To determine the number of trailing zeros in the factorial of a number \( n \), we can use the fact that trailing zeros are produced by the factors of 10 in the number. Since a factor of 10 is produced by a pair of factors 2 and 5, and there are generally more factors of 2 than factors of 5 in factorials, we primarily ... | 44,249 |
Here's how you could implement this function:
```python
def vectors_equal(v1, v2, tolerance=1e-5):
distance = ((v1[0] - v2[0])**2 + (v1[1] - v2[1])**2 + (v1[2] - v2[2])**2)**0.5
return distance <= tolerance
``` | Create a function that takes 2 3D vectors and returns True if they are equal (defined by a tolerance of 1e-5, i.e., they are within 1e-5 of each other). | To create a function that compares two 3D vectors for equality within a specified tolerance, we can use Python. The function will take two vectors as input, each represented as a tuple or list of three elements. We will check if the absolute difference between each corresponding components of the vectors is within the ... | 44,250 |
The task requires a Python function that takes a dictionary of string keys and converts it to a dictionary of dictionary keys with the specified types. The function should have type hints for both the input and output dictionaries.
Here's an example implementation of the `my_dict_to_dict` function:
```python
from typ... | Develop a Python function `my_dict_to_dict` that converts a dictionary of string keys to a dictionary of dictionary keys, where the keys are typed according to the specified input types. The function should have a type hint for the input dictionary and a type hint for the output dictionary. The function should return a... | To create the `my_dict_to_dict` function that converts keys from a dictionary of string keys to a dictionary with keys of a specified type, we need to implement type conversion and handle exceptions if the conversion fails. Below is the implementation of the function according to your specifications:
```python
from ty... | 44,251 |
Here is a Python function that parses a JSON string and merges it with an existing JSON object:
```python
import json
from typing import Any, Dict, Union
def merge_json(existing_json: Dict[str, Any], json_string: str) -> Union[Dict[str, Any], None]:
"""
Parses a JSON string and merges it with an existing JSON... | Write a Python function that parses a JSON-formatted string and merges it with an existing JSON object. The function should take two arguments: `existing_json`, a Python dictionary that represents an existing JSON object; and `json_string`, a string containing valid JSON data to be parsed. The function should return th... | To achieve the merging of a JSON object with a string containing JSON data while respecting the rules specified, you can use the following Python function. This function utilizes the `json` module for parsing and merging the objects. It will also handle errors gracefully and take care of the specified merging logic.
H... | 44,252 |
Here's an implementation of a Python function that takes an unsorted list of numbers as input and returns the top `n` largest numbers:
```python
def top_n_largest(nums, n):
if len(nums) == 0 or n < 0:
raise ValueError("Invalid input: list is empty or n is negative")
nums.sort(reverse=True)
return ... | Design a Python function that takes an unsorted list of numbers as input and returns the top `n` largest numbers. Your function should handle invalid input gracefully and raise an appropriate error. Furthermore, if the list size is smaller than `n`, return the entire list in descending order.
Your function should rais... | Certainly! Below is a Python function that meets the specified requirements. It returns the top `n` largest numbers from an unsorted list, handles invalid inputs, and raises a `ValueError` when necessary.
```python
def top_n_largest_numbers(numbers, n):
# Check for invalid input
if not isinstance(numbers, list... | 44,253 |
To solve this problem, we can use a decorator function to wrap the original function `fn` and measure its execution time and number of calls. The decorator function `timed` will check if the original function has already been timed using `hasattr` and `timed_fn.calls`. It will return the original function `fn` if it ha... | Write a Python function `timed` that wraps another function, `fn`, and returns a new function that measures how long `fn` takes to execute and how many times it is called. The function `timed` should return the original function `fn` if it has already been timed, otherwise it should return a new function that prints th... | You can create the `timed` decorator function in Python by utilizing the `time` module to measure execution time and a counter to keep track of how many times the function has been called. Below is an implementation of the `timed` function:
```python
import time
from functools import wraps
def timed(fn):
if hasat... | 44,254 |
To write a Python function to calculate the water index of a water body, you can follow these steps:
1. Define the function with the required parameters, including the `area`, `volume`, and `density` of the water body.
2. Calculate the water index as the ratio of the volume of water to the area of the water body, mult... | Write a Python function named `calc_water_index` for calculating the water index of a water body. The function takes the following parameters:
- `area`: The area of the water body in square meters.
- `volume`: The volume of water in cubic meters.
- `density`: The density of water in $kg/m^3$.
Then, the function shoul... | Here's a Python function `calc_water_index` that calculates the water index based on the provided parameters. The function includes type hints for clarity:
```python
def calc_water_index(area: float, volume: float, density: float) -> float:
"""Calculates the water index of a water body.
Parameters:
- area... | 44,255 |
```python
def hex_value(value):
if type(value) == str:
value = int(value)
return f"0x{value:02x}"
```
The `hex_value()` function accepts a string or integer as input and converts it to a hexadecimal string. If the input is a string, it is converted to an integer using the `int()` constructor. Then, it ... | Write a Python function that accepts a string or integer as input and returns a hexadecimal string representation of the value. The function should handle both string and integer inputs using the `int()` constructor. The hexadecimal string should be prefixed with `'0x'` and padded with zeros to ensure that its length i... | Certainly! Below is a Python function `hex_value` that takes either a string or an integer as input and returns its hexadecimal string representation, prefixed with `'0x'` and padded to ensure the length is a multiple of 2.
Here's the implementation:
```python
def hex_value(value):
# Convert the input to an integ... | 44,256 |
To find the key with the largest value in a dictionary, we can iterate through the items of the dictionary and compare the values. If there are more than one key with the largest value, we can pick the one that appears later in the dictionary by keeping track of the largest value and its corresponding key.
Here is the... | Design a Python function to find the key with the largest value in a dictionary. If there are more than one, use the one that appears later in the dictionary. If the dictionary is empty, return None. | To solve the problem of finding the key with the largest value in a dictionary while respecting the requirement to return the later appearing key in case of ties, we can create a function called `find_key_with_largest_value`. Here's how we can implement it:
```python
def find_key_with_largest_value(d):
if not d: ... | 44,257 |
Here's how you can implement this:
```python
def format_value(value):
if isinstance(value, str):
return f'"{value}"'
elif isinstance(value, int):
return f"{value:,d}"
elif isinstance(value, list):
if all(isinstance(item, str) for item in value):
return ", ".join(value)
... | Write a Python function to create a string representation of a dictionary with the format "{key}: {value} | {key}: {value} | ..." where the keys are sorted alphabetically. Each key-value pair should be separated by a pipe character ("|"). The values can be of any type, and their string representations should be formatt... | Here's a Python function that formats a dictionary according to the specifications you provided. It handles the formatting of different types of values, sorts the keys alphabetically, and constructs the required output string.
```python
def format_dict(input_dict):
def format_value(value):
if isinstance(va... | 44,258 |
To speed up computation on the CPU, we can use the GPU to do the computation if it is available. The `torch.cuda.is_available()` function checks if a GPU is available and the `torch.device('cuda')` function creates a `device` object that represents the GPU. Then, we can transfer the input data to the GPU device using t... | I have a function that performs a computationally expensive operation on the CPU. I want to speed it up by using the GPU to do this computation if it is available. Use the following code to check if a GPU is available and, if so, transfer the input data and perform the computation on the GPU. Then transfer the result b... | To implement the `run_gpu_computation` function that performs a computationally expensive operation on the GPU if available, we first need to define the `expensive_computation` function. We can simulate an "expensive" computation by, for instance, adding a small value to each element.
Here's how to implement the comp... | 44,259 |
Here is a Python function that implements the dot product of two vectors:
```python
def vector_dot(vector_a, vector_b):
if vector_a is None or vector_b is None:
return None
if len(vector_a) != len(vector_b):
raise ValueError("Both vectors must have the same length")
if len(vector_a) == 0 or... | Write a Python function `vector_dot` that takes `vector_a` and `vector_b` as input and returns their dot product. If `vector_a` and `vector_b` do not have the same length, raise an exception. If either input is `None` or an empty list, return `None` or `0` directly, respectively. | Certainly! Below is a Python function `vector_dot` that computes the dot product of two vectors, handling the specified conditions.
```python
def vector_dot(vector_a, vector_b):
if vector_a is None or vector_b is None:
return None
if len(vector_a) == 0 or len(vector_b) == 0:
return 0
if len... | 44,260 |
Here's a Python function that computes the F-measure:
```python
def compute_fmeasure(labels, predictions):
tp, fp, fn = 0, 0, 0
for label, prediction in zip(labels, predictions):
if label == 1 and prediction == 1:
tp += 1
elif label == 0 and prediction == 1:
fp += 1
... | Write a Python function named `compute_fmeasure` that takes two arguments: `labels`, an array of true labels, and `predictions`, an array of predicted labels for the same set of samples. The function should return the F-measure score, a harmonic mean between precision and recall. Precision is the number of true positiv... | To compute the F-measure score, we need to determine the precision and recall based on the true labels and predicted labels. Here’s a step-by-step breakdown of how to implement the `compute_fmeasure` function:
1. **Calculate true positives (TP)**: The number of samples predicted as positive that are actually positive.... | 44,261 |
To write a function that takes the HTML text as an input and returns a boolean indicating whether the text has a particular string, you can use regular expressions. Regular expressions are powerful tools for pattern matching and are widely used in text processing and web scraping.
Here's an example implementation in P... | I am writing a web scraper to extract data from a specific website. The scraper is working but it's not fully robust because the website's HTML code is inconsistent. Sometimes it uses empty `<div>` tags and sometimes it doesn't. I need to write a function that takes the HTML text as an input and returns a boolean indic... | To create a function that reliably checks if a particular string is present in the HTML text, even when the HTML structure may include inconsistencies such as empty `<div>` tags, you could implement a simple approach in Python.
Here's how you can define that function:
```python
import re
def contains_string(html_tex... | 44,262 |
```python
def join_string_list(string_list):
if not isinstance(string_list, list):
raise ValueError("The input must be a list.")
return ", ".join(map(str, string_list))
```
This implementation uses the join method on the list object to join the strings together with a comma and a space. It also convert... | Create a Python function that takes a list of strings and returns a single string that combines all the strings in the list, with each string separated by a comma and a space (", "). Make sure to convert each element to a string before joining. Include a precondition check to ensure the input is a list. | Certainly! Below is a Python function that takes a list of strings, ensures the input is valid, converts each element to a string, and combines them into a single string separated by a comma and a space.
```python
def combine_strings(string_list):
# Precondition check: ensure the input is a list
if not isinsta... | 44,263 |
Here is a Python function that implements this approach:
```python
def reverse_string_lines(string: str) -> str:
"""
Reverses the characters in a string line-by-line, where each line is terminated by either a newline character
or the end of the string. For example, given the string `"hello\nworld\n"`, the ... | Create a Python function to reverse the characters in a string line-by-line, where each line is terminated by either a newline character or the end of the string. For example, given the string `"hello\nworld\n"`, the function should return the string `"olleh\ndlrow\n"`. The function should assume that the input string ... | You can create a Python function to reverse the characters in a string line-by-line as described. Here’s how you can implement it:
```python
def reverse_lines(input_string):
# Split the input string into lines using the newline character
lines = input_string.splitlines(keepends=True)
# Reverse each li... | 44,264 |
Here's how you can do it in Python:
```python
from collections import Counter
def sort_unique_by_frequency(array):
counter = Counter(array)
return sorted(counter.items(), key=lambda x: (x[1], -x[0]), reverse=True)
```
The `Counter` object is used to count the occurrences of each integer in the input array. T... | Write a function `sort_unique_by_frequency` that takes an array of integers and returns an array of the unique integers sorted in descending order of their occurrence frequency.
Any integer that appears more than once in the array should be listed before those that appear fewer times.
Your code should pass the follow... | To create the function `sort_unique_by_frequency`, we can follow these steps:
1. Count the occurrences of each integer in the input array.
2. Sort the unique integers based on their frequency in descending order.
3. If two integers have the same frequency, they can maintain any order relative to each other, but for co... | 44,265 |
Here is an implementation of the `compose` function:
```python
from functools import reduce
from typing import Callable, List
def compose(*funcs: Callable[[], int]) -> Callable:
"""
Compose a list of functions from right to left.
If any function in the composition fails, `compose` immediately returns `Non... | Develop a Python function `compose(...)` that takes a list of functions and applies them to an input argument from right to left. For example, `compose(f, g, h)` should return a function equivalent to `lambda x: f(g(h(x)))`. If the list of functions is empty, `compose` should return the original argument. If any functi... | You can create the `compose` function as described using a higher-order function approach. Here's how you can implement it in Python:
```python
def compose(*functions):
"""
Composes a list of functions from right to left.
If any function fails during processing, it returns None.
Args:
... | 44,266 |
Here's how you could do it:
```python
import csv
import hashlib
def check_user_db(db_file, username, password):
with open(db_file, 'r') as csv_file:
reader = csv.reader(csv_file)
for row in reader:
if row[0] == username and row[1] == password:
return True
with open(... | Write a Python function that takes a database of username and password combinations as an argument and a username, password combination as input. The function should check if the username-password combination exists in the database and return True if it does. If not, the function should add the combination to the datab... | Certainly! Here’s a Python function that meets your requirements. It uses the `hashlib` library to hash the username and password with SHA-256. The database is stored as a CSV file, and the function checks for the username-password combination, adds it if it doesn't exist, and updates the CSV file accordingly.
Here’s ... | 44,267 |
Here is the implementation:
```python
def create_cfg_nodes(cfg):
nodes = []
for node, children in cfg:
if len(children) == 0:
nodes.append(['leaf', children, False])
elif len(children) == 1:
nodes.append(['conditional', children, False])
else:
nodes.a... | Implement a `create_cfg_nodes` function to create and return a list of nodes based on the given control flow graph (as a list of lists). The function should traverse the graph and create a CFG node for each node in the graph. A CFG node is represented as a list with three elements: the node type, the node's children (i... | To implement the `create_cfg_nodes` function that processes a control flow graph (CFG) represented as a list of lists, we need to iterate over each node in the graph and determine whether it is a leaf node, a conditional node, or a branch node based on the number of its children. Additionally, we'll mark the starting n... | 44,268 |
```python
import tarfile
def extract_tar(tar_path, destination_dir):
try:
with tarfile.open(tar_path, 'r') as tar:
tar.extractall(destination_dir)
return True
except Exception as e:
print(f"An error occurred while extracting the tar archive: {e}")
return False
```
T... | Create a Python function to extract a tar archive to a user-specified directory, handling any exceptions that may occur during the process. | Certainly! Below is a Python function that extracts a tar archive to a user-specified directory. The function handles various exceptions that may occur during the extraction process, such as file not found, permission errors, and other general exceptions.
To begin with, ensure you have the necessary module imported. ... | 44,269 |
Here is a Python function that implements this approach:
```python
def is_rectangular_grid(grid):
try:
for row in grid:
if len(row) != len(grid[0]):
return False
return True
except TypeError:
return "Invalid grid dimensions"
``` | Write a Python function that takes a list of integers representing the dimensions of a grid and validates whether it is rectangular (i.e., all rows have the same number of columns). If the grid is rectangular, return `True`, otherwise return `False`. If the input is not a list of integers or contains negative numbers, ... | You can achieve this by defining a function that checks the properties of the input grid dimensions. Here is a Python function that implements the required functionality:
```python
def validate_rectangular_grid(grid_dimensions):
# Check if the input is a list
if not isinstance(grid_dimensions, list):
r... | 44,270 |
Here is an implementation of the Fermat's Little Theorem approach:
```python
import random
def is_prime_fermat(number):
if number < 2:
return False
if number in [2, 3]:
return True
p = random.randrange(2, number)
return pow(p, number-1, number) == 1
```
You can validate this function ... | Write a Python function `is_prime(number)` that returns `True` if the given number is prime, and `False` otherwise. You may not use any built-in prime-testing functions or modules. | Certainly! Here is a Python function `is_prime(number)` that checks if a given number is prime without using any built-in prime-testing functions or modules:
```python
def is_prime(number):
# Check for numbers less than 2, which are not prime
if number < 2:
return False
# Check if the number is 2 o... | 44,271 |
```python
from itertools import product
def subset_by_bounds(arr, bounds):
slices = [slice(start, stop) for start, stop in bounds]
return arr[tuple(slices)]
``` | Suppose you have a multidimensional array and you want to extract a subset of the data as a copy, based on the bounds of the dimensions. For example, you want to extract a 2D slice of an array of shape `(10, 10)` bounded by `[2:5, 3:7]`. This subset should be a 2D array with shape `(3, 4)`.
Write a Python function tha... | Certainly! You can achieve this using NumPy, which is a powerful library for numerical computing in Python. Here's a function that accepts an array and a tuple of slice bounds, and returns the corresponding subset as a copy:
```python
import numpy as np
def extract_subset(array, bounds):
"""
Extract a subset ... | 44,272 |
1. Sort the list of `datetime` objects in ascending order.
2. Initialize a counter to keep track of the number of unique dates.
3. Iterate through the sorted list, comparing each date to the previous one.
4. If the current date is different from the previous date, increment the counter by 1.
5. Return the final counter... | I have a list of Python `datetime` objects representing dates of visit, written as `datetime.datetime(year, month, day)`. I want to get the number of unique dates represented in the list. This is a simple task. | You can easily find the number of unique dates from a list of `datetime` objects by converting the list to a set, which automatically removes duplicates, and then checking the length of that set.
Here is an example of how you can do this:
```python
from datetime import datetime
# Example list of datetime objects
vis... | 44,273 |
To create a Python function that takes a string containing a list of names and their corresponding ages, formatted as "Name, Age", and returns a list of tuples containing the name, age, and age range, we'll need to perform several steps:
- Split the input string into a list of individual "Name, Age" pairs.
- Iterate t... | Develop a Python function that takes a string containing a list of names and their corresponding ages, formatted as "Name, Age", and returns a list of tuples containing the name, age, and the age displayed as a person's age range, as defined below:
- If the age is less than 18, the age range is "Under 18"
- If the age... | To create the required Python function, we will define a function named `parse_names_ages`. This function will take a string input containing names and ages formatted as "Name, Age", separated by semicolons. It will process this input, extract the names and ages, determine the appropriate age range, and return a list o... | 44,274 |
To implement a function that checks if a string has all unique characters, we can iterate through each character in the string and check if it has already occurred in the string. To avoid using data structures like sets, we can use the `ord()` function to get the ASCII value of each character and use a list of booleans... | Implement a Python function `is_unique_chars_no_set` that checks if a string has all unique characters without using data structures like sets.
Hint: You can use the `ord()` function to get the ASCII value of a character.
Your code should pass the following assertions:
```python
assert is_unique_chars_no_set("a") == ... | To implement the function `is_unique_chars_no_set` that checks if all characters in a given string are unique without using set data structures, we can utilize an array to keep track of the characters we've encountered. Given that we're working with ASCII characters, we can create a boolean list of size 256 (the number... | 44,275 |
```python
def ground_truth_labeling(data_frames, target_columns):
if len(data_frames) != len(target_columns):
raise ValueError("The lengths of data_frames and target_columns must be the same.")
ground_truth_labels = []
for i, (data_frame, target_column) in enumerate(zip(data_frames, target_columns))... | Develop a Python function `ground_truth_labeling` that takes a list of `data_frames` and `target_columns` as input parameters, and returns a list of `ground_truth_labels` that are the same length as `data_frames`. Each `ground_truth_label` is a string with the following format:
```
"data_frame_i column_j: value_k"
wh... | To implement the `ground_truth_labeling` function as you described, we'll need to iterate through each data frame in the `data_frames` list and then through each target column in the `target_columns` list. For each combination, we will extract the required information to format the ground truth labels. Here's how we ca... | 44,276 |
Here's the Python function that returns the coefficient of the `n`th triangular number:
```python
def get_coeff(n: int) -> int:
return n + 1
```
The function `get_coeff(n)` takes in an integer `n` and returns the coefficient of the `n`th triangular number. The coefficient is simply `n + 1`. This is because the se... | Write a Python function `get_coeff(n)` to return the coefficient of a given index `n` in the sequence of triangular numbers. The triangular numbers are the numbers that appear in the rows of Pascal's triangle, where each number is the sum of the two numbers directly above it. For example, the first few triangular numbe... | To compute the coefficient of a given index `n` in the sequence of triangular numbers, we can use the formula for the nth triangular number:
\[
T(n) = \frac{n(n+1)}{2}
\]
This formula gives us the nth triangular number directly, which represents the sum of the first `n` natural numbers.
Here’s how we can implement ... | 44,277 |
Here's how we can implement this:
```python
def find_object_with_attr(objects, attr):
try:
for obj in objects:
if hasattr(obj, attr):
return obj
return None
except AttributeError:
return None
``` | Implement a Python function that takes a list of objects as input. Each object in the list has a property `attr` that can be accessed using the dot notation. The function should return the first object in the list that has `attr` as a property. If no such object exists, the function should return `None`.
Use a `try-ca... | Certainly! Below is a Python function that implements the specified behavior. This function iterates over the list of objects and checks each one for the presence of the `attr` property. If it finds an object with `attr`, it returns that object. If no such object is found, the function returns `None`. The try-catch blo... | 44,278 |
To solve this problem, it's important to understand the structure of the data and the desired outcome. The given structure is a list of tuples, each containing an integer ID and another tuple. The IDs are unique, and the inner tuple contains two numbers. The goal is to find the ID of the tuple with the greatest sum of ... | I have a list of tuples, each containing an integer and another tuple. The integer represents a unique ID and the other tuple contains two numbers. Design a Python function to find out the ID of the tuple with a greater sum of the numbers in the inner tuple, and then create a set of IDs of tuples with the same inner tu... | Sure! Below is a Python function that accomplishes what you're looking for. This function iterates through a list of tuples, calculates the sum of the numbers in the inner tuple associated with each ID, and keeps track of the ID that has the greatest sum. Then, it creates a set of IDs that share the same inner tuple as... | 44,279 |
Here's how you can implement the `tanimoto` function:
```python
def tanimoto(x, y):
"""Calculate the Tanimoto similarity coefficient between two bit arrays.
Args:
x (list): A bit array of length n.
y (list): A bit array of length n.
Returns:
float: The Tanimoto similarity coeffici... | Write a Python function `tanimoto` to calculate the [Tanimoto similarity coefficient](https://en.wikipedia.org/wiki/Jaccard_index) between two bit arrays. The function should accept two arguments: `x` and `y` that represent bit arrays (0s and 1s). Both arrays are of the same length. The function should return the Tanim... | Certainly! Here is a Python function that calculates the Tanimoto similarity coefficient between two bit arrays. The function includes input validation using assertions to ensure the input is of the correct type and length.
```python
def tanimoto(x, y):
"""
Calculate the Tanimoto similarity coefficient between... | 44,280 |
To escape a string surrounded by single quotes, we can use a loop that iterates through each character in the given string and checks if it is a backslash ('\\') character. If it is, we append a backslash ('\\') to the new string, followed by another backslash ('\\'). Otherwise, we simply append the current character t... | Write a Python function to escape a string that is surrounded by single quotes, where any backslash ('\\') character must be escaped. The function should return a new string with the escaped characters as double backslashes ('\\\\'). | You can create a function in Python that escapes backslashes in a string that is surrounded by single quotes. Here's how you can implement such a function:
```python
def escape_single_quoted_string(input_string):
# Check if the string is surrounded by single quotes
if input_string.startswith("'") and input_str... | 44,281 |
Here is the implementation of `log_call_time`:
```python
import datetime
import time
def log_call_time(func, *args, **kwargs):
start_time = time.time()
result = func(*args, **kwargs)
end_time = time.time()
execution_time = end_time - start_time
log_entry = f"Function: {func.__name__}, Time: {datet... | Write a Python function `log_call_time(func, *args, **kwargs)` that logs the execution time of a given function. The function should take a variable number of positional and keyword arguments, as well as accepting any necessary arguments for `func`. The function should return the result of executing `func` and should l... | Here's a Python function named `log_call_time` that fulfills your requirements. This function uses the `time` module to measure execution time and the `datetime` module to log the current date and time. The function will log the execution details to a file named `"func_time.txt"`.
```python
import time
import datetime... | 44,282 |
To write a function that dynamically loads a module given its name and returns a function object based on a provided function name, let's follow these steps:
1. Import a module using `importlib.import_module`: `importlib` is a standard library module that provides functions for dynamic module loading in Python. `impor... | Write a Python function that dynamically loads a module given its name and returns a function object based on a provided function name. The function should take an absolute import path to the module as an argument and return a reference to the function.
Your code should pass the following test case:
```python
import m... | You can achieve this by using Python's built-in functions to dynamically load a module and retrieve a function from it. Here’s a function that accomplishes this using the `importlib` module, which provides a straightforward way to import a module using its name:
```python
import importlib
def get_function_from_module... | 44,283 |
To multiply a 1-D NumPy array `v` of shape (n, ) with a 2-D NumPy array `m` of shape (n, m), follow these steps:
1. Validate the shapes of `v` and `m`: Ensure that the first dimension of `v` is equal to the second dimension of `m` by checking `v.shape[0] == m.shape[0]`. This ensures the arrays are compatible for multi... | Write a Python function `vector_matrix_multiply(v, m)` that multiplies a 1-D NumPy array `v` of shape (n, ) with a 2-D NumPy array `m` of shape (n, m). Return the resulting product as a NumPy array of shape (m, ). You may assume that `v` and `m` are of compatible shapes. | To multiply a 1-D NumPy array `v` with a 2-D NumPy array `m`, we can use NumPy's `dot` function or the `@` operator, which is designed for matrix multiplication. Additionally, since `v` is a 1-D array with shape (n,) and `m` is a 2-D array with shape (n, m), the result will have shape (m,).
Here's a Python function `v... | 44,284 |
Here's how you can implement this:
```python
import os
def read_binary_and_name(path):
filename = os.path.basename(path) # Get the file name without the extension
file_extension = os.path.splitext(filename)[1] # Get the extension
filename_without_extension = os.path.splitext(filename)[0] # Get the file... | Create a Python function that takes a `path` argument, reads the contents of the path into a byte array, and returns a list of two elements: the byte array, and the file name of the path (without its extension). | You can create a Python function to read the contents of a file located at the specified path, convert those contents into a byte array, and return that byte array along with the file name (without its extension). Here's how you can implement this:
```python
import os
def read_file_as_bytes(path):
"""
Reads t... | 44,285 |
Here is a Python function to convert a date string in the format 'YYYY/MM/DD' to the corresponding number of days since the Unix Epoch in UTC time:
```python
import datetime
def days_since_epoch(date_string: str) -> int:
date = datetime.datetime.strptime(date_string, '%Y/%m/%d')
unix_epoch = datetime.datetime... | Write a Python function to convert a date string in the format 'YYYY/MM/DD' to the corresponding number of days since the Unix Epoch (1970-01-01) in UTC time. The function should use the built-in datetime library to perform the parsing and calculation. | You can use the `datetime` module from Python's standard library to achieve this. Here's a function that converts a date string in the format 'YYYY/MM/DD' to the corresponding number of days since the Unix Epoch (1970-01-01):
```python
from datetime import datetime, timedelta
def days_since_epoch(date_str):
"""
... | 44,286 |
To traverse a data structure and perform some action based on certain attributes, you can use recursion. The function should use a depth-first search algorithm and visit every node in the data structure. The action can be as simple as printing the attribute value or more involved. The function should be able to handle ... | Write a Python function that traverses a data structure and performs some action based on certain attributes. The function should access the attributes using the dot notation, such as `obj.attr`. The action may be as simple as printing the attribute value or more involved. Write the function so that it handles any data... | Certainly! Below is a Python function named `traverse_and_action` that can traverse a variety of data structures: lists, dictionaries, and custom objects. It uses dot notation to access attributes of objects and performs a specified action on them, such as printing the attribute values.
### Python Function Implementat... | 44,287 |
Here is the implementation of the `file_checksum` function:
```python
import binascii
def file_checksum(path: str, chunk_size: int = 4096) -> str:
with open(path, 'rb') as file:
checksum = binascii.crc32(b'')
while True:
chunk = file.read(chunk_size)
if not chunk:
... | Write a Python function `file_checksum` to calculate the checksum of a file using the CRC-32 algorithm. The function should take two arguments: `path`, a string representing the path to the file, and `chunk_size`, an integer representing the size of the chunk to read from the file at a time. The function should return ... | To calculate the checksum of a file using the CRC-32 algorithm, you can use Python's built-in `binascii` module, which provides a convenient function to compute the CRC-32 checksum of bytes. Here’s a possible implementation of the `file_checksum` function:
```python
import binascii
def file_checksum(path, chunk_size=... | 44,288 |
To deduplicate a list of strings, we can use a Python set to store the unique strings. We can iterate over the input list, and for each string, we can check if it's already in the set. If it's not, we'll add it to the set and append it to the output list. This way, we ensure that each string appears only once in the ou... | Write a Python function `deduplicate_strings(strings: List[str]) -> List[str]` that takes a list of strings and returns a deduplicated list, where each string appears only once in the output. If the input list is empty or contains no strings, the function should return an empty list.
Use type annotations to specify th... | Here's a Python function that meets your requirements. It takes a list of strings and returns a deduplicated list while handling any potential errors that may arise during execution. The code uses type annotations for better clarity.
```python
from typing import List
def deduplicate_strings(strings: List[str]) -> Lis... | 44,289 |
Here is a Python function that implements the above steps:
```python
def format_cardinal(n: int, cardinal_dict: dict) -> str:
"""
Formats the cardinal number representation of a given number, n.
Parameters:
- n: The number to convert (must be between 0 and 999)
- cardinal_dict: A dictionary mappin... | Write a Python function `format_cardinal` that takes a positive `int` `n` and returns a string of the cardinal number representation of `n`, e.g., `1` -> `'one'`, `100` -> `'one hundred'`, `123` -> `'one hundred twenty three'`, etc.
The function should use an input dictionary `cardinal_dict` to map each digit to its c... | To implement the `format_cardinal` function that converts integers from 0 to 999 into their cardinal number string representation, we can first define a dictionary containing the mappings for numbers from 0 to 99. Then, we can break down numbers from 100 to 999 into their component parts and format them accordingly.
H... | 44,290 |
Here's how you can solve this problem in Python:
```python
def character_count_in_list(string, lst):
result = {}
for char in string:
if char in lst:
result[char] = result.get(char, 0) + 1
return result
``` | Write a Python function that takes a string and a list as arguments and returns a dictionary with keys representing the characters from the string and values representing the number of times each character appears in the list. For example, given the string "aabbcc" and the list ["a", "b", "a", "b", "c", "c"], the funct... | Here's a Python function that implements the functionality you've described:
```python
def count_characters_in_list(characters, lst):
# Create a dictionary to hold the counts
count_dict = {}
# Count only the characters present in the list
for char in characters:
if char in lst:
... | 44,291 |
To write this function, you need to understand the syntax of Python comments. Inline comments are denoted by the hash (`#`) symbol and extend to the end of the line. To generate documentation, we can replace these comments with the `#` symbol.
Here is a Python function that implements this approach:
```python
def pro... | Write a Python function `process_comments` that takes a string representing Python source code and replaces inline comments with `#` to generate documentation. The function should return the resulting code as a string. | To create the function `process_comments`, we will analyze the input string representing Python source code and replace inline comments with `#` to create documentation. The function will find comments that start with `#` and replace them with a formatted version for clearer documentation.
Here is the implementation:... | 44,292 |
To design a Python function `convert_to_object(obj)` that converts all values in the input object to objects, you can follow these steps:
1. Define a recursive function `convert_value(value)` that takes a value and returns an object with `data` and `type` attributes.
2. If the value is a list, call `convert_value` on ... | Design a Python function `convert_to_object(obj)` that recursively converts all values in the input `obj` to objects, regardless of their types. Each value should be converted into a Python object with a `data` attribute and a `type` attribute. The `data` attribute should store the original value of the input, and the ... | Here is a Python function `convert_to_object(obj)` that accomplishes the task of recursively converting all values in the input to objects with `data` and `type` attributes:
```python
class CustomObject:
def __init__(self, data):
self.data = data
self.type = type(data).__name__
def convert_to_obje... | 44,293 |
Here is the implementation of the Python function to find the second smallest element in a list:
```python
def second_smallest(input_list):
"""
Find the second smallest element in a list.
Args:
input_list (list): The input list of integers or floats.
Returns:
second_smallest_element (... | Write a Python function to find the second smallest element in a list, allowing for both integers and floats as input. The function should return `None` if the input list contains less than two elements or if all elements are equal. Use inline documentation to explain your code.
Your code should pass the following ass... | Here's a Python function that meets your requirements for finding the second smallest element in a list. The function includes inline documentation to explain its logic:
```python
def second_smallest(numbers):
"""
Find the second smallest unique element in a list of numbers (integers or floats).
Param... | 44,294 |
Here's an example implementation of the function:
```python
def convert_path_windows_to_unix(path: str) -> str:
if not path:
return ''
path_parts = path.split('\\')
if '/' in path:
path_parts = path.split('/')
if path_parts[0][-1] == ':':
path_parts[0] = '/' + path_parts[0][:-1]... | Write a Python function to convert a file path from Windows to Unix style. For example, `C:\Users\user\Documents\file.txt` should be converted to `/C/Users/user/Documents/file.txt`. You need to account for different cases where file paths may contain slashes, spaces, and special characters. Additionally, your solution ... | Sure! Below is a Python function that converts a Windows file path to a Unix-style file path. This function will handle drive letters, backslashes (`\`), and also manage some special cases you mentioned.
```python
import os
def windows_to_unix_path(windows_path):
"""
Convert a Windows file path to a Unix-styl... | 44,295 |
To create a Python function that normalizes the channel-wise mean and standard deviation of a tensor to have zero mean and unit standard deviation, you can use the following steps:
1. Compute the mean and standard deviation of the input tensor along the channel dimension.
2. Normalize the input tensor by subtracting i... | Create a Python function that takes a tensor (or PyTorch `Tensor`) and normalizes the channel-wise mean and standard deviation of the tensor to have zero mean and unit standard deviation. Use parallel optimization to speed up the loop execution.
Your code should pass the following test case:
```python
input_tensor = t... | To normalize a tensor in PyTorch such that each channel has zero mean and unit standard deviation, we can create a function `normalize_channel_mean_std`. We will use PyTorch operations to achieve this in an efficient way, leveraging its parallelization features.
Here's an implementation of the function:
```python
imp... | 44,296 |
Here's a possible implementation of the function:
```python
def convert_to_tree(s):
chars = list(s)
def next_node(idx=0):
char = chars[idx]
idx += 1
return char, idx
return next_node()[0]
``` | Write a Python function `convert_to_tree(s)` that accepts a string `s` and returns a tree-like representation of the string. The function should work as follows:
- Convert the string to a list of characters using `list(s)`.
- Define a default argument value of `idx=0`.
- Define a function `next_node()` that returns the... | To create a tree-like representation from a string in Python, we can define a `TreeNode` class that represents each node in the tree. Then, we will create the `convert_to_tree` function which will construct the tree based on the input string. The function will utilize an inner function called `next_node()` to manage th... | 44,297 |
To create such a function, you need to first check the type of the timestamp and handle it accordingly. If it's a Unix timestamp, convert it to a datetime object using the `datetime.fromtimestamp()` method. Then, you can convert the datetime object to a string using the `strftime()` method with the desired format.
Nex... | Write a Python function that takes a timestamp and returns an SQL statement to insert or update a row into a `user` table. The function should handle different inputs, including Unix timestamps and datetime objects. You should also include a check to ensure the username is valid and the email is in the correct format. | To create a Python function that generates an SQL statement for inserting or updating a row in a `user` table, we need to consider several parameters: the username, email, and timestamp. We'll make use of Python's built-in `datetime` module to handle both Unix timestamps and datetime objects, and utilize regular expres... | 44,298 |
Here's how you can do it:
```python
def call_function(fn, args):
return fn(*args)
def sum_function(a, b):
return a + b
result = call_function(sum_function, (1, 2))
print(result) # Output: 3
``` | Write a Python function that defines and calls another function. The inner function should take two arguments, `a` and `b`, and return their sum. The outer function should take two arguments, `fn` and `args`, and return the result of calling `fn` with `args`. For example, calling the outer function with `fn=sum` and `a... | Certainly! Below is a Python function that defines and calls another function as per your requirements:
```python
def outer_function(fn, args):
def inner_function(a, b):
return a + b
# If the provided function is `sum`, we will use the inner function
if fn == sum:
return sum(args)
... | 44,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.