response_seed stringlengths 53 5.17k | instruction_seed stringlengths 29 4.02k | response stringlengths 16 8.81k | __original_row_idx int64 0 50k |
|---|---|---|---|
To count the number of consecutive numbers in a file, we can use regular expressions to find all the consecutive numbers in each line of the file, and then count them using file I/O and line-by-line processing to avoid loading the entire file into memory.
The following is an implementation of `number_of_numbers_in_fil... | Develop a Python function `number_of_numbers_in_file` that counts the number of consecutive numbers in a given file. The function should take a file path as input and return an integer as output. Use regular expressions to find consecutive numbers in each line of the file and count them. You should also use file I/O an... | To create the `number_of_numbers_in_file` function, we'll utilize Python's file I/O capabilities along with the `re` module for regular expressions. The function will read the file line by line, using a regex pattern to find all occurrences of consecutive numbers within each line. We'll then keep a total count of these... | 3,100 |
To perform this check in a single line of code, you can use the `getattr` function and the `and` operator in Python. The `getattr` function allows you to retrieve an attribute from an object, and the `and` operator evaluates expressions from left to right and returns the first falsy value or the last expression if all ... | I want to check if a `User` object has the `is_staff` attribute, and if it does, I want to check if its `is_active` attribute is true. I want to write this check in a single line of code, and if either attribute doesn't exist, I want to return false. | You can perform the checks using the `getattr` function to safely access the attributes of the `User` object. This way, if either attribute does not exist, it will return `False`. Here’s how you can do this in a single line:
```python
is_staff_active = getattr(user, 'is_staff', False) and getattr(user, 'is_active', Fa... | 3,101 |
Here's how you can implement this:
```python
def count_item(data, item):
count = 0
first_index = None
last_index = None
for index, value in enumerate(data):
if value == item:
count += 1
if first_index is None:
first_index = index
last_index... | Write a Python function to display the number of times a specific item appears in a list. For example, if the list is [1, 2, 2, 1, 3] and the item is 2, the function should print "2 appears 2 times in the list starting at index 1 and ending at index 2".
The function should support any list and any item. | You can achieve this by writing a function that counts the occurrences of a specific item in the list and identifies the first and last index of its occurrences. Below is a Python function that implements this logic:
```python
def display_item_count(lst, item):
count = lst.count(item)
if count == 0:
... | 3,102 |
To check if an object is a positive integer or a negative integer, we can first check if it is an integer using the `isinstance` function. Then, we can check if it is greater than or equal to 1 (positive integer) or less than or equal to -1 (negative integer) using the `<=` and `>=` operators.
Here is a possible imple... | Write a Python function to check whether an object is a positive integer or a negative integer. Your function should return `True` if the object is an integer and its value is greater than or equal to 1 (positive integer) or less than or equal to -1 (negative integer), otherwise return `False`.
Your code should pass t... | You can create the function `is_positive_or_negative_integer` to check if the input object is a positive or negative integer as specified. Here's how you can implement this function:
```python
def is_positive_or_negative_integer(obj):
# Check if obj is an instance of int and is either
# a positive integer (>=... | 3,103 |
Here is the implementation:
```python
def unique_chars(string):
characters = set()
for char in string:
characters.add(char)
return characters
``` | Write a function that takes a string and returns a set of all characters that occur in that string (e.g., `'12233444'` -> `{'1', '2', '3', '4'}`). You can use the built-in `set` type, but not any string methods.
Your code should pass the following test case:
```python
test_strings = ["1234", "12233444", "abcde", "Hell... | You can create a function `unique_chars` to accomplish this task. Below is a sample implementation that utilizes a `set` to collect unique characters from the input string without using any string methods:
```python
def unique_chars(s):
char_set = set() # Initialize an empty set to store unique characters
for... | 3,104 |
The function can be implemented using a `for` loop to iterate through the list of controllers. At each iteration, the function can check if the current controller requires a power flow calculation. If any controller requires a power flow calculation, the function can return `True`, indicating that at least one controll... | Write a Python function `needs_powerflow` that takes a list of power system controllers, and determines whether any of them require an initial power flow calculation. The function should iterate through the list in order, and return `True` if any of the controllers require a power flow, or `False` if none of them do.
... | Certainly! Below is a Python function named `needs_powerflow` that takes a list of power system controllers. It checks if any controller requires an initial power flow calculation. To minimize control flow operations, the implementation uses a loop to find the first controller that requires power flow and returns `True... | 3,105 |
Here's how you could implement the function:
```python
from numpy import nan
def check_nan_or(x, y=None, default=False):
if x is nan or x is None or x == y:
return True
else:
return default
```
This function checks whether `x` is `NaN`, `None`, or equal to `y`. If any of these conditions are ... | Implement a Python function `check_nan_or` that takes three arguments: `x`, `y`, and `default`, and returns `True` if `x` is `NaN` or `x` is `None` or `x` is equal to `y`, and returns `default` otherwise.
Provide default values for `y` and `default`:
```python
def check_nan_or(x, y=None, default=False):
...
```
... | To implement the function `check_nan_or`, we will make use of the `math.isnan()` function to check if the value of `x` is `NaN`, and we will also check for `None` and equality with `y`. If none of these conditions are met, we will return the specified `default` value.
Here's the implementation:
```python
import math
... | 3,106 |
To partition a list into two parts, you need to select a random `k` index to divide the list into two parts. The first part will contain the elements from the start of the list up to the `k` index, and the second part will contain the remaining elements.
Here's how you could implement the `partition_list` function:
`... | Write a Python function `partition_list` that takes a list and partitions it into two parts. The function should return a tuple containing the two resulting lists. The first part should have a length of `k`, where `k` is a random integer between 0 and `len(lst) - 1`, inclusive. The second part should contain the remain... | To implement the `partition_list` function, we can use the `random` library to generate a random integer for `k`. The function will then return a tuple containing two lists: the first list containing the first `k` elements of the input list, and the second list containing the remaining elements. Here's how we can do th... | 3,107 |
Here's a Python implementation that uses duck typing for the dictionary and list arguments:
```python
def check_keys(dictionary, list_of_strings):
if dictionary is None or len(dictionary) == 0:
raise ValueError("Dictionary is invalid.")
if list_of_strings is None or len(list_of_strings) == 0:
r... | Write a Python function that accepts a dictionary and a list of strings as arguments, and checks if all the strings in the list are keys in the dictionary. Return a list of booleans indicating whether each string is in the dictionary as a key.
Your function should support any type of container for the dictionary and l... | You can create the function `check_keys` that accepts any dictionary-like and list-like structures. The function will use duck typing to ensure that it works with any types that support the required methods. Here’s how you can implement this:
```python
def check_keys(dictionary, keys):
# Using a list comprehension... | 3,108 |
To accomplish this task, we need to create a function that takes a function `f` and a variable number of arguments. This function should return an iterator that yields the result of composing `f` with each of its arguments.
Here's how we can implement this:
```python
def compute_compositions(f, *args):
for arg in... | Write a Python function `compute_compositions(f, *args)` that takes a function `f` and a variable number of arguments. It returns an iterator that yields the composition of `f` with each of its arguments.
For example, writing `list(compute_compositions(lambda x: x**2, 1, 2, 3))` should return `[1, 4, 9]`. | To create the function `compute_compositions(f, *args)` that computes the composition of the function `f` with each of its arguments, we can define the function to yield the result of applying `f` to each argument in `args`. This can be easily achieved using a generator in Python.
Here's the implementation of the `com... | 3,109 |
Here's how you can implement this function using string formatting and regular expressions:
```python
import re
def convert_snake_case_to_camel_case(string: str) -> str:
string = re.sub(r'^_', '', string)
words = string.split('_')
words[0] = words[0].lower()
for i in range(1, len(words)):
word... | Build a Python function that takes a string in `snake_case` and converts it into `camelCase`. If the string starts with an underscore, remove the underscore as well. Note that the function should handle other potential special cases for string conversion, such as `PascalCase`, `kebab-case`, `Capitalized Case`, etc. Use... | To create a Python function that converts a string from `snake_case` to `camelCase`, while also handling special cases like `PascalCase`, `kebab-case`, and your specific rules (e.g., removing leading underscores), we can use regular expressions for pattern matching and string manipulation. Below is the implementation o... | 3,110 |
Here's how you could do it:
```python
import datetime
def is_valid_date_string(string):
try:
datetime.datetime.strptime(string, '%Y-%m-%d')
return True
except ValueError:
return False
```
This function uses the `datetime.datetime.strptime()` method, which takes a date string and a for... | Write a Python function to check if the given string is a valid date string in the format `YYYY-MM-DD`. The function should return `True` if the given string is a date string, `False` if it is not, and raise an exception if the input is not a string. | You can achieve this by using the `datetime` module in Python, which provides functionality to work with date and time. Here is a function that checks if a given string is a valid date string in the format `YYYY-MM-DD`:
```python
from datetime import datetime
def is_valid_date(date_string):
if not isinstance(date... | 3,111 |
```python
def get_origin_name(repo_url, branch_name):
if repo_url.lower().endswith(".git") and branch_name.lower() == "master":
return "origin"
elif not repo_url.lower().endswith(".git") and branch_name.lower() == "master":
return "github"
elif branch_name.lower() != "master" and repo_url.lo... | Design a Python function that takes a Git repository URL and a branch name and returns the remote origin name according to the following logic (case insensitive):
- If the repository URL ends with ".git", then the origin name is "origin".
- If the repository URL does not end with ".git", then the origin name is "githu... | You can implement the logic described in a Python function. Below is a Python function `get_origin_name` that takes a Git repository URL and a branch name as input, applies the specified rules, and returns the calculated origin name:
```python
def get_origin_name(repo_url: str, branch_name: str) -> str:
# Normaliz... | 3,112 |
Here's how you can do it in Python:
```python
def integer_to_binary_string(num):
bit_string = ''
while num > 0:
bit_string = str(num % 2) + bit_string
num //= 2
return bit_string
``` | Write a Python function to convert an integer into a string with only the digits '0' and '1', where the index of each digit corresponds to its place value, starting from the least significant bit. To do this, repeatedly apply integer division by 2 using `//` to retrieve the next digit from the right, and take the modul... | You can create a Python function `integer_to_binary_string` that converts an integer to its binary representation using only the digits '0' and '1'. Below is the implementation of this function:
```python
def integer_to_binary_string(n):
if n == 0:
return '0' # Edge case for zero
binary_string = ''
... | 3,113 |
To extract the domain name from a URL with subdomains, we can use regular expressions to match the pattern of a URL, including the subdomains. We can then extract the domain name from the matched groups using the `.group()` method.
```python
import re
def extract_domain(url):
pattern = r"^https?://(?:\w+\.)*(\w+)... | Write a Python function to extract the domain name from a URL, including subdomains. If the URL does not have a domain name, the function should return an empty string. If the URL is invalid (does not start with 'http://' or 'https://'), the function should raise an exception. | You can create a Python function that extracts the domain name from a given URL, checks if the URL is valid, and handles cases where there is no domain name. Below is a function that meets your requirements:
```python
from urllib.parse import urlparse
def extract_domain(url):
# Check if the URL starts with 'http:... | 3,114 |
Here's how we can implement this function:
```python
def format_report(report_name, repo_name, pull_request_id):
if report_name == 'pull_request_report':
return f"Report for {repo_name} PR #{pull_request_id}"
elif report_name == 'pipeline_report':
return f"Report for {repo_name} pipeline #{pull... | Write a function `format_report` that takes in a `report_name`, `repo_name`, and `pull_request_id` as arguments and returns a formatted string. If the `report_name` is `pull_request_report`, then the string should be formatted as the following:
```
Report for {repo_name} PR #{pull_request_id}
```
If the `report_name`... | Below is the implementation of the `format_report` function based on your specifications:
```python
def format_report(report_name, repo_name, pull_request_id):
if report_name == 'pull_request_report':
return f'Report for {repo_name} PR #{pull_request_id}'
elif report_name == 'pipeline_report':
... | 3,115 |
Here is a Python function that implements this approach:
```python
def multiply_keys_values(dictionary):
"""
Multiplies all keys and values in a dictionary by 2x and 4x respectively.
"""
result = {}
for key, value in dictionary.items():
if isinstance(value, dict):
result[key * 2... | Create a function that takes a dictionary as input and returns a new dictionary with each key multiplied by 2x and each value multiplied by 4x. The function should be able to handle nested dictionaries recursively. | To create a function that takes a dictionary as input and returns a new dictionary with each key multiplied by `2x` and each value multiplied by `4x`, we need to handle both the nesting of dictionaries and ensure that the operations on keys and values are performed correctly. In Python, keys in dictionaries need to be ... | 3,116 |
To solve this problem, we can use the built-in `ord()` function to get the integer ordinal of each character in the string. Then, we can use Python's formatting capabilities to convert the ordinal value to a hexadecimal string. We can store the hexadecimal strings in a list and return it as the final result.
```python... | Write a Python function to take the string 'Hello, world' as an input, and return a list of hex values representing the characters in the string. | You can create a Python function to convert each character in the string `'Hello, world'` to its corresponding hexadecimal value. Here’s how you would do it:
```python
def string_to_hex(input_string):
# Create a list of hex values for each character in the input string
hex_values = [hex(ord(char))[2:] for char... | 3,117 |
```python
import re
def convert_path(path):
invalid_chars_regex = re.compile(r"[^\w\-_./]")
converted_path = invalid_chars_regex.sub("_", path).lower()
return converted_path
```
This implementation uses regular expressions to match and replace invalid characters in the path string with underscores and th... | Write a Python function that takes a path string and returns the path string with all characters in lowercase and any invalid characters replaced with an underscore.
For example, the path `/Users/Alice/Documents/My Docs.txt` should be converted to `/users/alice/documents/my_docs.txt`. | You can achieve this by creating a function that processes the path string, converting all characters to lowercase and replacing any invalid characters with an underscore. In this context, we can consider invalid characters to be any characters that are not alphanumeric, a forward slash, or an underscore.
Here's how y... | 3,118 |
Here is a Python implementation of the `get_value_with_fallbacks` function:
```python
def get_value_with_fallbacks(d: dict, keys: list) -> object:
"""
Returns the value in d corresponding to the first key in keys that exists in d.
If no matching key is found, returns None.
"""
for key in keys:
... | Write a Python function `get_value_with_fallbacks` that takes a dictionary `d` and a list of keys `keys`. The function should iterate through the keys in order and return the first value in `d` that corresponds to a key that exists in the dictionary. If no matching key is found, the function should return `None`. Here ... | You can create the function `get_value_with_fallbacks` as described. The function will iterate through the provided list of keys and return the corresponding value from the dictionary if the key exists. If none of the keys are found, it will return `None`. Below is the implementation:
```python
def get_value_with_fall... | 3,119 |
To decompose a 4x4 transformation matrix into a rotation matrix and a translation matrix, you can first extract the rotation matrix from the upper-left 3x3 submatrix, and then extract the translation vector from the last column of the original 4x4 matrix.
Here's how you could do it:
```python
import numpy as np
def ... | I want to write a Python function to decompose a 4x4 transformation matrix into a rotation matrix and a translation matrix. The rotation matrix will be represented by a quaternion, and the translation matrix will be represented by a 3x1 matrix. The input matrix should be a numpy array, and the output matrices should al... | To decompose a 4x4 transformation matrix into a rotation matrix (represented by a quaternion) and a translation vector, you can follow these steps:
1. Extract the translation vector from the last column of the transformation matrix.
2. Extract the rotation part of the matrix (the top-left 3x3 submatrix).
3. Convert th... | 3,120 |
Here is the implementation of the function:
```python
import re
def capitalize_first_letter(string: str) -> str:
pattern = r"\b(\w)"
return re.sub(pattern, lambda match: match.group().upper(), string)
``` | Create a Python function that takes a string as input and returns the same string with the first character of each word capitalized. Use regular expressions to handle cases where the first character is not a letter. For example, the function should return `"Hello World"` if given `"hello world"`. | You can achieve this by using Python's `re` module to handle regular expressions. The function will find the first character of each word and capitalize it, while ensuring that it handles cases where the first character isn't a letter. Here's a Python function that accomplishes this:
```python
import re
def capitaliz... | 3,121 |
Here's how you can implement this function:
```python
def parse_byte_data(input_dict):
output_dict = {}
for key, value in input_dict.items():
new_dict = {}
new_dict['value'] = value.decode('utf-8')
if key == 'header_data':
new_dict['data_type'] = 'header_data_type'
... | Create a Python function that takes a dictionary containing byte data as input and returns a dictionary of header data as output. The input dictionary looks something like this:
```
{
'header_data': b'Some header data',
'other_data': b'Something else',
}
```
The output dictionary should be of the form:
```
{
... | Certainly! Below is a Python function that processes the input dictionary of byte data and returns the desired output dictionary, adhering to the specified structure. In this example, I've provided placeholder values for `data_type`, `data_type_description`, and `data_type_references`. You can modify these values accor... | 3,122 |
```python
def byte_to_hex(bytes_str):
return ":".join(f"{b:x}" for b in bytes_str)
``` | Write a Python function `byte_to_hex(b: bytes) -> str` that converts a byte string to a colon-delimited hex string representation. It should work for any "bytes-like" object. Here is an example:
```python
byte_to_hex(b"hello") == "68:65:6c:6c:6f"
byte_to_hex(b"world") == "77:6f:72:6c:64"
byte_to_hex(b"hello world") ==... | You can create a Python function `byte_to_hex` that converts a bytes-like object to a colon-delimited hex string representation. Here's how you can implement this function:
```python
def byte_to_hex(b: bytes) -> str:
# Generate the hex strings for each byte and join them with colons
return ':'.join(f'{byte:02x... | 3,123 |
To implement the `serialize_json` function, we first need to understand the structure of a JSON string. A JSON string is a serialized representation of a Python object that contains its data and type information. It consists of key-value pairs, where the keys are strings and the values can be different types such as `i... | Develop a Python function `serialize_json` that takes a Python object and returns a JSON string. The function should support the following types:
- `int`
- `str`
- `bool`
- `list`
- `dict`
Your function should handle type-safe serialization, ensuring that only the specified types are serialized and others are handled... | Sure! Below is a Python function `serialize_json` that takes a Python object and returns a JSON string. It handles the specified types (`int`, `str`, `bool`, `list`, `dict`) and returns `None` for unsupported types:
```python
import json
def serialize_json(obj):
if isinstance(obj, (int, str, bool)):
# Dir... | 3,124 |
To parse an IP address and CIDR mask from a string in the format "10.25.130.193/29", we need to understand the structure of the IP address and CIDR mask.
An IP address is a 32-bit number represented as four decimal numbers separated by periods. Each decimal number represents an octet (8 bits) of the address. CIDR stan... | I want a function that parses the following format: `10.25.130.193/29` into an IP address and CIDR mask (e.g., 10.25.130.193/29 is an IP address of 10.25.130.193 and a CIDR mask of 29) and validates that the IP address and CIDR mask are valid. The function should return True if the input is valid and False otherwise.
... | To achieve the task of parsing the IP address and CIDR mask from the input format and validating them, we can implement the following function. This function will utilize the `ipaddress` module available in Python, which provides a straightforward way to validate IP addresses and CIDR notations.
Here's the implementat... | 3,125 |
The function should process each log file in the list of paths and return a list of strings representing the file names of log files that match the given file path. If the file is empty or is the same as the file specified by the file path string, it should be skipped.
Here's how we can implement this:
```python
impo... | Design a Python function that takes a string representing a file path and a list of strings representing a list of file paths. The function should process each log file in the list of paths and return a list of strings representing the file names of log files that have the same content. For example, if `log_path_file1.... | To achieve the desired functionality, we'll create a Python function that takes a string representing a file path and a list of strings representing a list of file paths. The function will read the content of each log file, compare it with the content of the specified file, and return a list of file names of the log fi... | 3,126 |
To create a Python function that evaluates a conditional statement in the global scope of the current script, you can use the `eval()` built-in function to evaluate the statement and the `globals()` function to get the global namespace. Then, you can use the `if` statement to check if the evaluated statement is `True` ... | Create a Python function named `eval_condition` that takes a string representing a conditional statement and evaluates it in the global scope of the current script. If the statement evaluates to `True`, return the string `True`; otherwise, return `False`.
Your code should pass the following assertions:
```python
asser... | You can create the `eval_condition` function using the built-in `eval` function in Python, which can evaluate a string as a Python expression. Here's how you can implement the function:
```python
def eval_condition(condition_str):
# Evaluate the condition and convert it to string for return
result = eval(condi... | 3,127 |
Here is how you could implement a function to add two matrices:
```python
def add_matrices(matrix1, matrix2):
if len(matrix1) != len(matrix2) or any(len(row) != len(matrix1[0]) for row in matrix2):
raise ValueError("Invalid matrices: dimensions do not match.")
sum_matrix = [[0] * len(row) for row in ma... | Write a Python function `add_matrices` to add two matrices (2D lists of numbers), where the function should expect two arguments: a list of rows and a list of columns, both of which will be integers. The function should raise a `ValueError` if the matrix is not valid. If the matrix is valid, the function should return ... | Here's a Python function `add_matrices` that takes two matrices as input and returns their sum. The function checks whether the matrices are valid (i.e., they have the same dimensions) and raises a `ValueError` if they are not. If they are valid, it uses list comprehensions to calculate the sum of the two matrices.
``... | 3,128 |
To solve this problem, you can use the built-in `int()` function and specify the `base` argument to convert the string to a hexadecimal number. You can also use a regular expression to check if the string has a 0x prefix and remove it before converting.
Here's one possible implementation:
```python
def convert_hex_to... | Write a Python function to convert a string of hexadecimal digits to a decimal number. The function should take a string `s` as input and return an integer. The string may represent a hexadecimal number with a 0x prefix (e.g., '0x1A'), or it may not (e.g., '1A').
For example, `convert_hex_to_decimal('0x1A')` should re... | You can create a Python function to convert a hexadecimal string to a decimal number by using the built-in `int` function with base 16. Here's how you can implement it:
```python
def convert_hex_to_decimal(s: str) -> int:
# Strip the '0x' prefix if it exists
if s.startswith('0x'):
s = s[2:]
# ... | 3,129 |
To write a Python function `stringify_list(lst)` that converts a list of strings to a string with the elements separated by commas, you can follow these steps:
1. Check if the list contains only a single element. If it does, return the element as a string.
2. Check if the list is empty. If it is, return an empty strin... | Write a Python function `stringify_list(lst)` that converts a list of strings to a string with the elements separated by commas. If the list contains only a single element, the function should return the element as a string. If the list is empty, the function should return an empty string. You can assume that the input... | You can achieve the desired functionality by using the `join` method in Python. This method allows you to concatenate a list of strings into a single string with a specified separator, which in this case would be `', '`. Below is the implementation of the `stringify_list` function:
```python
def stringify_list(lst):
... | 3,130 |
```python
def column_means(matrix):
num_rows = len(matrix)
num_cols = len(matrix[0])
means = [0] * num_cols
for i in range(num_cols):
col_sum = 0
for j in range(num_rows):
col_sum += matrix[j][i]
means[i] = col_sum / num_rows
return means
```
This implementation ... | Write a function to calculate the mean of each column in a matrix. The matrix is stored as a 2D array or list of lists. The function should return a list containing the mean of each column. | Certainly! Below is a Python function that calculates the mean of each column in a given 2D list (matrix). The function will return a list containing the means of each column.
```python
def calculate_column_means(matrix):
if not matrix or not matrix[0]:
return []
# Number of columns
num_cols = len... | 3,131 |
Here is the implementation:
```python
import base64
def decode_base64_string(input_string):
try:
return base64.b64decode(input_string).decode('utf-8')
except Exception:
return ''
```
In this implementation:
- `import base64`: This imports the `base64` module.
- `def decode_base64_string(input... | Write a Python function `decode_base64_string(input_string)` that takes a base64-encoded string and returns the decoded string. The function should catch any exceptions and return an empty string if any exception occurs. The function should assume that the input string is valid and correctly formatted.
Your code shoul... | Here’s a Python function `decode_base64_string` that decodes a base64-encoded string. It handles exceptions and returns an empty string if an error occurs during the decoding process.
```python
import base64
def decode_base64_string(input_string):
try:
# Decode the base64 string and convert bytes to a UTF... | 3,132 |
To solve this problem, we can first iterate over the list of objects and build a dictionary that maps each type to a list of names. We can use a `defaultdict` from the `collections` module to handle cases where an object has a type that is not present in the dictionary. If an object has a type that is already present i... | Write a Python function that takes a list of objects (each with a `.name` and `.type` attribute) as input and returns a dictionary that maps each type to a list of names. If an object has a type that is already present in the dictionary, add its name to the list for that type. If an object has a type that is not presen... | Here is a Python function that accomplishes the task you described. This function takes a list of objects and organizes them into a dictionary that maps types to lists of names. It also includes error handling for attribute access issues, and it returns an empty dictionary if the provided list is empty:
```python
def ... | 3,133 |
Here's how you can do it in one line of Python code:
```python
def return_non_duplicates(input_list):
return [num for num in input_list if input_list.count(num) == 1]
``` | Design a Python function `return_non_duplicates` that takes a list of numbers and returns a list of unique numbers, where each number appears only once. This function should be written in one line of code.
The function should use set comprehension to create a set of unique numbers and then return a list from that set,... | You can create the `return_non_duplicates` function using a one-liner that utilizes set comprehension and the `count` method to filter out the non-duplicate numbers. Here's the implementation:
```python
def return_non_duplicates(numbers):
return [n for n in set(numbers) if numbers.count(n) == 1]
# Assertions to t... | 3,134 |
To find variables in a given scope, you can use the following steps:
1. Identify the `scoperef` object: First, you need to identify the `scoperef` object. This object contains the scope information and variable mappings.
2. Traverse the `scoperef` object: Starting from the `scoperef` object, recursively traverse its p... | Write a Python function, `find_variables_in_scope`, that returns a list of variables in a given scope. The function should recursively traverse the `scoperef` object and look up the variables associated with a given scope name. | To create a Python function that extracts variables from a scope specified by a name in a `scoperef` object, we'll assume that `scoperef` is a dictionary or similar structure where scopes are represented as keys, and the values contain either variable definitions or nested scopes. The function will recursively traverse... | 3,135 |
To determine if a given name is unique, we can check if it exists in a list of existing names. We can use a `set` or a `dict` to store the names for efficient lookups, and then check if the given name is already in the set or dict.
Here's how we can implement this in Python:
```python
def validate_name(name, existing... | Create a function in Python that validates a given name against a list of existing names. You can assume the input name is a valid Python identifier that can be used as a function or variable name. Your function should return `True` if the name is unique and `False` if it is a duplicate.
Your code should pass the foll... | You can create a simple function to validate a name against a list of existing names in Python. Here's how you can do it:
```python
def validate_name(name, existing_names):
"""Check if the given name is unique compared to the existing names."""
return name not in existing_names
# Test cases
existing_names = [... | 3,136 |
By using the `Fibonacci` class, we can compute each Fibonacci number efficiently and store the results in the `_cache` dictionary to avoid repeated computations. We can also use the `_cache` to speed up the computation of subsequent Fibonacci numbers.
```python
class Fibonacci:
def __init__(self):
self._ca... | Design a Python function to efficiently sum up the first N Fibonacci numbers using the following class:
```python
class Fibonacci:
def __init__(self):
self._cache = {}
def compute_fib(self, n):
# Compute the nth Fibonacci number and cache it for future use
if n in self._cache:
... | You can create a function that uses the provided `Fibonacci` class to compute and sum the first `N` Fibonacci numbers efficiently. Since the Fibonacci numbers are calculated recursively and cached, the function won't recompute the same Fibonacci numbers multiple times.
Here’s how you can do it:
```python
class Fibon... | 3,137 |
To detect and remove duplicate sublists from a list of lists, we can iterate over the list and compare each sublist with the rest of the sublists in the list. We can use a set to store the unique sublists we have seen so far, and for each sublist, we can check if it is already in the set. If it is not, we can add it to... | Develop a Python function `remove_duplicate_lists` that takes a list of lists and removes any duplicate sublists from it. The function should return a new list containing the original items, but without any duplicate sublists. | Certainly! To remove duplicate sublists from a list of lists in Python, you can use a combination of a set to track seen items and a list to compile the final result. Below is an implementation of the `remove_duplicate_lists` function:
```python
def remove_duplicate_lists(lst):
seen = set()
result = []
... | 3,138 |
Following your instruction, here's a Python function named `create_elem` that generates a `<div>` element with a given content, and optionally sets the `display` property:
```python
from xml.etree import ElementTree as ET
def create_elem(content: str, is_visible: bool = True) -> ET.Element:
"""
Create a <div>... | Create a Python function named `create_elem` to generate a `<div>` element with a given content. The function should take two parameters: `content` and `is_visible`. If `is_visible` is `True`, append the `style="display: block;"` attribute to the `<div>` element. Otherwise, append the `style="display: none;"` attribute... | You can create the `create_elem` function in Python as follows. This function accepts `content` and `is_visible` as parameters and generates a `<div>` element with the appropriate style attribute based on the visibility.
Here's the complete function:
```python
def create_elem(content: str, is_visible: bool) -> str:
... | 3,139 |
Here's how you can implement this:
```python
def compare_string_to_list(string, string_list):
if not isinstance(string_list, list):
raise ValueError("The input list is not a list.")
if string in string_list:
return True
return False
```
This implementation checks if the input list is a li... | Create a Python function that takes in a string and a list of strings as input and compares the string to each string in the list. If the string is a part of the list, return `True`. If the string is not a part of the list, return `False`. Use `isinstance` to check if the input list is a list. If it is not a list, rais... | Certainly! Below is a Python function that meets your requirements. It checks if a given string is present in a provided list of strings and properly handles cases where the list input is not a list.
```python
def is_string_in_list(input_string, string_list):
# Check if string_list is indeed a list
if not isin... | 3,140 |
To create the list of tuples containing the names of two students of the same gender, we can iterate over the list of dictionaries and use a dictionary to track the gender of each student. For each student, we can check if they have the same gender as any other student we've seen so far. If so, we can add a tuple conta... | Design a Python function named `create_pairs` that takes a list of dictionaries containing students' data, where each dictionary has the fields `name`, `age`, and `gender`, and returns a list of two-element tuples, where each tuple contains the names of two students of the same gender.
For example, given the following... | To implement the `create_pairs` function, we will follow these steps:
1. Categorize the students based on their gender.
2. For each gender category, generate all the possible pairs of students.
3. Return the list of pairs.
Here is the implementation of the function:
```python
def create_pairs(students):
from ite... | 3,141 |
```python
import re
def replace_template(string, template):
pairs = re.findall(r"(\w+):(\w+)", string)
values = {key: value for key, value in pairs}
return template.format_map(values)
``` | Given a string containing a list of key-value pairs (e.g., "name:John, age:25, gender:male, location:New York"), as well as a corresponding template string (e.g., "My name is {name}, and I am {age} years old."), write a Python function to output the final string by replacing the template placeholders with the correspon... | You can achieve this by creating a function that first parses the key-value pairs from the input string, then replaces the placeholders in the template string with the corresponding values. Below is the implementation:
```python
def fill_template(data_string, template):
# Split the data string into key-value pairs... | 3,142 |
To create the `add_numbers` function, we can use the `pad_to_n` function to pad each number to a length of 10 before adding them.
Here is the implementation of the `add_numbers` function:
```python
def add_numbers(num_a, num_b):
padded_a = pad_to_n(str(num_a), 10)
padded_b = pad_to_n(str(num_b), 10)
retur... | I have a function `pad_to_n(text, n)` (n should be an integer) that returns a string padded or truncated to a length of n, with spaces used to pad or truncate.
I want to write a function `add_numbers(num_a, num_b)` that takes two numbers as input and returns the sum of those numbers, with each number padded to 10 char... | To achieve the desired functionality, we can implement the `add_numbers` function, which will take two numbers as input, use the `pad_to_n` function to pad each number to 10 characters, and then compute the sum.
Here is the code that includes both the `pad_to_n` function and the `add_numbers` function:
```python
def ... | 3,143 |
Here's how you can implement this:
```python
def format_array_with_brackets(arr):
if len(arr) == 0:
return ""
if len(arr) == 1:
return f"[{arr[0]}]"
return f"[{', '.join(map(str, arr))}]"
```
This implementation uses the `len` function to check the length of the input array. If the length ... | Develop a Python function `format_array_with_brackets` that takes an array as an input and returns a string with the elements enclosed in brackets and separated by commas. If the input array is empty, the function should return an empty string. If the input array contains only one element, the output should have the el... | You can achieve the desired functionality by implementing the `format_array_with_brackets` function as described. Here's the implementation:
```python
def format_array_with_brackets(arr):
if not arr:
return ""
return "[" + ", ".join(map(str, arr)) + "]"
# Test assertions
assert format_array_with_brack... | 3,144 |
```python
def is_within_tolerance(a, b, tol, tol_type):
within_tolerance = False
if tol_type == "relative":
relative_diff = abs(a - b) / b # Relative difference
within_tolerance = relative_diff <= tol
elif tol_type == "absolute":
absolute_diff = abs(a - b)
within_tolerance =... | Create a Python function `is_within_tolerance` that takes four arguments: `a`, the actual value; `b`, the expected value; `tol`, the tolerance amount; and `tol_type`, the type of tolerance to use (either `'relative'` or `'absolute'`). The function should return `True` if the tolerance condition is satisfied, and `False... | Here's a Python function named `is_within_tolerance` that checks whether the actual value is within the specified tolerance of the expected value, depending on the type of tolerance specified (either relative or absolute):
```python
def is_within_tolerance(a, b, tol, tol_type):
"""
Check if 'a' is within toler... | 3,145 |
To extract the sum of all `span` elements' inner text from a given HTML string, you can use a regular expression to match all `span` elements and extract their inner text. Then, you can use a loop to iterate over each match and calculate the sum of all `span` elements' inner text.
Here is a Python function that implem... | Write a Python function to return the sum of all `span` elements' inner text in a given HTML string. | To sum the inner text of all `<span>` elements in a given HTML string, you can use the `BeautifulSoup` library from the `bs4` package, which makes it easy to parse HTML content. Here's a Python function that accomplishes this:
```python
from bs4 import BeautifulSoup
def sum_span_text(html_string):
# Parse the HTM... | 3,146 |
To refactor the code, you need to address several issues:
1. The conditional `if-elif` statements can be combined into a single `if-elif-else` block.
2. The long conditional expression can be split into multiple lines with proper indentation.
3. The logic in the `else` branch can be extracted into a separate function ... | Here is a Python function:
```python
def get_color(color):
if color == 'red':
color_code = 0xFF0000
elif color == 'green':
color_code = 0x00FF00
elif color == 'blue':
color_code = 0x0000FF
else:
raise ValueError('Invalid color')
return color_code
```
However, this f... | Here is the refactored version of the `get_color` function based on the specified approach:
```python
def get_color(color):
if color in ('red', 'green', 'blue'):
color_code = (
0xFF0000 if color == 'red' else
0x00FF00 if color == 'green' else
0x0000FF
)
else:... | 3,147 |
Here is the Python code to solve this problem:
```python
def product_of_lists(lists):
return [prod(lst) for lst in lists]
def prod(lst):
return 1 if not lst else lst[0] * prod(lst[1:])
```
The `product_of_lists` function takes a list of lists of integers as input and returns a list of their product using the... | Given a list of lists of integers, your task is to return a list of the product of all integers in each list. Each list has at least one element.
Your code should pass the following assertion:
```python
assert product_of_lists([[1, 2, 3, 4], [5, 6], [7, 8, 9]]) == [24, 30, 504]
``` | You can achieve the desired functionality by defining a function `product_of_lists` that takes a list of lists as input and returns a list containing the product of the integers in each list. Here's how you can implement this:
```python
def product_of_lists(lists):
products = []
for sublist in lists:
p... | 3,148 |
Here is the implementation of `find_missing_keys` using set operations:
```python
def find_missing_keys(dict_1, dict_2):
set_1 = set(dict_1.keys())
set_2 = set(dict_2.keys())
return list(set_1 - set_2)
``` | Define a Python function `find_missing_keys(dict_1, dict_2)` that takes two dictionaries as inputs and returns a list of keys that are present in `dict_1` but not in `dict_2`.
For example, if `dict_1 = {'a': 1, 'b': 2, 'c': 3}` and `dict_2 = {'b': 2, 'c': 3, 'd': 4}`, the function should return `['a']`.
You can assum... | Certainly! Below is a Python function named `find_missing_keys` that takes two dictionaries as input and returns a list of keys that are present in the first dictionary but not in the second.
```python
def find_missing_keys(dict_1, dict_2):
# Use a list comprehension to find keys in dict_1 that are not in dict_2
... | 3,149 |
Here's an example implementation:
```python
import random
def create_random_points(n):
points = []
for _ in range(n):
x = random.uniform(0, 100)
y = random.uniform(0, 100)
point = (x, y)
points.append(point)
return points
```
In this implementation, we use the `random.unif... | Write a Python function `create_random_points(n)` that generates `n` random points in a two-dimensional space. The points should be represented as tuples containing two floating-point coordinates (x, y), where both x and y are in the range of [0, 100]. The function should return a list of these points.
Your code shoul... | To create a function that generates `n` random points in a two-dimensional space, we can use the `random` module from Python's standard library. The `random.uniform(a, b)` function will allow us to generate floating-point numbers in the specified range.
Here’s how to implement the `create_random_points(n)` function:
... | 3,150 |
To transform strings into tab-separated values, we can first split the input string into rows using the `splitlines()` method, and then split each row into columns using the `split()` method. We can then join each row using the `join()` method with a tab character ('\t') as the delimiter, and then join all rows using t... | Write a Python function that takes a string of comma-separated values, parses it into a list of lists, and then transforms it into a string of tab-separated values. The function should preserve the first row of the input string and add a tab character before each subsequent row. | Here is a Python function that accomplishes the task of transforming a string of comma-separated values into a string of tab-separated values, while preserving the first row and adding a tab character before each subsequent row.
```python
def transform_csv_to_tsv(input_string):
# Split the input string into lines
... | 3,151 |
To extract and manipulate the first 4 bits of a byte, you can use bitwise operations. You can shift the bits of the input byte left by 4 to move the first 4 bits to the right, and then use bitwise and (&) to set the last 4 bits to 0.
Here's how you can do it in Python:
```python
def extract_and_manipulate(byte):
... | Write a function to extract, manipulate, and store the first 4 bits of a given byte, such that the resultant byte has the first 4 bits set to zero (0) and the remaining 4 bits set to the values of the first 4 bits of the original byte. For example, the function should return 0x00 if the input is 0b00011010 (0x1A in hex... | To achieve the manipulation of the first 4 bits of a byte and store the result as specified, we can follow these steps:
1. Extract the first 4 bits of the byte.
2. Construct a new byte where the first 4 bits are set to 0, and the last 4 bits are the same as the extracted bits.
Here's a Python function that performs t... | 3,152 |
To represent each integer as a character in a string, we can use a Python function that takes a list of integers and returns a string with a sequence of characters based on each integer's sequence number in the list. The function should begin with the letter 'a' and continue with the next letter after 'z', wrapping bac... | Create a Python function that takes a list of integers, and returns a string with a sequence of characters representing each integer in the list, where each character is an alphabetical representation of that integer's sequence number in the list. The function should begin with the letter 'a' and continue with the next... | You can achieve this by creating a function that maps each integer to a corresponding character based on its index in the list. You can use the modulus operation to wrap around the alphabet when the index exceeds 25 (the number of letters in the English alphabet). Here is an implementation of such a function:
```pytho... | 3,153 |
To write a function to convert a slice object to a list of integers, we need to consider the following:
- The `slice` object provides access to the `start`, `stop`, and `step` attributes, which represent the beginning index, ending index (exclusive), and the step size, respectively.
- The function should return an empt... | Write a Python function to convert a slice object to a list of integers. The input is a slice object `slice_obj`, and the output is a list `int_list`. If the slice object represents a step, the function should initialize `int_list` to the range of integers from the slice's `start` to the `stop` value (exclusive) increm... | You can create a Python function to convert a slice object into a list of integers according to the specified rules. Below is the implementation of such a function:
```python
def slice_to_int_list(slice_obj):
# Extract start, stop, and step from the slice object
start = slice_obj.start if slice_obj.start is no... | 3,154 |
Here's a sample implementation of the decorator:
```python
import functools
import threading
def auto_thread_local_storage(func):
storage = threading.local()
@functools.wraps(func)
def wrapper(*args, **kwargs):
if isinstance(func, classmethod):
return func(*args, **kwargs)
if... | Implement a Python decorator that automatically creates thread-local storage for a function's return value. The decorator should work with both regular functions and class methods. You can use the `threading.local` class to create thread-local storage. | To implement a Python decorator that creates thread-local storage for a function's return value, we can utilize the `threading.local` class. This class allows us to store data that is unique to each thread, making it suitable for our needs.
Here's how to implement the decorator:
```python
import threading
from functo... | 3,155 |
To find the smallest positive integer that is not present in the given list, we can start by sorting the list in ascending order, then check each integer in the sorted list starting from 1 to find the first integer that is not present in the list.
Here's an implementation of the function using Python's built-in `sort(... | Create a Python function to find the smallest positive integer that is not present in a given list of unique integers. The function should take a list of integers `nums`, and return the smallest positive integer that is not present in the list. Handle input validation with assertions, ensuring the input is a list of in... | You can create a Python function that accomplishes this task by using a set to keep track of the integers that are present in the list. Then, you can iterate from 1 upwards, checking which is the smallest positive integer that is not in that set. Below is an implementation of such a function with the required input val... | 3,156 |
Here's how you could implement the `my_sleep()` function:
```python
import time
def my_sleep(delay, wait=True):
if not isinstance(delay, int) or delay < 0:
raise ValueError("delay must be a positive integer")
if wait:
time.sleep(delay)
else:
return
``` | Write a Python function `my_sleep(delay, wait=True)` that simulates a sleep timer. If `wait` is `True`, the function should run for `delay` seconds. If `wait` is `False`, the function immediately returns without any delay. Ensure that `delay` is a positive integer. | You can create a Python function `my_sleep` that simulates a sleep timer using the `time` module. The function will check the `wait` parameter and either sleep for the specified `delay` seconds or return immediately if `wait` is `False`. Here's how you can implement this:
```python
import time
def my_sleep(delay, wai... | 3,157 |
To write a Python function that can calculate the area of a geometric object, you can follow these steps:
1. Define a class for each type of geometric object (e.g., Rectangle, Circle, Triangle). Each class should have attributes that correspond to the properties of the object (e.g., length, width, or radius for a circ... | Write a Python function that can calculate the area of a geometric object. The function should be able to handle shapes of different types - rectangles, circles, or triangles. The function should also support rectangles with extra attributes (such as rotation). | To create a Python function that calculates the area of different geometric shapes such as rectangles, circles, and triangles, we can define a function that accepts a shape type along with its relevant attributes. Here's an implementation that accomplishes this:
```python
import math
def calculate_area(shape, **kwarg... | 3,158 |
Here's how you could implement the function:
```python
def contains_distinct_objects(my_list):
unique_elements = set()
for element in iter(my_list):
if element in unique_elements:
return False
unique_elements.add(element)
return True
``` | Design a Python function to check if a list contains only distinct objects. Return true if all elements in the list are distinct, and false if there are duplicate elements. The function should handle hashable and unhashable objects, but not support sequences for efficiency.
The function should use early return for eff... | To check if a list contains only distinct objects in Python, we can utilize a set to keep track of seen elements. This will allow us to efficiently detect duplicates, and we will handle both hashable and unhashable objects with care. For unhashable objects, we can use a list to keep track of those elements.
Here's a f... | 3,159 |
Here is the implementation of this Python function:
```python
from pathlib import Path
def get_parent_directory(file_path):
try:
path = Path(file_path)
parent_dir = path.parent
return parent_dir.name
except Exception:
return None
``` | Write a Python function that takes in a file path string, and returns the parent directory's name. The function should parse the given file path using the `pathlib` module's `Path` class, and use the `parent` attribute to traverse up one level. The function should return a string representation of this parent directory... | To create a Python function that retrieves the parent directory's name from a given file path using the `pathlib` module, you can follow the implementation below. This function will use a `try-except` block to catch any potential exceptions and will return `None` in case of an error.
Here’s the code for the function:
... | 3,160 |
Here is the implementation of a Python functor:
```python
class Functor:
def __init__(self, value):
self.value = value
def map(self, func):
return Functor(func(self.value))
def pure(value):
return Functor(value)
```
In this implementation:
- The `__init__` method initializes the ... | Write a Python function `make_functor` that takes an arbitrary class and a function and returns a new class that applies the passed function to its instances. The functor class should have two methods: `map`, which takes a function and returns a new functor with the function applied to the instances; and `pure`, which ... | To create a functor class in Python that meets the requirements you've described, we can define a function `make_functor` that takes an arbitrary class and a function. This function will return a new class that incorporates the methods `map` and `pure`, which behave according to the functor laws. Below is the implement... | 3,161 |
Here's how we can implement this using a list comprehension:
```python
def square_list(numbers):
return [number ** 2 for number in numbers]
numbers = [1, 2, 3]
squares = square_list(numbers)
sum_of_squares = sum(squares)
print(f"The square and sum of the numbers in {numbers} is {sum_of_squares}.")
```
In this im... | Design a Python function to calculate the square and sum of the numbers in a given list, using a list comprehension.
Example:
```python
[1, 2, 3] -> [1, 4, 9] -> 1 + 4 + 9 -> 14
``` | You can achieve this by creating a Python function that utilizes list comprehension to first compute the squares of the numbers in the input list, and then calculates the sum of those squared values. Here's how you can implement this:
```python
def sum_of_squares(numbers):
# Use list comprehension to compute the s... | 3,162 |
Here's how I would implement the function:
```python
def check_prime(n):
if not isinstance(n, int):
raise AssertionError('Input must be an integer')
if n < 2:
return False
if n == 2:
return True
if n % 2 == 0:
return False
for i in range(3, int(n**0.5) + 1, 2):
... | Write a Python function `check_prime(n)` that checks whether a given integer `n` is a prime number. The function should return `True` if `n` is a prime number and `False` otherwise. In addition, the function should raise an `AssertionError` if the input is not an integer. | Certainly! Below is a Python function `check_prime(n)` that checks whether a given integer `n` is a prime number. It returns `True` if `n` is a prime number and `False` otherwise. If the input is not an integer, it raises an `AssertionError`.
```python
def check_prime(n):
# Check if the input is an integer
ass... | 3,163 |
```python
import re
def parse_directions(directions):
pattern = re.compile(r"(L|R|U|D)(\d+)")
matches = pattern.findall(directions)
coordinates = [(0, 0)]
for direction, num in matches:
steps = int(num)
x, y = coordinates[-1]
if direction == "L":
x -= steps
e... | Create a Python function to parse a string representing a sequence of directions, and return the corresponding coordinates. The input string consists of a sequence of directions and numbers, where each direction can be one of "L" (left), "R" (right), "U" (up), or "D" (down). Each number represents the number of steps i... | Here's a Python function that parses a string of directions and steps, and returns the corresponding sequence of coordinates on a 2D plane. The function tracks the movement starting from the origin (0, 0) and creates a list of coordinates after each step based on the given directions.
```python
def parse_directions(di... | 3,164 |
The function should be platform-agnostic and return a list of system information, regardless of the platform (Windows, Linux, macOS).
```python
import platform
def get_system_info_win():
return ["Windows info"]
def get_system_info_nix():
return ["Nix info"]
def get_system_info():
if platform.system() ==... | Create a Python function `get_system_info()` that returns a list of system information, regardless of the platform (Windows, Linux, macOS). The function should work on any system with the necessary dependencies. The function should contain a platform-specific `get_system_info_win()` and `get_system_info_nix()` function... | To create the `get_system_info()` function that gathers system information across different platforms, we will define two platform-specific functions: `get_system_info_win()` for Windows and `get_system_info_nix()` for Linux and macOS. We will make use of built-in libraries like `platform` and `os` to determine the cur... | 3,165 |
Here's how you could do it:
```python
import time
from functools import wraps
def timed(func):
@wraps(func)
def wrapper(*args, **kwargs):
start_time = time.time()
result = func(*args, **kwargs)
end_time = time.time()
execution_time = end_time - start_time
print(f'Execut... | Write a Python function `timed` that takes a function and returns a new function, with the same functionality as the original function but with the addition of timing the function execution time. The new function should print the execution time and return the result of the original function. | You can create a decorator in Python to achieve the functionality you described. The `timed` function will take a function as an argument, and it will return a new function that computes the execution time of the original function while maintaining its functionality. Here’s how you can implement it:
```python
import t... | 3,166 |
Here's how we can implement this:
```python
def remove_first_char(strings):
return [s[1:] for s in strings if len(s) > 1]
``` | Write a Python function that takes a list of strings and returns a list of strings with the first character removed from each string. If the length of the string is less than 1, then ignore it.
Your code should pass the following test case:
```python
strings = ['apple', 'banana', 'carrot', '']
assert remove_first_char... | Here is a Python function that removes the first character from each string in a list and ignores any strings with a length of less than 1:
```python
def remove_first_char(strings):
return [s[1:] for s in strings if len(s) > 0]
# Test case
strings = ['apple', 'banana', 'carrot', '']
assert remove_first_char(strin... | 3,167 |
To convert a string to its equivalent string literal, you can follow these steps:
1. Initialize an empty string to store the resulting string literal.
2. Iterate through each character in the input string.
3. If the character is a single quote, append a double quote to the string literal.
4. If the character is a doub... | Write a Python function that takes in a string and returns a string literal of that string, with single quotes replaced by double quotes, and vice versa. For example, if the input string is `"<tag>hello</tag>"`, the resulting string literal would be `"'<tag>hello</tag>'"`. | You can achieve this by writing a Python function that takes the input string, replaces single quotes with double quotes and vice versa, and then returns the resulting string as a string literal. Here's how you can implement this:
```python
def convert_quotes(input_string):
# Replace single quotes with double quot... | 3,168 |
Here's how you can implement the given function using dictionary comprehensions:
```python
def arg_to_dict(arg):
if isinstance(arg, list):
return {elem: 0 for elem in arg}
elif isinstance(arg, dict):
return {key: value for key, value in arg.items()}
elif isinstance(arg, str):
return... | Write a Python function that takes a single argument and returns a dictionary based on the given argument's type. If the argument is a list, the dictionary should have keys corresponding to each element in the list, with values initialized to zero. If the argument is a dictionary, the keys and values should be copied i... | You can achieve this by defining a function that checks the type of the argument and constructs the appropriate dictionary based on the specified requirements. Here's a Python function that implements the described behavior:
```python
def create_dict_from_arg(arg):
if isinstance(arg, list):
# Create a dict... | 3,169 |
To change the type of all edges in the given list to `'C'` while preserving the order, I would loop through the list of tuples and modify the third element of each tuple to `'C'`.
Here is the implementation of the function in Python:
```python
def change_edge_type(edges):
for i, edge in enumerate(edges):
... | The input of a function is a list of tuples representing edges in a graph, where the first item is the starting node, the second item is the ending node, and the third item is the edge type. For example, `[(1, 2, 'A'), (2, 3, 'B'), (3, 4, 'A'), (4, 5, 'B')]` represents 4 edges, where `'A'` and `'B'` are the types of th... | You can achieve this by using a list comprehension to iterate through the input list of tuples and replace the edge type with `'C'`. Here's an example function that does this:
```python
def change_edge_type(edges):
return [(start, end, 'C') for start, end, _ in edges]
# Example usage:
edges = [(1, 2, 'A'), (2, 3,... | 3,170 |
Here's how you could implement this function:
```python
def filter_source(source, target):
target_set = set([y for x in target for y in x])
return [x for x in source if x not in target_set]
```
You can test your function using the provided test cases:
```python
source1 = [1, 2, 3, 4]
target1 = [[1], [2, 3]]... | Design a Python function that takes two parameters: `source` and `target`. `source` is a list of elements, and `target` is a list of lists containing elements. The function should return a list of elements from `source` that are not in any of the lists in `target`. Use list comprehension to construct the output list.
... | Certainly! Below is a Python function that implements the logic you described. The function uses list comprehension to filter out elements from the `source` list that are present in any of the lists in the `target` list.
```python
def filter_source(source, target):
# Flatten the target lists to a single set of el... | 3,171 |
To transform a Kubernetes resource name to the desired format, we can use regular expressions with substitution. Regular expressions allow for flexible pattern matching and substitution, making them particularly useful for tasks like text manipulation.
Here is the Python function using regular expression with substitu... | Given a Kubernetes resource name, write a Python function to replace all uppercase characters with a dash followed by the corresponding lowercase character. If the resource name already starts with a dash, remove the dash. For example, given `FooBarBaz`, the function should return `foo-bar-baz`. Use regular expression ... | You can accomplish this by using Python's `re` module, which provides support for regular expressions. Here’s a function that meets your requirements:
```python
import re
def transform_resource_name(resource_name):
# Replace uppercase letters with dash followed by lowercase letters
transformed = re.sub(r'(?<!... | 3,172 |
Here's how you can do it in Python:
```python
def generate_color_palette(colors):
palette = {}
for color in colors:
if color not in palette:
palette[color] = 0
palette[color] += 1
return sorted(palette.keys(), key=lambda x: palette[x], reverse=True)
```
The function uses a dict... | Create a Python function to generate a color palette from a list of RGB colors. The function should accept a list of colors and return a list of color values that represent the palette. The color palette should be sorted in descending order by the total number of pixels in each color. For example, if the input list is ... | You can achieve this by creating a function that counts the occurrences of each RGB color in the input list, sorts the unique colors by their count in descending order, and then returns a list of these unique colors. Below is a Python function that implements this logic:
```python
def generate_color_palette(colors):
... | 3,173 |
To validate a list of user objects against a list of banned usernames, we can use a `set` to store the banned usernames, and then iterate through the list of user objects. For each user, we check if its username is unique and not in the set of banned usernames. If the username is not valid, we add the user to a list of... | Write a Python function to validate a list of user objects (each with a `.username` attribute) against a list of banned usernames (strings), where a user is valid if it has a unique username and the username does not match any of the banned usernames. Your function should return a list of invalid users. | You can implement this validation function in Python by checking for duplicated usernames and verifying that each username is not in the list of banned usernames. Here's a sample implementation:
```python
def validate_users(user_list, banned_usernames):
"""
Validate a list of user objects against a list of ban... | 3,174 |
Here's how you could do it:
```python
def deal_hands(n):
if not isinstance(n, int) or n <= 0:
return None
return n * (n - 1) * (n - 2) * (n - 3) * (n - 4) // 120
```
This function checks if n is a positive integer and calculates the number of ways a hand of 5 cards can be dealt from a deck of n cards ... | Write a Python function that takes a positive integer n and returns the number of ways a hand of 5 cards can be dealt from a deck of n cards. The function should return None if n is not a positive integer.
Your code should pass the following test case:
```python
n = 52
expected_output = 2598960
actual_output = deal_ha... | To solve the problem of calculating the number of ways to deal a hand of 5 cards from a deck of `n` cards, we can use the concept of combinations, denoted as \( C(n, k) \), which represents the number of ways to choose `k` items from `n` items without regard to the order of selection.
The formula for combinations is g... | 3,175 |
To implement a Python function that performs a depth-first search of a tree and returns the first node with a target value, you can follow these steps:
1. Define a recursive function that takes a node and target value as inputs.
2. Check if the current node's value matches the target value. If so, return the node.
3. ... | Create a Python function that takes a `root` node of a tree and a target value, and returns the first node in the tree with the target value. The function should perform a depth-first, recursive search, and return `None` if the target value is not found. | Certainly! Below is a Python function that performs a depth-first recursive search to find the first node in a tree that matches the target value. For this example, we assume the tree nodes are instances of a class called `TreeNode`, which has the attributes `val` (to store the value of the node) and `children` (to sto... | 3,176 |
To perform a logical AND operation on two lists, we can iterate over both lists simultaneously and perform the AND operation on corresponding elements.
Here's how we can implement this function:
```python
def logical_and(a, b):
result = []
for i in range(len(a)):
result.append(a[i] and b[i])
retur... | Write a Python function that takes two lists of equal length and returns a list that is a logical AND of the two inputs.
Inputs:
```python
a = [True, False, False, True, True]
b = [True, True, False, False, True]
```
Output:
```python
result = [True, False, False, False, True]
```
Your code should pass the followi... | You can accomplish this task by defining a function `logical_and` that takes two lists of boolean values and returns a new list that combines them using a logical AND operation. Here's how you can implement this function:
```python
def logical_and(a, b):
# Check if both lists are of equal length
if len(a) != l... | 3,177 |
Here's how you can implement this:
```python
def boolean_match(a, b):
"""Check whether a boolean-like value matches another value.
Args:
a: A boolean-like value, such as True or False, or a string that can be converted to a boolean.
b: Another value to compare.
Returns:
True if bo... | Write a Python function `boolean_match` that takes two arguments: `a` and `b`. If `a` is a boolean-like value, such as `True` or `False`, or a string that can be converted to a boolean, check whether `a` matches `b`. Return `True` if both `a` and `b` are equal, or if they can be converted to the same boolean value. Oth... | Below is the implementation of the `boolean_match` function in Python, along with a description and examples.
```python
def boolean_match(a, b):
"""
Check if two values match in boolean context.
Args:
a: A boolean-like value (True, False, or a string that represents a boolean).
b: A va... | 3,178 |
To perform natural sorting on a list of strings based on the numerical values within them, we can use the following approach:
1. Split each string into substrings using regular expressions to match non-numeric characters.
2. Convert each substring to an integer and sort them in ascending order.
3. Reassemble the subst... | Write a Python function that performs natural sorting on a list of strings, where natural sorting is based on the numerical values within the strings. The sorting should consider each string as a list of substrings separated by one or more non-numeric characters. Each substring should be interpreted as an integer and s... | To implement natural sorting based on the criteria provided, we can create a function `natural_sort` that processes the input list of strings and sorts them according to the numerical values embedded within the strings.
We will break each string into substrings using a regular expression to separate numeric and non-nu... | 3,179 |
Here's how you can implement the Jaccard similarity function in Python:
```python
def jaccard_similarity(dict_a, dict_b):
intersection = len(set(dict_a.keys()) & set(dict_b.keys()))
union = len(set(dict_a.keys()) | set(dict_b.keys()))
return intersection / union
``` | Use set operations to create a Python function that calculates the Jaccard similarity between two sets of dictionaries. The function should return a float value between 0 and 1, representing the similarity. | To calculate the Jaccard similarity between two sets of dictionaries in Python, we can define a function that first converts each dictionary into a set of its string representations. The Jaccard similarity is defined as the size of the intersection of the two sets divided by the size of the union of the two sets.
Here... | 3,180 |
You can use a list comprehension to iterate through the list of tuples and check if the occupation is not `None`. If it is not `None`, then it is kept in the new list. Otherwise, `None` is appended.
Here's how you can do it in two lines of Python code:
```python
def filter_occupation(input_list):
return [(name, o... | Write a Python function that takes a list of tuples, each representing a user's name, age, and occupation, and returns a list of tuples containing only the user's name and occupation, provided that the user has an occupation. If the user does not have an occupation, then the name should be followed by `None`.
Your cod... | You can achieve this by defining a function `filter_occupation` that processes each tuple in the input list. The function will check the occupation of each user; if it's present, it will include it in the result, otherwise, it will include `None`. Here's how you can implement this:
```python
def filter_occupation(user... | 3,181 |
To implement this function, we need to iterate through the dictionary and maintain a map of values to their corresponding keys. Here's how we can achieve that:
1. Initialize an empty `result` dictionary to store the keys and values.
2. Iterate through the given dictionary `d` using `for key, value in d.items()`.
3. Ch... | Implement a Python function that takes a dictionary as an argument and returns a new dictionary whose keys are the values of the original dictionary and whose values are the keys of the original dictionary.
For example, given a dictionary `d = {"key1": "value1", "key2": "value2", "key3": "value1"}`, the function shoul... | You can achieve this by iterating over the items in the original dictionary and populating a new dictionary where the keys are the values of the original dictionary and the values are lists of keys that mapped to those values. Here's how you can implement this function in Python:
```python
def invert_dict(d):
inve... | 3,182 |
To update the list of atom objects, we need to iterate through each atom object in the list and perform the required actions:
- Assign the correct atom type to each atom: This can be done by comparing the atom's `.atom_type` attribute with a predefined list of types and assigning the correct type based on the match.
-... | Write a Python function to update a list of atom objects to contain the appropriate atom type, atom charge, multiplicity (number of bonds), and ring membership.
The atom objects in the list have the following attributes:
- `.atom_type`
- `.atom_charge`
- `.multiplicity`
- `.in_ring`
The function should perform the f... | To create a Python function that updates a list of atom objects to include the appropriate atom type, atom charge, multiplicity, and ring membership, we need to define our atom class and then implement the function that processes the list of atom objects. Below is an example implementation.
We'll assume that we have s... | 3,183 |
Here's how you could do it:
```python
def format_time_duration(duration):
hours = duration // 3600
minutes = (duration % 3600) // 60
seconds = duration % 60
if hours > 0:
formatted_duration = f"{hours}h{minutes:02}m{seconds:02}s"
elif minutes > 0:
formatted_duration = f"{minutes}m{s... | Write a Python function to format an input time duration (in seconds) into a human-readable string. Here are the rules:
- If the duration is below a minute, format it as "{X}s", where "X" is the number of seconds, rounded to the nearest whole number.
- If the duration is between one minute and one hour, format it as "... | Here's a Python function that formats a time duration in seconds into a human-readable string according to the specified rules:
```python
def format_duration(seconds):
# Round the input duration to the nearest whole number
total_seconds = round(seconds)
# Calculate hours, minutes, and seconds
hour... | 3,184 |
Here's an example implementation:
```python
from datetime import datetime
DAYS_OF_WEEK = {
0: "Monday",
1: "Tuesday",
2: "Wednesday",
3: "Thursday",
4: "Friday",
5: "Saturday",
6: "Sunday",
}
BANK_HOLIDAYS = {
"2023-01-01": "New Year's Day", # New Year's Day
"2023-04-14": "Good F... | Write a function in Python that takes a date (format: "YYYY-MM-DD") and returns the day of the week as a string (e.g., "Monday"). The function should account for bank holidays (New Year's Day, Good Friday, Easter Monday, Christmas Day, and Boxing Day).
Your code should pass the following assertions:
```python
assert g... | To create the function `get_day_of_week` that returns the day of the week for the given date, and also account for specific bank holidays in the year 2023, we can utilize the `datetime` module from Python's standard library.
Here’s how we can implement this function:
```python
from datetime import datetime
def get_d... | 3,185 |
Here is a Python function that represents a 0D tensor using type aliasing and class-based function definition:
```python
from __future__ import annotations
class tensor_0d:
"""
A class representing a 0D tensor.
"""
def __init__(self, label: str, value: float):
self.label = label
self.v... | Write a Python function to represent a 0D tensor using type aliasing and class-based function definition. The function takes a `label` and a `value` as arguments, where `label` is a string and `value` is a `float`. The function should return a `tensor_0d` object, which is a class with a `label` attribute of type `str` ... | Here's a Python implementation for a function that creates a 0D tensor using type aliasing and class-based definitions, as per your specifications:
```python
from typing import Optional
# Define the class for a 0D tensor
class Tensor0D:
def __init__(self, label: str, value: float):
self.label: str = label... | 3,186 |
```python
class TreeNode:
def __init__(self, val, left=None, right=None):
self.val = val
self.left = left
self.right = right
def is_symmetric(root):
if root is None:
return True
def check_symmetric(left, right):
if left is None and right is None:
return ... | Design a Python function to determine if a given tree is symmetric. You can use a recursive approach to traverse the tree, starting from the root node. If a node has two children, check if they match by comparing their values and recursively checking their subtrees. If a node has only one child, treat it as a single-no... | To determine if a given binary tree is symmetric, we can define a class `TreeNode` to represent each node in the tree. We'll implement a recursive function that checks the symmetry by comparing the left and right subtrees.
Here’s how to implement this in Python:
```python
class TreeNode:
def __init__(self, value,... | 3,187 |
To check whether a string contains only ASCII letters and digits, we need to iterate over each character in the string and check if it is within the range of ASCII values for letters and digits.
To determine if each character is valid, we can use the ASCII character value ranges (0-9 -> 48-57; a-z -> 97-122; A-Z -> 65... | Write a Python function to check whether a string contains only ASCII letters (a-z, A-Z) and digits (0-9). Utilize ASCII character value ranges (0-9 -> 48-57; a-z -> 97-122; A-Z -> 65-90) to determine if a character is valid.
Your code should pass the following assertions:
```python
assert is_string_valid('') is True
... | You can create a Python function to check whether a string contains only ASCII letters and digits by iterating through each character in the string and checking its ASCII value. Here’s how you can implement this:
```python
def is_string_valid(s):
for char in s:
ascii_value = ord(char)
# Check if as... | 3,188 |
To define a function named `random_number` that returns a randomly generated integer between 1 and 10 (inclusive), you can use the `random` module in Python, which provides a set of functions for generating random numbers. The `random` module has a function called `randint` that can generate a random integer between tw... | Write a Python function to define a function named `random_number` that takes no arguments and returns a randomly generated integer between 1 and 10 (inclusive). This function should use the `random` module and the `randint` function within it.
Your code should pass the following test case:
```python
for _ in range(10... | Here is a Python function named `random_number` that fulfills your requirements. This function uses the `random` module to generate a random integer between 1 and 10 (inclusive).
```python
import random
def random_number():
return random.randint(1, 10)
# Test the function with the provided test case
for _ in ran... | 3,189 |
To achieve the desired behavior, you can make use of Python's dictionary keys check and default values. The function `get_settings(settings, port=None)` checks whether the `port` argument is None. If it's None, it checks whether the key `port` exists in the `settings` dictionary. If it exists, it uses the value associa... | I have a dictionary `settings = {'url': 'https://example.com', 'port': 80}` and a function `get_settings(settings, port=None)`. If the `port` argument is not provided, then the function should look for a `port` key in `settings` and use that as the default value if it exists, otherwise it should use the default value p... | You can implement the `get_settings` function to achieve this behavior by checking if the `port` argument is `None`. If it is, the function can attempt to retrieve the port from the `settings` dictionary, falling back on a default value if that key does not exist. Here is how you can write this function:
```python
def... | 3,190 |
Here's how we can implement this function:
```python
def get_config_option(config_dict, key, default=None):
if key in config_dict:
return config_dict[key]
elif default is not None:
return default
else:
raise KeyError(f"Key '{key}' not found in dictionary.")
``` | Write a Python function `get_config_option` that retrieves a configuration option from a given dictionary. The function should check whether the given dictionary contains the specified key and return its value if it exists. If the key does not exist, the function should return a default value provided as an optional ar... | Certainly! Here's a Python function named `get_config_option` that accomplishes the requirements you've described:
```python
def get_config_option(config, key, default=None):
"""
Retrieve a configuration option from a given dictionary.
Parameters:
config (dict): The configuration dictionary.
key (... | 3,191 |
Here are the steps for implementing the `validate_request(request_string)` function:
1. Split the `request_string` into separate parts based on the space character.
2. Check whether the first part is either `GET` or `POST`.
3. Check whether the second part starts with a slash `/` and does not contain any spaces.
4. Che... | Write a Python function to validate a string containing a URL request. The function should return a tuple of two values (a boolean indicating whether the request is valid, and the string message containing the error message if the request is invalid).
A valid request string consists of the following parts:
- The meth... | Here is a Python function that validates a given URL request string according to the specified rules. It checks the method, URI path, and HTTP version, and returns a tuple indicating whether the request is valid, along with an error message if it is not.
```python
def validate_request(request_string):
# Split the ... | 3,192 |
Here is the implementation of the `compose` function:
```python
def compose(f, g):
def new_function(x):
return g(f(x))
return new_function
``` | Develop a Python function `compose` that composes two functions `f` and `g` together, returning a new function that performs `g` after `f` on its input. The resulting function should have the signature `compose(f, g)(x)` and should be equivalent to `g(f(x))`. | Sure! In Python, you can create a `compose` function that takes two functions `f` and `g` as arguments and returns another function that applies `f` to its input and then applies `g` to the result.
Here’s how to implement this:
```python
def compose(f, g):
def composed_function(x):
return g(f(x))
ret... | 3,193 |
Here is the implementation:
```python
def within_tolerance(actual, expected, tolerance=0.001):
return abs(actual - expected) <= tolerance * expected
``` | Implement a Python function `within_tolerance` that takes three arguments: `actual` and `expected` as numbers, and `tolerance` as a ratio (e.g., 0.1), and returns `True` if the absolute difference between `actual` and `expected` is less than or equal to `tolerance * expected`. If `tolerance` is not given, use the defau... | You can implement the `within_tolerance` function in Python as follows:
```python
def within_tolerance(actual, expected, tolerance=0.001):
"""
Check if the actual value is within the specified tolerance of the expected value.
Parameters:
actual (float): The actual value.
expected (float): The expe... | 3,194 |
To check if a given date and time is within a specified time range, you can compare the target datetime with the start and end of the time range. The target datetime should be within the time range if it is greater than or equal to the start of the time range and less than or equal to the end of the time range.
Here i... | Create a Python function that checks if a given date and time is within a specified time range. The function takes two arguments: a target datetime object and a tuple of two datetime objects representing the start and end of the time range. The function should return a Boolean value indicating whether the target dateti... | Certainly! Here’s a Python function that checks if a given target `datetime` object is within a specified time range defined by a start and end `datetime` object. We'll use the `datetime` module to achieve this:
```python
from datetime import datetime
def is_within_time_range(target_datetime: datetime, time_range: tu... | 3,195 |
Here's how you can implement this in Python:
```python
import os
def check_file_or_directory_exists(path):
return os.path.exists(path)
``` | Write a Python function to check if a file or directory exists. The function should receive a path as a string and return a boolean that indicates whether the file or directory exists.
Your code should pass the following assertions:
```python
assert check_file_or_directory_exists('/path/to/directory') == True
assert c... | To check if a file or directory exists in Python, you can use the `os.path` module, which provides a function called `exists()`. Here's how you can implement the function according to your requirements:
```python
import os
def check_file_or_directory_exists(path: str) -> bool:
return os.path.exists(path)
# Test ... | 3,196 |
Here's how you could implement this function in Python:
```python
def concat_dicts(dict_list):
combined_string = ''
for item in dict_list:
name = item['name']
score = item['score']
combined_string += f'{name} {score}, '
return combined_string.rstrip(', ')
```
This function takes ... | Write a Python function that takes a list of dictionaries as an input, where each dictionary has `name` and `score` keys. The function should return a string that consists of the name and score of each dictionary concatenated together, separated by commas. For example, if the input is `[{'name': 'Alice', 'score': 90}, ... | Sure! You can use the following Python function to achieve that. The function iterates over each dictionary in the input list, and concatenates the `name` and `score` values into a formatted string, which is then joined together with commas.
Here is the implementation:
```python
def format_scores(score_list):
# C... | 3,197 |
To write a Python function to convert a value in bytes (B) to other units of information, such as kilobytes (KB), megabytes (MB), and gigabytes (GB), you can follow these steps:
1. Define a function that takes two arguments: the value in bytes and the desired unit of conversion.
2. Use a dictionary to store the conver... | Write a Python function that converts a value in bytes (B) to other units of information, such as kilobytes (KB), megabytes (MB), and gigabytes (GB). The function should take two arguments: the value in bytes and the desired unit of conversion. Include a docstring that explains the function's input and output, and an e... | Here's a Python function that converts a value in bytes (B) to other units of information, including kilobytes (KB), megabytes (MB), and gigabytes (GB). The function uses appropriate conversion factors for each unit. The docstring provides detailed information about the function's inputs and outputs, along with an exam... | 3,198 |
Here's how you could do it:
```python
def format_event(event_data):
return (
f"{event_data['user']} {event_data['is_active']} "
f"{event_data['event_type']} the {event_data['entity_type']} "
f"{event_data['entity_id']} at {event_data['timestamp']}"
)
```
This function takes the event d... | Write a Python function `format_event` that takes a dictionary named `event_data` and returns a string representation of the event data in the following format:
```
"{user} {is_active} {event_type} the {entity_type} {entity_id} at {timestamp}"
``` | Certainly! Below is a Python function `format_event` which takes a dictionary named `event_data` and returns a formatted string representation of the event data according to the specified format:
```python
def format_event(event_data):
# Extract fields from the event_data dictionary
user = event_data.get('user... | 3,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.