response_seed stringlengths 53 5.17k | instruction_seed stringlengths 29 4.02k | response stringlengths 16 8.81k | __original_row_idx int64 0 50k |
|---|---|---|---|
Here's how you could do it:
```python
def first_two_repeated(string):
if len(string) >= 2:
return string[:2] * 3
else:
return string
```
This function checks if the input string has at least two characters. If so, it extracts the first two characters and repeats them three times. Otherwise, it... | Create a Python function that takes a string and returns a new string that is composed of the first two characters of the original string, repeated three times. If the input string has less than two characters, then return the original string. | You can create the desired function in Python as follows:
```python
def repeat_first_two_chars(input_string):
# Check if the string has less than 2 characters
if len(input_string) < 2:
return input_string
# Extract the first two characters and repeat them three times
return input_string[:2] * 3... | 7,600 |
To generate a 16-byte random string in hex format, you can use the `secrets` module provided by Python. The `secrets.token_hex()` function generates a random string of the specified number of bytes in hexadecimal format.
Here's how you can implement the guid generator function in Python:
```python
import secrets
def... | Write a Python function to generate a unique identifier (guid) for a specific data entry object. The guid should be a 16-byte random string in hex format. The function takes a data entry as input and returns the guid as a string.
Your code should pass the following test case:
```python
import random
data_entry = rand... | You can generate a unique identifier (GUID) for a data entry by using the `os.urandom` function, which provides cryptographic-quality random bytes. Then you can convert those bytes to a hexadecimal string. Here's how you can implement the function:
```python
import os
def generate_guid(data_entry):
# Generate 16 ... | 7,601 |
Here is the implementation of a Python function that generates a list of all Collatz numbers (in ascending order) for a given initial value $x_0$:
```python
def generate_collatz_sequence(x0):
collatz_sequence = []
x = x0
while x != 1:
collatz_sequence.append(x)
if x % 2 == 0:
x ... | Here is a simple Collatz conjecture:
$x_{n+1} = \begin{cases}
x_n/2 & \text{if } x_n \text{ is even} \\
3x_n + 1 & \text{if } x_n \text{ is odd}
\end{cases}$
Write a Python function that generates a list of all Collatz numbers (in ascending order) for a given initial value $x_0$.
Your code should pass the fo... | You can create a function to generate the Collatz sequence by following the rules you provided. Here's a Python function that does just that:
```python
def generate_collatz_sequence(x0):
# Initialize the sequence with the starting number
sequence = []
current = x0
# Generate the Collatz sequence
... | 7,602 |
To validate the nodes in a Maya scene based on the given rules, we can iterate through each node in the list and check its type and number of children against the rules. If a node does not meet the rules, we can add its name to a list of invalid nodes.
```python
def validate_nodes(nodes):
invalid_nodes = []
fo... | I have a Maya scene file that contains a list of nodes. Each node has a type attribute (string), a name attribute (string), and a list of children (other nodes). Each node also has a history attribute (list of nodes) that records the parent of each node in the scene. I want to write a Python function that takes a list ... | Here's a Python function that takes a list of nodes and validates them based on your specified rules. The function checks the attributes and relationships of each node, collecting the names of any invalid nodes in a list, which it then returns.
```python
def validate_nodes(nodes):
invalid_nodes = []
for node ... | 7,603 |
Here is the implementation of `bitwise_shift_right`:
```python
def bitwise_shift_right(x: int, n: int, is_signed: bool) -> int:
if is_signed:
return x >> n
else:
return x >> n & 0xFFFFFFFF
```
The function `bitwise_shift_right` takes three arguments: `x` (an integer), `n` (the number of bits t... | Write a Python function `bitwise_shift_right(x, n, is_signed)` that performs a bitwise shift right operation on the given integer `x` by `n` bits. If `is_signed` is `True`, the function should preserve the sign of the number. If `is_signed` is `False`, the function should treat the number as unsigned. The function shou... | To implement the `bitwise_shift_right` function that performs a bitwise right shift operation while considering whether the number is signed or unsigned, we need to handle both cases appropriately.
Here's how you can define the function:
```python
def bitwise_shift_right(x, n, is_signed):
if is_signed:
# ... | 7,604 |
You can create a Python function that uses the `re` module to match and remove control characters from a given string.
```python
import re
def strip_control_characters(text):
control_characters = re.compile(r'[\x00-\x1F\x7F-\x9F]')
return control_characters.sub('', text)
``` | Write a Python function `strip_control_characters(text)` that strips control characters from a given string. The control characters include the following code points:
* U+0000 to U+001F
* U+007F to U+009F
The function should also handle Unicode characters properly.
Your code should pass the following assertion:
```p... | To create the `strip_control_characters` function that removes control characters from a given string, we can utilize Python's string handling capabilities along with the Unicode code point ranges specified. We'll iterate over each character in the input string and keep only those that are not in the control character ... | 7,605 |
To validate whether two lists are the same length, we can use the `len()` function to get the length of each list and compare the lengths. If the lengths are equal, the lists are of the same length. By using list comprehension, we can write a concise and efficient implementation of the function.
Here's an implementati... | Develop a function `validate_lists` in Python that checks whether two lists are the same length and returns a boolean value. If the lists are the same length, the function should return `True`, otherwise it should return `False`. The function should accept two list arguments and perform the check using list comprehensi... | You can create the `validate_lists` function in Python as specified. Here's the implementation using list comprehension to compare the lengths of the two lists:
```python
def validate_lists(list1, list2):
return len(list1) == len(list2)
# Example usage:
list_a = [1, 2, 3]
list_b = [4, 5, 6]
list_c = [7, 8]
print... | 7,606 |
To create a function that takes an object and replaces its specified attributes with default values, we can leverage the Python's built-in library `copy`, which provides a convenient way to make deep copies of objects. This library recursively copies objects, meaning that it creates new instances of nested objects.
He... | Write a Python function that takes in an object and returns a copy of the object with the specified attributes replaced by default values. The function should be able to handle complex objects with nested sub-objects. | To create a function that copies an object while replacing specified attributes with default values, you can use the `copy` module to handle complex objects and recursion to navigate through nested structures. Below is an implementation that achieves this in Python.
We'll define a function `replace_attributes_with_def... | 7,607 |
Here's an example of how you could implement the `paginate()` function:
```python
def paginate(items, page_size=10, page=1):
start_index = (page - 1) * page_size
end_index = start_index + page_size
return items[start_index:end_index]
```
This function accepts three arguments: `items`, `page_size`, and `pa... | Write a Python function `paginate(items, page_size=10, page=1)` that accepts an iterable of items and returns a list of items for the specified page, where each page consists of the given number of items. The `page` parameter should default to 1, while the `page_size` parameter should default to 10. Make sure the funct... | Here's a Python function that implements pagination for an iterable of items. The function `paginate` accepts an iterable, a `page_size`, and a `page` number, returning the items for the specified page. The function also handles keyword arguments for `page` and `page_size`.
```python
def paginate(items, page_size=10, ... | 7,608 |
Here's how you can implement the `extract_value_from_nested_dict` function in Python:
```python
def extract_value_from_nested_dict(nested_dict, path):
if not path:
return nested_dict
key = path[0]
if key not in nested_dict:
raise AssertionError(f"Key {key} not found in the nested dictionary... | Design a Python function `extract_value_from_nested_dict` that takes a nested dictionary and a path as inputs and returns the value at the given path in the nested dictionary. The path is a list of keys to follow, and the function should raise an assertion error if a key is not present in the dictionary. If the path is... | Here's a Python function called `extract_value_from_nested_dict` that meets your requirements. This function will traverse a nested dictionary based on the provided path (a list of keys) and return the value at that location. If a key is missing along the path, it raises an assertion error. If the path is empty, the fu... | 7,609 |
To implement a key-value store, you can use a dictionary in Python. The keys in the dictionary represent the keys in the store, and the values associated with each key are a list of values. The `add` and `remove` functions can be implemented by adding and removing values from the list associated with the given key, res... | Write a Python function to implement a key-value store, where each key is associated with a list of values. The function should support the following operations:
- `add(key, value)`: Add a new value to the list of values associated with a key.
- `remove(key, value)`: Remove a value from the list of values associated w... | Certainly! Below is a Python implementation of a key-value store that meets your requirements. We will define a class named `KeyValueStore` which encapsulates the desired operations.
```python
class KeyValueStore:
def __init__(self):
self.store = {}
def add(self, key, value):
"""Add a new valu... | 7,610 |
Here is an example implementation of the function:
```python
def group_by_event_type(dicts):
return {
event_type: [d for d in dicts if d['event_type'] == event_type]
for event_type in set(d['event_type'] for d in dicts)
}
```
The function `group_by_event_type` takes a list of dictionaries as i... | Given a list of dictionaries, write a function that groups them by their `event_type` key, and returns a dictionary with the event types as keys and the lists of dictionaries as values. Here are a few example inputs and outputs:
```python
# example 1
input = [
{'id': 1, 'event_type': 'click'},
{'id': 2, 'event... | You can achieve this by defining a function that iterates through the list of dictionaries and groups them based on the `event_type` key. Below is a sample implementation in Python:
```python
def group_by_event_type(event_list):
grouped_events = {}
for event in event_list:
event_type = event['even... | 7,611 |
To solve this problem, you can iterate through the key-value pairs in the dictionary and store the last value seen for each key in a new dictionary. You can use a conditional statement to check if the key has already been seen and update the value accordingly.
Here's an example of a function that satisfies the given a... | Write a Python function `remove_duplicates_in_dict` that takes a dictionary `d` as an argument and returns a new dictionary with the same keys, but with only the last value seen for each key. You may assume the values are hashable (e.g., strings, numbers). The function should satisfy the following assertions:
```pytho... | You can achieve this by iterating through the dictionary and creating a new one that captures only the last value associated with each key. Here’s how you can implement the `remove_duplicates_in_dict` function:
```python
def remove_duplicates_in_dict(d):
# Create a new dictionary to store the last seen values for ... | 7,612 |
To check if a port number is valid, we can define a function `check_port_number` that takes the port number as an argument and checks if it is in the valid range. The valid range is from 0 to 65535, inclusive. We can use the `range` function to define this range and check if the port number is within the range.
Here i... | Write a Python function `check_port_number` that takes a port number as input and checks whether it is valid. A valid port number is an integer within the range of 0 to 65535.
Your code should pass the following assertions:
```python
assert check_port_number(80) is True
assert check_port_number(65535) is True
assert c... | You can implement the `check_port_number` function as follows:
```python
def check_port_number(port):
"""
Check if the given port number is valid.
A valid port number is an integer in the range of 0 to 65535.
Parameters:
port (int): The port number to check.
Returns:
bool: Tr... | 7,613 |
Here's how you could do it:
```python
def transform_dict_of_lists(d):
new_dict = {}
for key, value in d.items():
new_dict[key] = {i: value[i] for i in range(len(value))}
return new_dict
``` | Write a Python function to transform a dictionary of lists into a dictionary of dictionaries. The keys of the initial dictionary should be used as keys for the final dictionary, and the values of the initial dictionary should be converted into a dictionary containing the index as keys and the corresponding element as v... | You can achieve the transformation of a dictionary of lists into a dictionary of dictionaries by iterating over the items in the original dictionary and constructing the new format. Here's a function that accomplishes this:
```python
def transform_dict_of_lists_to_dict_of_dicts(input_dict):
# Initialize the output... | 7,614 |
Here's an example of how you can implement this in Python:
```python
def overlap_area(rect1, rect2):
x1, y1, x2, y2 = rect1
x3, y3, x4, y4 = rect2
min_x = max(x1, x3)
max_x = min(x2, x4)
min_y = max(y1, y3)
max_y = min(y2, y4)
if min_x > max_x or min_y > max_y:
return [0.0, 0.0, 0.0... | Write a Python function to calculate the area of overlap between two rectangles. The input of the function is two arrays of floats of size (4,). The first four elements of `rect1` contain the coordinates of the bottom-left corner and the top-right corner of the first rectangle, and the second four elements of `rect2` c... | To calculate the area of overlap between two rectangles defined by their bottom-left and top-right coordinates, we can follow the steps below:
1. Retrieve the coordinates of each rectangle.
2. Determine the coordinates of the overlapping area by:
- Finding the maximum of the x-coordinates of the bottom-left corners... | 7,615 |
```python
def format_iso_date(string):
year, month, day = string.split('-')
months = {
'01': 'Jan',
'02': 'Feb',
'03': 'Mar',
'04': 'Apr',
'05': 'May',
'06': 'Jun',
'07': 'Jul',
'08': 'Aug',
'09': 'Sep',
'10': 'Oct',
'11': '... | Write a Python function `format_iso_date(string)` to format a date string in ISO format (YYYY-MM-DD) to a human-readable format. The function should replace each hyphen with a space, and adjust the month name to use the abbreviated three-letter form. For example, `format_iso_date('2023-01-01')` should return `'Jan 01 2... | Sure! You can create the function `format_iso_date(string)` to transform an ISO date string into the desired format. Below is the implementation of the function that meets the specified requirements:
```python
def format_iso_date(date_string):
# Dictionary to convert month number to abbreviated month name
mont... | 7,616 |
To write a Python function `map_with_type_check` that takes two dictionaries `source_dict` and `target_dict` and maps values from `source_dict` to keys in `target_dict` according to certain conditions, you can follow these steps:
1. Iterate through the keys in `target_dict` and check if they are strings. If not, retur... | Write a Python function `map_with_type_check` that takes two dictionaries, `source_dict` and `target_dict`, and maps the values in `source_dict` to the corresponding keys in `target_dict` according to the conditions:
1. Each key in `target_dict` must be a string.
2. If the key in `target_dict` is not in `source_dict`,... | You can create the `map_with_type_check` function to fulfill the requirements mentioned. Here's how you could implement it:
```python
def map_with_type_check(source_dict, target_dict):
result = {}
for key in target_dict:
if isinstance(key, str): # Ensure the key in target_dict is a string
... | 7,617 |
This problem requires us to find the first minimum value in a list of integers. We can achieve this by iterating through the list and keeping track of the minimum value and its index.
The following Python function implements this behavior:
```python
def first_minimum(nums):
first_idx = None
first_min = None
... | Create a Python function that takes a list of integers and returns the first minimum value in the list. The function should return the index of the first minimum value in the list. If there are multiple minimum values, return the index of the first occurrence.
Your code should pass the following assertions:
```python
... | You can accomplish this by creating a function that iterates through the list to find the index of the first occurrence of the minimum value. Here's the implementation of the `first_minimum` function:
```python
def first_minimum(lst):
if not lst: # Check if the list is empty
return None # or you could ra... | 7,618 |
The roof tiles are rectangular and measure 1 x 2, which means that two tiles are needed to cover a space of width 1. In general, the number of tiles required to cover a space of width n is n * 2.
Here is a Python function that implements this approach:
```python
def count_roof_tiles(width, length):
if width < 0 o... | Implement a Python function `count_roof_tiles(width, length)` that calculates the number of roof tiles required to cover a rectangular wall of a given width and length. The function should return 0 if the input values don't meet the preconditions: width >= 0, length >= 0, width and length are integers.
The roof tiles ... | Here's the implementation of the function `count_roof_tiles`:
```python
def count_roof_tiles(width, length):
if not (isinstance(width, int) and isinstance(length, int)) or width < 0 or length < 0:
return 0
return (width * length) // 2
``` | 7,619 |
To solve this problem, we can use a simple logical expression combining the conditions given in the instruction. When `a` is odd, the function should return `True` if `a` is positive and `b` is negative. We can represent this condition using the logical AND operator (`and`). When `a` is even, the function should return... | Design a Python function that accepts two integer parameters, `a` and `b`. The function should return `True` if the sum of the two numbers is even. Additionally, if `a` is odd, the function should also return `True` if `a` is positive and `b` is negative. For example, if `a` is 1 and `b` is -1, the function should retu... | You can create a Python function that implements the given logic as follows:
```python
def check_numbers(a, b):
# Check if the sum of a and b is even
if (a + b) % 2 == 0:
return True
# Check if a is odd and a is positive, and b is negative
if a % 2 != 0 and a > 0 and b < 0:
return True
... | 7,620 |
Here is a possible implementation for such a function:
```python
def find_target_char(string: str, target: str) -> int:
assert type(string) is str, "string should be a str type"
assert type(target) is str, "target should be a str type"
if target not in string:
return -1
return string.index(targ... | Design a Python function that takes a string and a target character and returns the index of the first occurrence of the target character in the string. If the target character does not exist in the string, the function should return -1. The function should also check the types of the input parameters and raise an `Ass... | Certainly! Below is a Python function that fulfills the requirements you specified. It checks for the correct types of the input parameters and returns the index of the first occurrence of the target character in the string, or -1 if the character is not found.
```python
def find_character_index(string: str, target: s... | 7,621 |
To filter out non-ASCII characters, we can iterate over each character in the Unicode string and check if its code point is within the range of ASCII characters, which is between 0 and 127. If it's an ASCII character, we can append it to a new string.
Here's how we can implement this:
```python
def filter_non_ascii_c... | Given a Unicode string, write a Python function to filter out all non-ASCII characters and return a new string containing only ASCII characters from the given Unicode string.
Your code should pass the following test case:
```python
unicode_string = "Hello, 世界!"
assert filter_non_ascii_characters(unicode_string) == "He... | You can create a function to filter out non-ASCII characters from a given Unicode string in Python. Here's a simple implementation:
```python
def filter_non_ascii_characters(unicode_string):
# Use a list comprehension to include only ASCII characters
return ''.join([char for char in unicode_string if ord(char)... | 7,622 |
To solve this problem, you need to iterate through the input list of strings and count the number of characters in each string. To achieve this, you can use a for loop to iterate over the list and a `len()` function to get the length of each string.
Here's an example implementation of the function:
```python
def coun... | Create a Python function that takes a list of strings as input and outputs a list of integers representing the number of characters in each string. Develop a test function with example input data and expected output to ensure the correctness of your code. | Here's a Python function that takes a list of strings as input and returns a list of integers representing the number of characters in each string. I'll also provide a test function to ensure the correctness of the code.
```python
def count_characters(strings):
# This function takes a list of strings and returns a... | 7,623 |
To construct file paths from a dictionary of file names and paths, we can use a dictionary comprehension to iterate through each key-value pair and construct a new dictionary where the key is the file path and the value is the file name. We can use the `os.path.join` function from the `os` module to join the file direc... | Given a dictionary whose keys are file names and values are the file paths, write a Python function `construct_file_paths(files_dict)` to construct a dictionary of file paths from the given files dictionary. The new dictionary should be a mapping from file names to their constructed paths.
For example, given `files_di... | Certainly! You can implement the function `construct_file_paths` to achieve this by iterating through the items in the given dictionary (`files_dict`), constructing the file paths by combining the directory paths with the file names, and then building a new dictionary with these constructed paths as keys and the origin... | 7,624 |
Here's an implementation of the `get_function_label` function using a `for` loop and the `break` statement:
```python
def get_function_label(function_label, function_labels, get_attr):
attr = get_attr(function_label)
for label in function_labels:
if get_attr(label) == attr:
return label
... | Create a Python function `get_function_label` that takes three arguments: a string `function_label`, a list of strings `function_labels`, and a function `get_attr`. The `get_attr` function takes a string as input and returns an attribute of the function `get_attr`. The function should return the first string in `functi... | Here is the implementation of the `get_function_label` function according to your specifications:
```python
def get_function_label(function_label, function_labels, get_attr):
# Get the attribute value of the function label using get_attr
attr_value = get_attr(function_label)
# Iterate through the list... | 7,625 |
To reverse the order of nodes in a binary tree, we'll have to traverse the tree in a specific order. We need to do the following in the specified order:
1. Reverse the left subtree of the current node.
2. Reverse the right subtree of the current node.
3. Swap the left and right subtrees of the current node.
4. Proceed... | In a binary tree, write a function to reverse the order of the nodes in a binary tree. Also, when a parent node is reversed, its left and right subtrees need to be swapped. | To reverse the order of nodes in a binary tree while swapping the left and right subtrees of each node, we can perform a post-order traversal of the tree. In this traversal, we will swap the left and right children of each node recursively, effectively flipping the entire tree.
Below is a Python code example using a s... | 7,626 |
To compute the mean of a list of numbers, first determine the length of the list and verify that it is not empty. Iterate over the list and add each element to a variable `sum`, which represents the sum of all elements. Divide `sum` by the length of the list to get the mean.
Here is the implementation of the `find_mea... | Design a Python function `find_mean(numbers)` to calculate the mean of a list of numbers. Return `None` if the list is empty.
Use an iterative approach to iterate over the list and update an accumulator variable `sum`. Divide the sum by the length of the list to obtain the mean. | Certainly! Here’s how you can implement the `find_mean` function in Python using an iterative approach to calculate the mean of a list of numbers:
```python
def find_mean(numbers):
# Check if the list is empty
if not numbers:
return None
# Initialize the sum accumulator
sum = 0
# ... | 7,627 |
Here is the implementation of the function using list comprehension with set operations:
```python
def unique_items(list1, list2):
return [item for item in list1 if item not in set(list2)]
```
The `unique_items` function takes two lists as input and returns a list of elements that are present in the first list bu... | Implement a Python function that takes two lists and returns a list of elements that are present in the first list but not in the second. Use a list comprehension with set operations to solve the problem. | You can achieve this by using a list comprehension along with set operations to efficiently find the elements that are in the first list but not in the second list. Here's how you can implement such a function in Python:
```python
def difference_list(list1, list2):
# Convert the second list to a set for faster mem... | 7,628 |
To implement the `version_compare()` function, we can break down the problem into three steps:
1. Tokenize the version strings into tokens.
2. Compare the tokens from left to right.
3. If the integer value of two tokens is the same, the token with fewer periods is considered greater.
Here is the implementation:
```py... | Implement a Python function `version_compare(version1, version2)` that compares two version strings, `version1` and `version2`. The function should return `1` if `version1` is greater than `version2`, `-1` if `version1` is less than `version2`, and `0` if `version1` and `version2` are equal.
A version string is a stri... | Certainly! Below is the implementation of the `version_compare` function, which compares two version strings according to the specified rules:
```python
def version_compare(version1, version2):
# Split both version strings into lists of integers
tokens1 = list(map(int, version1.split('.')))
tokens2 = list(... | 7,629 |
Here's how you could do it:
```python
def filter_dict_keys_by_suffix(input_dict):
filtered_dict = {}
for key, value in input_dict.items():
if key.endswith('_id'):
filtered_dict[key] = value
return filtered_dict
``` | Implement a Python function that takes a dictionary as input and returns a filtered dictionary containing only those keys whose suffix is "_id". The function should:
- Iterate through the items of the input dictionary and filter the keys that end with "_id".
- Create a new dictionary to store the filtered items and ret... | You can create the function as described using a dictionary comprehension to efficiently filter the dictionary keys. Here’s a sample implementation:
```python
def filter_ids(input_dict):
# Use a dictionary comprehension to filter keys that end with '_id'
filtered_dict = {key: value for key, value in input_dict... | 7,630 |
Here is the implementation of this function:
```python
def format_asterisks(n):
if n < 0:
return '<span class="unexpected">*</span>'
if n == 0:
return '<span class="0">*</span>'
if n == 1:
return '<span class="1">*</span>'
if n > 1:
return '<span class="2">*</span>'
``` | Design a Python function that takes an integer `n` and returns a formatted string of `n` asterisks. The string is placed inside an HTML span element with a class based on the number of asterisks: '0' for zero, '1' for one, '2' for two or more, and 'unexpected' for any negative input. For example, the string for `n=5` s... | You can create the desired function in Python by following the given requirements. The function will format the output string based on the value of `n`. Here is how you can implement the function:
```python
def format_asterisks(n):
if n < 0:
class_name = 'unexpected'
asterisks_string = ''
elif ... | 7,631 |
To reverse a string while preserving the pattern of characters, we need to utilize two key concepts:
1. String slicing: We can convert the string into a list of its characters using the `list()` function, then use the built-in `reversed()` function to reverse the list of characters.
2. String concatenation: We can joi... | Write a Python function that takes a string as an argument and returns a string with the same characters in reverse order. However, the pattern of characters should be preserved. For example, given the string "abc123", the output should be "321cba". | To reverse the characters of a given string while preserving the pattern (where letters retain their order and numbers retain their order), we can create a function that separates the characters into letters and digits, reverses each part, and then reconstructs the final string based on the original pattern.
Here's a ... | 7,632 |
To accomplish this task, we can write a function that iterates through the list of strings and uses the Python built-in `len()` function to calculate the length of each string. However, we need to handle any exceptions that may occur during this process and return `None` for any objects that cannot be converted.
Here ... | Write a Python function that takes a list of strings, and returns a list of integers, where each integer represents the length of the corresponding string. The function should handle any exceptions that may occur during this process and return None for any objects that cannot be converted.
Your code should pass the fo... | Here is a Python function that takes a list of strings and returns a list of integers representing the lengths of those strings. The function also handles exceptions and ensures that any items that cannot be converted to strings are replaced with `None`.
```python
def convert_strings_to_lengths(string_list):
lengt... | 7,633 |
Here's how you could do it:
```python
def object_list_to_dict(data):
return {obj.name: obj.value for obj in data}
``` | Write a Python function that takes a list of objects named `data` and returns a new dictionary with keys as the `name` attribute of each object and values as the `value` attribute. The function should support the following assertion:
```python
assert object_list_to_dict(
[object(), object()]
) == {object().nam... | To create the desired function, we first need to ensure that the objects in the list have attributes `name` and `value`. Here is how you can implement the function `object_list_to_dict` and the corresponding assertion:
```python
class CustomObject:
def __init__(self, name, value):
self.name = name
... | 7,634 |
Here's how we can define a Python function to check the label of a document:
```python
def check_label(document: dict) -> bool:
if document.get("label") in ["positive", "negative"]:
return True
else:
return False
```
The function takes in a dictionary as an argument. It checks if the document'... | Set up a Python function to check the label of a given document. The function should return a Boolean value (True or False) based on whether the document is labeled as "positive" or "negative".
The document is stored in a dictionary format, where the label is stored as a string under the key "label".
Here is an examp... | You can create a Python function that checks the label of the document as follows:
```python
def is_document_positive(document):
"""
Check if the document is labeled as 'positive'.
Parameters:
document (dict): A dictionary containing the document content and label.
Returns:
bool: True... | 7,635 |
Here is one way to implement the function using a for loop:
```python
def replace_attributes(attributes: dict, attrs_to_replace: list, new_value: str) -> dict:
for attr in attrs_to_replace:
if attr in attributes:
attributes[attr] = new_value
return attributes
```
You can also use a list co... | Write a Python function that takes a dictionary of attributes and values, and a list of attribute names to replace. The function should replace the values of the replaced attribute names with a new value (e.g., the attribute "height" is replaced with the value "unknown"). | Certainly! Below is a Python function that takes a dictionary of attributes and values, as well as a list of attribute names to replace. The specified attributes' values are replaced with the new value "unknown".
```python
def replace_attributes(attributes_dict, attributes_to_replace):
"""
Replace specified a... | 7,636 |
The goal is to write a Python function that extracts the first two characters from a given string and returns them as a new string. The function should handle various cases, including when the input string is `None`, an empty string, longer than two characters, and shorter than two characters. To acheive this, we can u... | Create a Python function that takes a string as input, extracts the first two characters from the string, and returns them as a new string. The function should handle the following cases:
- If the input string is `None`, it returns an empty string.
- If the input string is an empty string, it returns an empty string.
... | Certainly! Below is a Python function that meets all your specified requirements. The function processes the input string while ensuring to handle all specified cases without using any built-in string functions:
```python
def extract_first_two_characters(input_string):
# Check if the input is None
if input_st... | 7,637 |
Here is an example implementation of the normalization function:
```python
def normalize_array(x):
x_min = x.min()
x_max = x.max()
x_range = x_max - x_min
x_norm = (x - x_min) / x_range
x_uint8 = x_norm.astype(np.uint8)
return x_uint8
``` | Write a Python function to normalize the values of a given NumPy array `x` to be between 0 and 1. You should also convert the type of the elements to `uint8`. | You can normalize a NumPy array to be between 0 and 1 by using the following formula:
\[ \text{normalized\_value} = \frac{x - \text{min}(x)}{\text{max}(x) - \text{min}(x)} \]
After scaling the values, you can convert them to `uint8`. Here’s how to implement this in a Python function:
```python
import numpy as np
de... | 7,638 |
Here is a Python function that implements the described behavior:
```python
def update_model_name(model, model_name):
if not isinstance(model, dict):
raise TypeError("model must be a dictionary")
if "name" in model:
model["name"] = model_name
else:
model["name"] = model_name
ret... | Create a Python function `update_model_name` that takes a data structure `model` and `model_name` string as inputs, and checks if the `model` is a dictionary. If it's not, raise a `TypeError`. If the `model` is a dictionary and has a key `name`, set the value of key `name` to `model_name` and return `True`. If the `mod... | Here's a Python function that adheres to your specifications for updating the model name:
```python
def update_model_name(model, model_name):
# Check if model is a dictionary
if not isinstance(model, dict):
raise TypeError("The model must be a dictionary.")
# Update or add the 'name' key in th... | 7,639 |
To create a Python function that fulfills the instruction, we can follow these steps:
1. Analyze the problem and understand the desired output:
- The function takes a list of modes as input and returns a dictionary that maps each mode to its corresponding color.
- The modes should be mapped to colors according t... | Create a Python function named `map_modes` that takes a list of modes (as strings) and returns a dictionary that maps each mode to its corresponding color (either red or blue). The modes should be mapped as follows:
- `"red"` -> `"red"`
- `"red_yellow"` -> `"red"`
- `"red_yellow_green"` -> `"red"`
- `"yellow"` -> `"bl... | Here's a Python function called `map_modes` that takes a list of modes and returns a dictionary mapping each mode to its corresponding color based on the specifications you provided:
```python
def map_modes(modes):
# Define the mapping of modes to colors
mode_color_mapping = {
"red": "red",
"re... | 7,640 |
To find the parent page of `p` that contains a link to `p`, you can use a recursive function that checks if the current page contains the link and if it doesn't, recursively searches for a parent page that contains the link.
Here's the implementation of the function:
```python
def find_parent_page(page, target_page):... | Given a page `p`, if `p` contains a link to a page `q`, the function should return `q`. On the other hand, if `p` does not contain a link to another page, the function should return `None`.
Write a recursive Python function to find the parent page of `p` that contains a link to `p`. If no such page exists, return `Non... | To solve this problem, we can write a recursive function that checks if the current page contains a link to the target page and, if not, searches through its parents to find one that does. Below is an implementation based on this idea.
We'll assume each `Page` object has the following properties:
- `name`: the name o... | 7,641 |
Here is the implementation:
```python
import hmac
import base64
def validate_hmac_token(string, secret_key, hmac_token):
computed_hmac = hmac.new(secret_key.encode(), string.encode(), 'sha256').digest()
computed_hmac_encoded = base64.b64encode(computed_hmac).decode()
return hmac_token == computed_hma... | Write a Python function to verify the validity of a given HMAC token by comparing it with the computed HMAC value of a given string using a specified secret key.
The function should take three parameters: `string`, `secret_key`, and `hmac_token`. The `hmac_token` should be an encoded string in base64 format. The funct... | You can use the `hmac` and `hashlib` libraries in Python to compute the HMAC value, and the `base64` library to decode the base64-encoded HMAC token. Below is a Python function implementing this verification process:
```python
import hmac
import hashlib
import base64
def verify_hmac(string, secret_key, hmac_token):
... | 7,642 |
Here's how you could implement the `get_random_three_persons` function:
```python
import json
import random
def get_random_three_persons(fpath):
with open(fpath) as json_file:
data = json.load(json_file)
random_elements = random.sample(data, k=3)
random_persons = {}
for i, element in enumerate... | Construct a Python function called `get_random_three_persons`, which takes a JSON file path `fpath` and returns a dictionary containing three random persons from the JSON dictionary, with keys "name", "age", and "country". The JSON file contains a list of dictionaries, where each dictionary contains the keys "name", "a... | To implement the `get_random_three_persons` function, you'll want to follow these steps:
1. Read the JSON file from the provided path.
2. Parse the JSON data to obtain a list of persons.
3. Use the `random` module to select three persons randomly from the list.
4. Return a dictionary containing their details (`name`, ... | 7,643 |
To write a Python function that takes a 2D matrix and a target integer and returns a list of 2-element lists representing the (row, col) indices of cells containing the target integer, you can follow these steps:
1. Define the function `filter_matrix(matrix, target)` with two parameters: `matrix` is a 2D matrix repres... | Write a Python function `filter_matrix(matrix, target)` that takes a 2D matrix of m x n dimensions (a list of lists) and a target integer. The function should return a list of 2-element lists, where each pair represents the (row, col) indices of a cell containing the target integer. The function should handle out-of-ra... | Here is the implementation of the `filter_matrix` function that meets the requirements described:
```python
def filter_matrix(matrix, target):
result = []
# Loop through each row in the matrix
for row_index in range(len(matrix)):
# Loop through each column in the current row
for col_in... | 7,644 |
To write this function, you'll need to use regular expressions to extract the DRM device number from the `device` string. Regular expressions provide a powerful way to parse and extract information from strings.
Here's how you can use regular expressions to parse the `device` string and extract the DRM device number:
... | Write a Python function `get_drm_device_number` that accepts a string `device` and returns the DRM device number. The `device` string is structured as follows:
```
"drm:<i>:<j>:<k>"
```
where `<i>`, `<j>`, and `<k>` represent integers. Your function should parse the string and return the value of `<k>` as an integer.... | To implement the `get_drm_device_number` function, we can use string manipulation techniques to parse the input string in the specified format. We'll check if the string matches the expected pattern and then extract the integer values. Here's a potential implementation:
```python
def get_drm_device_number(device: str)... | 7,645 |
Here's how we can implement this:
```python
def flat_dict_keys(d, prefix=""):
for k, v in d.items():
if isinstance(v, dict):
yield from flat_dict_keys(v, prefix + k + ".")
else:
yield prefix + k
```
In this implementation, we create a generator function `flat_dict_keys` tha... | Write a Python function `flat_dict_keys` that takes a nested dictionary as input and returns a list of keys with all nested levels flattened. The keys in the returned list should be strings that represent the path to the nested value in the original dictionary. For example, given `{'a': {'b': 2, 'c': 3}, 'd': 4}`, the ... | You can achieve this by recursively traversing the nested dictionary and building the paths to each key. Below is a Python function `flat_dict_keys` that implements this logic:
```python
def flat_dict_keys(d, parent_key=''):
items = []
for key, value in d.items():
# Create a new key by adding the curre... | 7,646 |
Here's how you could do it:
```python
def intersects(intervals):
for i in range(len(intervals) - 1):
for j in range(i + 1, len(intervals)):
a, b = intervals[i]
c, d = intervals[j]
if a <= d and c <= b:
return True
return False
```
This function itera... | Given a list of time intervals `intervals` as an input, where each interval is represented by a list of two integers `[start, end]`, write a Python function `intersects` that returns `True` if any two intervals intersect, and `False` otherwise. The function should follow the method name conventions of the Python standa... | To determine if any two intervals intersect, we can follow this approach:
1. Sort the intervals based on their start times.
2. After sorting, we can simply check if the end of the current interval overlaps with the start of the next interval.
3. Two intervals `[a, b]` and `[c, d]` intersect if and only if `b > c`.
H... | 7,647 |
Here's an example implementation of the `compare_and_increment` function:
```python
def compare_and_increment(a, b):
if a >= b:
return a + b
else:
b += 1
return float(b)
```
In this implementation, we use an `if-else` statement to check whether `a` is greater than or equal to `b`. If i... | Implement a Python function `compare_and_increment` that takes two arguments, `a` and `b`, and returns the sum of `a` and `b` if `a` is greater than or equal to `b`. Otherwise, return the incremented `b` as a float.
Your code should pass the following assertions:
```python
assert compare_and_increment(3, 4) == 5.0
ass... | Here is the implementation of the `compare_and_increment` function that meets the specified requirements:
```python
def compare_and_increment(a, b):
if a >= b:
return a + b
else:
return float(b + 1)
# Assertions to check the correctness of the function
assert compare_and_increment(3, 4) == 5.0... | 7,648 |
To solve this problem, let's follow these steps:
1. Define a function `get_dict_with_key_value_pair` that takes a dictionary, a key list, and a value as arguments.
2. Check whether the key list contains a nonexistent key.
3. If the value does not match, raise a `KeyError` exception.
4. If both conditions are not met, ... | Write a Python function `get_dict_with_key_value_pair` that takes a dictionary and two arguments. The first argument is a list of keys to check, and the second argument is a value to check. The function should return a new dictionary containing only those keys and values that match the specified key-value pair. If no s... | Here’s a Python function `get_dict_with_key_value_pair` that meets your specifications:
```python
def get_dict_with_key_value_pair(input_dict, keys, value):
# Check for keys in the input dictionary
for key in keys:
if key not in input_dict:
raise KeyError(f"The key '{key}' does not exist in... | 7,649 |
To implement the function described in the instruction, we can use an `if` statement to check whether the key exists in the dictionary. If the key exists and the value associated with it is not `None`, then the value is returned. Otherwise, `None` is returned.
Here is the Python function that implements this approach:... | Implement a Python function named `check_value` that takes two parameters: `my_dict` and `my_key`. The function should return the value associated with the given key `my_key`. If the key does not exist in the dictionary, the function should return `None`.
```python
def check_value(my_dict, my_key):
if my_key in my... | The function you've provided is close to what you want, but it has a small issue. The condition `my_dict[my_key]` will evaluate to `False` for non-existent keys or if the value is something that evaluates to `False` (like `0`, `False`, or an empty string). Instead, you only need to check if the key exists.
Here’s a co... | 7,650 |
Here's how you could do it:
```python
class SameInputError(Exception):
pass
def my_max(x, y):
if x == y:
raise SameInputError('Two arguments cannot be the same')
elif x > y:
return x
else:
return y
``` | Write a Python function `my_max` that takes two integer inputs and returns the larger one. If they are the same, it should raise an exception with error message `Two arguments cannot be the same`. | You can create the `my_max` function as follows:
```python
def my_max(a, b):
if a == b:
raise ValueError("Two arguments cannot be the same")
return a if a > b else b
# Example usage:
try:
result = my_max(5, 10)
print("The larger number is:", result)
result = my_max(10, 10)
print("... | 7,651 |
You can create a Python function that takes a string representing a percentage and converts it to a floating point number. You can use regular expressions to validate the string and extract the numerical value, and then perform the appropriate calculation to obtain the fractional representation.
Here's how you could d... | I have a string that represents a percentage of the form 'X%' with X being a number between 0 and 100. For example, 50% is represented as '50%'. Write a Python function to convert this string to a floating point number that represents the percentage as a fraction between 0 and 1. For instance, the function should retur... | You can achieve this by creating a function that checks if the string is a valid percentage format and then converts it accordingly. Here's a Python function that does exactly that:
```python
def percentage_to_float(percentage_str):
# Check if the string ends with '%' and is not empty
if not percentage_str or ... | 7,652 |
To recursively traverse a nested container and find all values of a specified key, we can follow a depth-first traversal approach using recursion. The function takes three arguments: `container` (the nested container), `key` (the key to search for), and `path` (a list of keys to resolve the nested structure). The funct... | Write a Python function that traverses a nested container (e.g., dictionary of lists of dictionaries) and returns a list of all values of a specified key. The function takes three arguments: `container` (the nested container), `key` (the key to search for), and `path` (a list of keys to resolve the nested structure). T... | Certainly! Below is a Python function that recursively traverses a nested container (which can be a dictionary, list, or any combination thereof) to find all values associated with a specified key. This function considers the provided `path` to navigate through the nested structure.
```python
def get_values(container,... | 7,653 |
To convert milliseconds to nanoseconds, we multiply `time_milli` by 1,000,000. However, the result may not be an integer, so we need to round it to the nearest integer.
Here is the implementation of the function `convert_milli_to_nano`:
```python
def convert_milli_to_nano(time_milli):
time_nano = round(time_milli... | Create a Python function `convert_milli_to_nano` that takes a single argument `time_milli` that is an integer or float representing time in milliseconds and returns an integer representing time in nanoseconds. The function should round the result to the nearest integer.
For example:
```
>>> convert_milli_to_nano(1.5)... | Here is the Python function `convert_milli_to_nano` that converts milliseconds to nanoseconds:
```python
def convert_milli_to_nano(time_milli):
"""
Convert time from milliseconds to nanoseconds.
Parameters:
time_milli (int or float): Time in milliseconds.
Returns:
int: Time in nanoseconds, ro... | 7,654 |
Here is a Python function that implements Sarrus' Rule to calculate the determinant of a 3x3 matrix:
```python
from typing import List
def determinant_3x3(matrix: List[List[float]]) -> float:
"""
Calculates the determinant of a 3x3 matrix using Sarrus' Rule.
"""
if len(matrix) != 3 or any(len(row) != ... | Define a Python function to calculate the determinant of a 3x3 matrix. This matrix is expressed in the form of a list of lists (a list of rows, where each row is a list of numbers), where the first index represents the row and the second index represents the column.
Use Sarrus' Rule to calculate the determinant of the... | To calculate the determinant of a 3x3 matrix using Sarrus' Rule, we can define a function in Python. Sarrus' Rule simplifies the process for 3x3 matrices and can be summarized as a specific pattern for the products of the elements.
Given a 3x3 matrix:
\[
\begin{bmatrix}
a_{11} & a_{12} & a_{13} \\
a_{21} & a_{22} & a... | 7,655 |
To swap the elements of a tuple, you can use the `+` operator to create a new tuple with the elements in a different order.
Here's an example of how you could implement this function:
```python
def swap_tuple_elements(t):
if len(t) < 2:
return t
else:
return (t[1], t[0]) + t[2:]
```
This func... | Create a Python function `swap_tuple_elements(t)` that takes a tuple `t` as an argument and returns a new tuple where the first and second elements of `t` are swapped. If `t` has fewer than two elements, return `t` unchanged. | You can create the desired function `swap_tuple_elements(t)` as follows:
```python
def swap_tuple_elements(t):
if len(t) < 2:
return t
else:
return (t[1], t[0]) + t[2:]
# Example usage:
print(swap_tuple_elements((1, 2, 3))) # Output: (2, 1, 3)
print(swap_tuple_elements((5, 10))) # Output: ... | 7,656 |
You could use a Python function to read the data file and return a dictionary of student names and their average scores.
Here's how you could do it:
```python
def read_data_file(file_path):
with open(file_path, 'r') as f:
data = [line.strip().split() for line in f.readlines()]
student_scores = {}
... | Write a Python function that reads a data file containing a list of student names and scores. The data file is space-delimited, with the first column being the student name, and the second column being the student's score on an exam.
Your function should read the data file and return a dictionary, where each key is th... | Certainly! Below is a Python function that reads a space-delimited data file containing student names and their scores, calculates the average score for each student, and returns a dictionary where the keys are student names and the values are their average scores.
```python
def read_student_scores(file_path):
sco... | 7,657 |
Here is a Python function that implements this decorator using the `time` and `logging` modules:
```python
import time
import logging
def track_execution_time(logger):
def decorator(func):
def wrapper(*args, **kwargs):
start_time = time.time()
result = func(*args, **kwargs)
... | Write a Python function to implement a decorator that prints the execution time of the original function every time it is called. The decorator should take an additional `logger` argument to specify the logger object to use for logging. Use the `logging` module to log the execution time. | Certainly! You can implement a decorator that logs the execution time of a function using the Python `logging` module. Below is an example of how to create such a decorator that takes a `logger` as an argument:
```python
import logging
import time
from functools import wraps
def log_execution_time(logger):
"""
... | 7,658 |
To implement a function that returns the value of a key in a dictionary, we can use the `get` method of the dictionary. The `get` method takes a key as an argument and returns the associated value, or `None` if the key is not in the dictionary. If a default value is provided, it will be returned instead of `None` if th... | Write a Python function `get_string_from_dict(dict, key)` that returns the value of the given `key` in a dictionary. If the given `key` is not in the dictionary, return an empty string. The function should provide documentation for its inputs and outputs. | Certainly! Below is a Python function `get_string_from_dict` that retrieves a value from a dictionary using a provided key. If the key is not found, it returns an empty string. The function includes appropriate documentation for its inputs and outputs.
```python
def get_string_from_dict(d: dict, key: str) -> str:
... | 7,659 |
To compute the SHA-256 hash of a file, you can use the `hashlib` module in Python. This module provides functions for computing hash values of different algorithms, including SHA-256.
Here's how you can write a Python function to compute the SHA-256 hash of a file:
```python
import hashlib
def sha256_file(filename):... | Write a Python function `sha256_file` that computes the SHA-256 hash of a file by reading it as a byte stream. You can use the `hashlib` module to perform the hashing. Document the function's purpose, its input arguments, and the expected output format.
Your code should pass the following test case:
```python
expected... | You can compute the SHA-256 hash of a file in Python using the `hashlib` module. Below is the implementation of the `sha256_file` function, including documentation for its purpose, input arguments, and expected output format.
```python
import hashlib
def sha256_file(file_path):
"""
Computes the SHA-256 hash o... | 7,660 |
Here's one way to implement the function:
```python
def arithmetic_series_sum(n):
total = 0
for i in range(1, n + 1):
term = (i * (i + 1)) // 2
total += term
return total
```
In this implementation, we use the arithmetic series formula to calculate the sum of consecutive integers from 1 to... | Write a Python function that takes a positive integer `n` as input and returns the sum of the first n terms of the arithmetic progression 1, 1+2, 1+2+3, 1+2+3+4, 1+2+3+4+5, ...
Your code should pass the following assertions:
```python
assert arithmetic_series_sum(1) == 1
assert arithmetic_series_sum(4) == 20
assert ar... | To solve this problem, we need to understand the pattern of the arithmetic progression given in the prompt. The sequence of sums can be broken down as follows:
- The 1st term is the sum of the first 1 natural number: \(1\)
- The 2nd term is the sum of the first 2 natural numbers: \(1 + 2 = 3\)
- The 3rd term is the su... | 7,661 |
Here's my implementation of the function in Python:
```python
def type_checker(arg):
if arg is None:
return "None"
elif arg is True or arg is False:
return "boolean"
elif isinstance(arg, int):
return "integer"
elif isinstance(arg, str):
return "string"
else:
... | Design a Python function that takes a single argument and returns the string "boolean" if the argument is a boolean, "integer" if the argument is an integer, or "string" if the argument is a string. If the argument is `None`, return the string "None". If the argument is `True` or `False`, return the string "boolean". H... | You can implement the function as follows:
```python
def type_checker(arg):
if arg is None:
return "None"
elif isinstance(arg, bool):
return "boolean"
elif isinstance(arg, int):
return "integer"
elif isinstance(arg, str):
return "string"
else:
return "unknown... | 7,662 |
Here's how you can implement the steps in Python:
```python
def calculate_max_tiles(n):
num_cells = n * n
num_tiles = num_cells // 4
return num_tiles
```
In Step 1, we calculate the total number of cells in the grid by multiplying the number of rows (n) by the number of columns (n).
In Step 2, we calcul... | Assume we have an NxN square grid of cells, and we want to split it into smaller 2x2 squares. We can do so by placing a "tile" on the grid. A tile can be placed on a cell if that cell is not already covered by a tile, and it does not overlap with any other tile.
Your task is to write a Python function to calculate the... | To solve the problem of placing the maximum number of 2x2 tiles on an NxN grid, we can start by analyzing the constraints of the problem. A 2x2 tile occupies 4 cells in the grid. Thus, the number of tiles we can place will depend on how many complete 2x2 blocks fit within the dimensions of the NxN grid.
Here's a strai... | 7,663 |
```python
import torch
def extract_red_channel(image: torch.Tensor) -> torch.Tensor:
assert image.dim() == 3 and image.shape[-1] == 3, "Expected image tensor of shape (H, W, 3)"
H, W, _ = image.shape
red_channel = torch.zeros(H, W, 1)
for i in range(H):
for j in range(W):
red_chan... | Write a Python function `extract_red_channel` that takes a tensor of shape `(H, W, 3)` representing an image in RGB format and returns a tensor of shape `(H, W, 1)` representing the red channel of the image. The function should:
- Create a tensor `red_channel` of shape `(H, W, 1)`.
- Loop over the image tensor `image`... | You can implement the `extract_red_channel` function as follows. The function will create a new tensor for the red channel, and then will copy the red values from the input image to this new tensor. Here's how you can do it:
```python
import numpy as np
def extract_red_channel(image):
# Get the shape of the input... | 7,664 |
Here's a Python function that solves this problem using list comprehension:
```python
def unique_count_with_list_comprehension(lst):
return len([x for x in set(lst) if x is not None])
``` | Write a Python function `unique_count_with_list_comprehension` that returns the number of unique elements in a list, while simultaneously eliminating duplicates. Here's how you can approach it:
Define a function that takes a list as an argument.
Use a list comprehension to create a new list with unique elements.
You c... | You can implement the `unique_count_with_list_comprehension` function as described in your request. The function will take a list as an argument, convert it to a set (to eliminate duplicates), convert it back to a list, and finally return the length of this list. Below is the implementation of the function and the asse... | 7,665 |
You can create a Python function that accepts a single argument `obj` and returns a list containing `obj`. If `obj` is already a list, return it as-is. Otherwise, return a list containing `obj`.
Here's how you could do it:
```python
def ensure_list(obj):
if isinstance(obj, list):
return obj
elif isins... | Develop a Python function `ensure_list` that accepts a single argument `obj` and returns a list containing `obj`. If `obj` is already a list, return it as-is. Otherwise, return a list containing `obj`. Raise an `Exception` if `obj` is not a list or a single object (e.g., a string or an integer). | Certainly! Below is the implementation of the `ensure_list` function according to your specifications:
```python
def ensure_list(obj):
# Check if obj is already a list
if isinstance(obj, list):
return obj
# Check if obj is a single object (not a list)
elif isinstance(obj, (str, int, float, bool... | 7,666 |
```python
import subprocess
from unittest.mock import Mock
mock_subprocess_run = Mock()
def process_files(path, extensions):
for file in os.listdir(path):
if file.endswith(extensions):
file_path = os.path.join(path, file)
subprocess.run(["command", file_path, "-o", f"{file_path}.pro... | Create a Python function `process_files` that takes a directory path and a list of file extensions. Your function should run a subprocess command to process all files with the given extensions within that directory. The command should take in the file path and output the result of the processing to a new file with the ... | Certainly! Below is a Python implementation of the `process_files` function, which processes files in a given directory with specified extensions using a subprocess command. Additionally, I will provide a unit test utilizing the `unittest.mock` module to simulate the subprocess command's behavior.
### Implementation o... | 7,667 |
Here is a Python function that implements this approach:
```python
import json
import os
from typing import Optional
def rescale_coordinates(
input_file: str,
output_file: str,
*,
x_scale: Optional[float] = None,
y_scale: Optional[float] = None,
) -> None:
"""
Rescales the x and y coordina... | Design a Python function that takes a JSON input file path, a JSON output file path, and two optional keyword arguments `x_scale` and `y_scale`. The function should rescale the x and y coordinates of the input file by the provided factors `x_scale` and `y_scale`. The output file should be a new JSON file containing the... | Certainly! Below is a Python function that meets the requirements you specified. It reads from a JSON input file, rescales the x and y coordinates by optional scaling factors, and writes the result to a new JSON output file.
```python
import json
from typing import Optional, List, Dict, Any
def rescale_coordinates(
... | 7,668 |
To write a Python function that generates HTML code based on a list of strings, you can use a list comprehension to build the HTML code. This approach allows you to use Python's built-in string formatting capabilities to create a bulleted list.
Here is a Python function that implements this approach:
```python
from t... | Write a Python function named `post_to_html` that takes a list of strings and returns a string that contains HTML code that displays the strings in the list in a bulleted list format. The function should use Python type hinting to specify the types of the input and output parameters. You can assume that the input list ... | Here’s a Python function named `post_to_html` that fulfills the requirements specified. It takes a list of strings as input and returns a string containing the corresponding HTML for a bulleted list.
```python
def post_to_html(items: list[str]) -> str:
# Use a list comprehension to generate the list items
list... | 7,669 |
We can use bit manipulation to compute the ceiling of `n / 2**b` without using division, floating-point operations, built-in functions like `math.ceil`, or converting it into computing the floor.
Here's a Python function that uses bit manipulation to compute the ceiling of `n / 2**b` without using division, floating-p... | Develop a Python function that computes the ceiling of `n / 2**b` without using division, floating-point operations, built-in functions like `math.ceil`, or converting it into computing the floor. Instead, use bit manipulation to compute the result. The function should include assertions to ensure both `n` and `b` are ... | Certainly! To compute the ceiling of `n / 2**b` using bit manipulation, we can leverage the fact that `2**b` is a power of two, which means we can achieve this operation using right shifts.
We can express the ceiling function mathematically:
- If `n` is perfectly divisible by `2**b`, then `ceil(n / 2**b) = n / 2**b`.... | 7,670 |
Here's how you can implement this function:
```python
def map_values_to_range(dictionary):
new_dictionary = {}
for key, value in dictionary.items():
if not 0 <= value <= 100:
value = min(max(value, 0), 100)
new_dictionary[key] = value
return new_dictionary
```
This function ite... | Write a Python function that takes a dictionary as input and returns a new dictionary with all values in the original dictionary that are between 0 and 100. For values outside this range, map the values to the closest bound (either 0 or 100). The function should maintain the original key-value mappings if they satisfy ... | Certainly! Below is a Python function that implements the described logic. The function takes a dictionary as an argument and returns a new dictionary where all values are adjusted to make sure they fall within the range of 0 to 100. If the original value is less than 0, it is set to 0, and if it is greater than 100, i... | 7,671 |
Here is a Python function that implements this approach:
```python
def grid_indices(orbital_indices):
"""
Calculates the grid indices for a given orbital index or list of orbital indices.
The grid index is the integer division of the orbital index by 2.
"""
if isinstance(orbital_indices, list):
... | Write a Python function to calculate the single-particle grid indices given the spin-less model for qubit indexing. The function should also accept a list of orbital indices and return the corresponding grid indices, where each grid index is the integer division of the orbital index by 2.
Your code should pass the fol... | To create a Python function that calculates the single-particle grid indices given a list of orbital indices, we need to follow the rules outlined in the problem statement. Specifically, each orbital index is converted to a grid index by performing integer division by 2.
Below is the implementation of the `grid_indice... | 7,672 |
To check whether a given dictionary key exists and convert its value to a string if it does, we can use a for loop to iterate through the dictionary's keys. If the key exists, we create a new dictionary with the same key and its value converted to a string. If the key doesn't exist, we create a new dictionary without t... | Write a Python function to check whether a given dictionary key exists, and if it does, return a dictionary with the same key and its value converted to a string. If the key doesn't exist, return a dictionary without the key. The function should be robust to handle different data types.
Your code should pass the follo... | You can create a function called `check_dict_key` to achieve the desired functionality. The function will take two parameters: a dictionary and a key. It will check if the key exists in the dictionary, and if it does, it will return a new dictionary with the key and its value converted to a string. If the key doesn't e... | 7,673 |
Here's how you can implement the function:
```python
def get_key_value_pairs(dictionary, keys):
return {key: dictionary.get(key) for key in keys}
``` | I have a dictionary containing the following information:
```python
{
'1': 'name',
'2': 'age',
'3': 'height',
'4': 'weight'
}
```
I would like to write a function that takes in the dictionary above and a list of keys (e.g., `['1', '4']`) and returns a new dictionary containing the corresponding key-va... | You can achieve this by defining a function that takes the dictionary and a list of keys as arguments. The function will then create a new dictionary that contains only the key-value pairs corresponding to the specified keys. Here's an example of how you can implement this:
```python
def filter_dict(input_dict, keys):... | 7,674 |
Here's how you could implement the `rewrite_url` function:
```python
import re
def rewrite_url(url):
hostname_pattern = r"^https?://www\.amazon\.(co\.jp|com)/"
rewritten_url = re.sub(hostname_pattern, "https://www.amazon.com.cn/", url)
return rewritten_url
```
This implementation uses the `re.sub` funct... | Write a Python function named `rewrite_url` that takes a URL string as input and rewrites the hostname part of the URL to be redirected to a different domain.
For instance, if the input is `https://www.amazon.com/dp/B0792J8QW3`, the function should return `https://www.amazon.com.cn/dp/B0792J8QW3`.
In addition, if the... | You can achieve this by using the `urlparse` and `urlunparse` functions from the `urllib.parse` module in Python. These functions allow you to easily parse a URL into its components and then reconstruct it after making modifications.
Here’s how the `rewrite_url` function can be implemented:
```python
from urllib.pars... | 7,675 |
To sum the tuples in each list, you can iterate through the tuples in each list. For each tuple in each list, you can add the elements in the same position and create a new tuple with the resulting sum.
You can implement this function in Python as follows:
```python
def sum_tuples_in_lists(list1, list2):
result =... | Write a Python function that takes two arguments: `list1` and `list2`, both of which are lists of tuples. The function should return a list of tuples that represent the sum of each tuple in `list1` and `list2`. You can assume that both lists are the same length and each tuple is the same length.
Here's an example of i... | You can implement the function `sum_tuples_in_lists` as follows. This function will iterate through both lists, summing the corresponding tuples element-wise. Here's how you can write the function:
```python
def sum_tuples_in_lists(list1, list2):
# Use a list comprehension to sum the tuples element-wise
return... | 7,676 |
Here is the Python implementation of the `find_missing_number_in_sequence` function:
```python
def find_missing_number_in_sequence(sequence):
number_set = set(sequence)
expected_range = set(range(min(sequence), max(sequence) + 1))
difference = expected_range - number_set
return difference.pop()
``` | Create a Python function named `find_missing_number_in_sequence` that finds the missing number in a sequence of numbers.
Input: A list of numbers in the form `[1,2,3,4,6,7,8,9]`.
Output: The missing number in the sequence. In this case, it's `5`. | Sure! You can create a function named `find_missing_number_in_sequence` that receives a list of numbers and finds the missing number in the sequence.
Here’s a simple implementation of this function:
```python
def find_missing_number_in_sequence(numbers):
# Calculate the expected sum of the complete sequence
n... | 7,677 |
Here's a possible implementation:
```python
def print_printables(s):
printable_chars = []
for char in s:
ascii_code = ord(char)
if 32 <= ascii_code <= 126:
printable_chars.append(char)
return ''.join(printable_chars)
``` | Implement a Python function `print_printables` that takes a string `s`, and return a string of all printable characters from `s`, without using the built-in `string.printable` constant. This function should not ignore characters that appear multiple times in `s`.
Your code should pass the following assertions:
```pyth... | To implement the `print_printables` function, we need to identify which characters are considered printable. The printable characters in ASCII are those that have a character code in the range from 32 (space) to 126 (tilde `~`).
We can approach this by iterating through each character in the input string `s`, checkin... | 7,678 |
```python
def lists_have_common_number(lst1, lst2):
return any([num in lst1 for num in lst2])
``` | Write a Python function to check if two lists have at least one number in common. Return `True` if they do, else `False`. Solve this in one line of code using list comprehension. | You can use the `any()` function in conjunction with a list comprehension to check if there is at least one number in common between the two lists. Here's a one-liner function that accomplishes this:
```python
def have_common_element(list1, list2):
return any(elem in list2 for elem in list1)
```
You can use this ... | 7,679 |
To convert a hexadecimal string to a binary string, we need to understand the relationship between hexadecimal and binary numbers. In hexadecimal, each digit represents a number in the base 16 system, with digits 0-9 representing the numbers 0-9 and letters A-F representing the numbers 10-15. To convert a hexadecimal n... | Write a Python function that converts a hexadecimal string to a binary string, where each hexadecimal character is represented by 4 bits in the binary string. The function should handle uppercase and lowercase letters in the hexadecimal string. The fixed-size binary string should be zero-padded on the left if the numbe... | Certainly! Below is a Python function that converts a hexadecimal string to a binary string as described in your requirements. The function handles both uppercase and lowercase hexadecimal characters and produces a zero-padded binary string.
```python
def hexadecimal_to_binary(hex_string):
# Convert the hexadecima... | 7,680 |
To write the function, you need to iterate through the given list and count the occurrences of the given item. If the item is not in the list, return 0. The function should have the specified signature.
Here's how you can implement the `get_count` function:
```python
def get_count(lst, item):
counter = 0
for ... | Write a Python function `get_count` that takes a list and counts the occurrences of the given item. If the given item is not in the list, return 0. The function should have the following signature:
```python
def get_count(lst, item):
"""
Counts the number of occurrences of an item in a list.
Parameters:
... | You can implement the `get_count` function by using the `count` method that lists in Python provide. Below is the implementation based on the specified signature:
```python
def get_count(lst, item):
"""
Counts the number of occurrences of an item in a list.
Parameters:
lst (list): The list to sear... | 7,681 |
To sort a list of tuples by the values of a specified key, we can use the `sorted` function in Python, which takes a list and a key function as arguments. The key function is used to extract a value from each element of the list, and the elements are sorted based on this value.
To access the values of the specified ke... | Write a Python function that takes a list of tuples as input and returns a list of tuples sorted by the values of the specified key. You may assume that the key will always be an integer.
Your code should pass the following test case:
```python
tuples = [('A', 10), ('B', 2), ('C', 8)]
sorted_tuples = sort_tuples_by_ke... | You can implement the function `sort_tuples_by_key` which takes a list of tuples and an index key, and returns a new list of tuples sorted based on the values at the specified index. Here's how you can do it:
```python
def sort_tuples_by_key(tuples_list, key_index):
return sorted(tuples_list, key=lambda x: x[key_i... | 7,682 |
Here's a simple solution to the problem:
```python
def check_async_gen(obj):
return isinstance(obj, (collections.abc.AsyncGenerator, types.AsyncGeneratorType))
``` | Write a Python function `check_async_gen(obj)` that checks whether a given object is an asynchronous generator or not. The function should return `True` if the object is an asynchronous generator, and `False` otherwise. | To check if an object is an asynchronous generator in Python, you can make use of the built-in `inspect` module, specifically the `inspect.isasyncgen` function. This function will return `True` if the object is an asynchronous generator, otherwise it will return `False`.
Here is the implementation of the `check_async... | 7,683 |
To calculate the quantiles of a list of numbers, we can use the Numpy library and its quantile() function. The quantile() function takes a list of numbers as an input and returns a list of quantiles at the specified percentiles.
```python
import numpy as np
def calculate_quantiles(numbers):
quantiles = np.quantil... | Calculate the quantiles of a given list of numbers. | To calculate the quantiles of a given list of numbers, you'll need to follow these steps:
1. **Sort the List**: Arrange the numbers in ascending order.
2. **Determine the Quantile**: Decide which quantiles you want to calculate. Common quantiles include quartiles (which divide data into four equal parts), percentiles... | 7,684 |
To read a text file and count the number of words starting with each alphabet, you can use the following steps:
1. Read the text file line by line to extract all words.
2. Convert each word to lowercase and extract the first letter using the `str.lower()` and `str[0]` methods.
3. Use a dictionary to count the occurren... | Create a Python function to read a text file and count the number of words starting with each alphabet (a-z). The function should return a list of tuples in the format `(alphabet, count)`, where `alphabet` is the first letter of a word and `count` is the number of words starting with that letter. | Certainly! Below is a Python function that reads a text file and counts the number of words starting with each letter of the alphabet (from 'a' to 'z'). The function returns a list of tuples containing the alphabet letter and its corresponding count.
```python
import string
from collections import defaultdict
def cou... | 7,685 |
To solve this problem, you can use a dictionary comprehension and the `zip()` function to iterate over the keys and values of the original dictionary and create a new dictionary for each language.
Here is the implementation:
```python
def match_languages(dictionary):
return [{language: word for language, word in ... | Given a language-specific dictionary where each key is a unique language and the value is a list of unique words or phrases in that language, write a Python function that matches each key-value pair and returns a list of dictionaries, where each dictionary has the original language as the key and the unique words or ph... | You can achieve this by iterating over the given dictionary and creating a new list of dictionaries, where each dictionary contains the language as the key and its associated words or phrases as the value. Here's how you can implement this in Python:
```python
def language_to_dicts(language_dict):
result = []
... | 7,686 |
You can create a Python function that takes a fixed number of parameters and returns a formatted string using the f-string format.
Here's how you could do it:
```python
def string_formatter(num, name, value):
return f"name: {name}, num: {num}, value: {value}"
``` | Write a Python function to create a simple string formatter that accepts a fixed number of parameters (e.g., `num, name, value`) and returns a string in the following format:
```
"name: {name}, num: {num}, value: {value}"
``` | You can create a simple string formatter function in Python using formatted string literals (also known as f-strings) or the `format()` method. Below is a function that accepts three parameters: `num`, `name`, and `value`, and returns the string in the specified format.
Here's an implementation using f-strings:
```py... | 7,687 |
Here is the implementation of the `convert_bytes_to_mb` function:
```python
def convert_bytes_to_mb(num_bytes: int) -> int:
assert num_bytes > 0, "The input must be a positive integer"
bytes_in_mb = 1024 ** 2
megabytes = num_bytes // bytes_in_mb
return megabytes
``` | Given a function `convert_bytes_to_mb` to convert the input number of bytes to megabytes. This function should use integer division, so the remaining bytes are lost and not rounded. The input number of bytes should be a positive integer.
Your code should pass the following assertions:
```python
assert convert_bytes_to... | To create the `convert_bytes_to_mb` function that converts bytes to megabytes using integer division, you can define the function as follows:
```python
def convert_bytes_to_mb(bytes):
# There are 1,048,576 bytes in one megabyte (MB).
return bytes // 1_048_576
```
This function uses the `//` operator, which pe... | 7,688 |
Here is the implementation of the function:
```python
import pandas as pd
def extract_unique_ids(df):
if not isinstance(df, pd.DataFrame):
raise ValueError("Input must be a pandas DataFrame.")
if 'id' not in df.columns or 'status' not in df.columns:
raise ValueError("Input DataFrame must have ... | Write a Python function that takes a pandas DataFrame as input and returns a list of all unique values in the 'id' column of the DataFrame. The function should also drop rows where the 'id' column has a null value or the 'status' column is not equal to 'active'.
You are expected to use DataFrame indexing to access spe... | To achieve this task, we will create a function that filters the DataFrame based on the specified conditions and then extracts unique values from the 'id' column. Below is the implementation in Python using the `pandas` library:
```python
import pandas as pd
def get_unique_active_ids(df):
# Drop rows where the 'i... | 7,689 |
Here's a simple solution that uses the `endswith` method:
```python
def validate_suffix(string):
return string.endswith('_list')
```
In this implementation, we use the `endswith` method to check if the string ends with `_list`. If it does, the method returns `True`, otherwise it returns `False`. | Write a Python function to validate whether a given string ends with the suffix `_list`. If it does, return `True`, otherwise return `False`.
Your code should pass the following assertions:
```python
assert validate_suffix('test') == False
assert validate_suffix('test_list_list') == True
assert validate_suffix('test_l... | You can implement the function `validate_suffix` as follows:
```python
def validate_suffix(s):
return s.endswith('_list')
# Testing the function with the provided assertions
assert validate_suffix('test') == False
assert validate_suffix('test_list_list') == True
assert validate_suffix('test_list') == True
```
Th... | 7,690 |
Here's how you can implement a `memoize` function:
```python
import collections
class Memoize:
def __init__(self, func, cache_size=20):
self.func = func
self.cache = collections.OrderedDict()
self.cache_size = cache_size
def __call__(self, *args, **kwargs):
key = (args, str(kw... | Write a Python function `memoize` that takes a function as an argument and returns a new function that is identical to the original function, except that it caches the results of previous calls to that function. The cache should be able to store an arbitrary number of results, and should evict the least-recently used r... | To create a Python function `memoize` that caches results of function calls, we can use a dictionary to store the results of previous calls. To ensure that we can evict the least-recently used (LRU) items from the cache when it reaches its maximum capacity, we can use the `collections.OrderedDict`. It allows us to main... | 7,691 |
To find the first match of a regular expression pattern in a string of text, we can use the `re` module in Python. The `re.search()` method takes a regex pattern and a string as arguments, and returns a `re.Match` object if a match is found, or `None` if not. By iterating through the matches using a `for` loop, we can ... | Write a Python function named `find_first_match` that takes two arguments: `text`, a string of text, and `pattern`, a regular expression pattern. The function should return the first matching substring as a string if found, or an empty string if not found. Perform input validation to ensure both arguments are non-empty... | To create the `find_first_match` function, we will use the `re` module, which provides support for regular expressions in Python. The function will validate the inputs to ensure that both `text` and `pattern` are non-empty strings. If they pass the validation, the function will search the `text` for the first occurrenc... | 7,692 |
Here is the implementation of the Python function that takes a string representing a time duration and returns the sum of the duration's seconds, minutes, hours, and days as an integer:
```python
import re
def time_duration_to_seconds(time_duration: str) -> int:
pattern = r"(?P<days>\d+d)?\s*(?P<hours>\d+h)?\s*(?... | Write a Python function that takes a string representing a time duration and returns the sum of the duration's seconds, minutes, hours, and days as an integer. The function should handle a variety of time formats, such as "1d 1h 1m 1s", "1d 1h1m1s", "1h1m1s", "1h1m", etc. The function should return 0 if the time durati... | You can achieve this by using regular expressions to parse the time duration string. We'll write a function that matches each time unit (days, hours, minutes, seconds) and calculates the total in seconds. Here's how you could implement this:
```python
import re
def parse_time_duration(duration):
# Define the rege... | 7,693 |
Here is the implementation of the `linear_scale` function in Python:
```python
import numpy as np
def linear_scale(X, min_val, max_val):
X_min = np.min(X)
X_max = np.max(X)
X_scaled = (X - X_min) / (X_max - X_min)
return X_scaled
```
In this implementation:
- `X_min` and `X_max` are calculated using... | Write a Python function named `linear_scale` to perform linear scaling on a feature matrix `X` with a given minimum and maximum value. The function should return the scaled matrix `X_scaled`.
The linear scaling transformation is defined as:
$$
X_{scaled} = \frac{X - X_{min}}{X_{max} - X_{min}}
$$
Here, $X$ is the or... | Certainly! You can define the `linear_scale` function in Python to perform linear scaling as described. I'll provide the implementation below, using NumPy for matrix operations:
```python
import numpy as np
def linear_scale(X):
"""
Perform linear scaling on the feature matrix X to the range [0, 1].
Param... | 7,694 |
Here's how we can implement this:
```python
from xml.etree import ElementTree
def extract_xml_values(xml_doc):
root = ElementTree.fromstring(xml_doc)
values = {}
for element in root.iter():
values[element.tag] = element.text
return values
``` | Write a Python function to extract the values of the XML elements in a given XML document, where each element has a name and a value. The function should return a dictionary with the element name as the key and the value as the corresponding value. | You can use Python's built-in `xml.etree.ElementTree` module to parse XML documents and extract the values of the elements. Below is a function that takes an XML string as input and returns a dictionary where the keys are the names of the XML elements and the values are the corresponding text content of those elements.... | 7,695 |
To write a Python function that takes two lists of equal length, and returns a list of tuples, where each tuple contains the corresponding elements from the two lists, we need to ensure that the lists are indeed the same length.
To achieve this, we can leverage the `try-except` block to handle the potential case when ... | Write a Python function `tuple_from_lists(list1, list2)` that takes two lists of equal length, and returns a list of tuples. Each tuple should contain the corresponding elements from the two lists. If the two lists are not the same length, raise a custom exception `UnequalLengthError`.
For example, if `list1 = [1, 2, ... | To accomplish the task, you'll need to define a custom exception called `UnequalLengthError`. Then, you can create the function `tuple_from_lists` that checks if the two input lists have the same length and raises the custom exception if they do not. Finally, if they are of equal length, the function will create a list... | 7,696 |
Here's how you can write a Python function that extracts the sum of a column from a pandas dataframe:
```python
import pandas as pd
def sum_of_column(dataframe, column_name):
assert column_name in dataframe.columns, "Column does not exist in the dataframe"
assert dataframe[column_name].dtype == 'int64' or dat... | Write a Python function to extract the sum of a specific column from a pandas dataframe, where the column name is specified as a string argument. You should ensure that the dataframe contains the specified column and the values in the column are numeric.
Your code should pass the following test case:
```python
df = pd... | You can create a function `sum_of_column` that takes a pandas DataFrame and a column name as arguments. The function will check whether the specified column exists in the DataFrame and whether its data type is numeric. If both conditions are met, it will return the sum of the column. Here's the implementation:
```pyth... | 7,697 |
Here is the implementation of the function:
```python
def two_sum_gte(values, threshold):
left = 0
right = len(values) - 1
while left < right:
sum_value = values[left] + values[right]
if sum_value >= threshold:
return True
elif sum_value < threshold:
left +=... | Write a Python function that takes two arguments, `values` and `threshold`, and returns `True` if there are any two values in the `values` collection that sum up to a value greater than or equal to `threshold`. Otherwise, return `False`. The function must iterate over the collection only once. You can assume the input ... | To solve this problem, we can use a two-pointer technique, which allows us to efficiently check for pairs of values that meet the criteria of having a sum greater than or equal to the `threshold`. Since the input is sorted, we can take one pointer starting at the beginning of the list and the other pointer starting at ... | 7,698 |
Here's how you can implement this function using `getattr` and `AttributeError`:
```python
def access_missing_attr(obj, attr_name, default):
try:
return getattr(obj, attr_name, default)
except AttributeError:
return default
```
The `getattr` function accepts three arguments: the object, the na... | Write a Python function to access a missing attribute on an object, returning a default value instead of raising an `AttributeError`. The function should take three arguments: `obj`, the object to access, `attr_name`, the name of the attribute to access, and `default`, the default value to return if the attribute does ... | You can create a function that uses Python's built-in `getattr` function to access an attribute on an object while providing a default value to return in case the attribute is missing. Here's a Python function that accomplishes this:
```python
def safe_getattr(obj, attr_name, default):
"""
Access an attribute ... | 7,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.