response_seed stringlengths 53 5.17k | instruction_seed stringlengths 29 4.02k | response stringlengths 16 8.81k | __original_row_idx int64 0 50k |
|---|---|---|---|
Here is a Python function that implements this approach:
```python
def extract_field(data, field, default=None):
"""
Extracts the value of a specific field from a JSON object. If the field is
a nested object, the function recursively extracts the value from the nested
object. If the field is not found,... | Write a Python function that extracts a specific field from a JSON object, and returns the value of that field if it exists or a default value otherwise. If the field is a nested object, the function should recursively extract the value from the nested object. | You can create a function in Python that extracts a specific field from a JSON object, including the ability to handle nested structures. Here's a simple implementation of such a function:
```python
import json
def extract_field(data, field_path, default=None):
"""
Extracts the value of a specific field from ... | 9,100 |
The question involves processing HTML strings, matching specific tags based on a given regular expression pattern, and replacing the matched tags with a given value. To accomplish this, we can use Python's regular expression library `re` to extract the tag name and inner content from the HTML string, and then replace t... | Write a Python function that takes a string of HTML as an input and returns a formatted string, replacing all matching tags with a given value, based on a given regular expression pattern. The regular expression pattern should match any HTML tags and their contents, and capture the tag name and inner content.
The func... | You can achieve this by using the `re` module in Python, which allows you to work with regular expressions. Below is a function that meets the specifications you provided:
```python
import re
def replace_html_tags(html_string, pattern, replacement_tag, replacement_value):
"""
Replace HTML tags matching a give... | 9,101 |
To calculate the angle between two points in 2D space, you could use the `atan2` function from the `math` module. The `atan2` function takes two arguments, the `y` coordinate and the `x` coordinate, and returns the angle in radians.
Here's how you could implement the function:
```python
import math
def calculate_ang... | Create a Python function to calculate the angle between two points in 2D space, where the angle is measured in radians. The function should take the coordinates of the two points as arguments and return the angle as a floating-point number. The function should follow the following conditions:
1. If the angle is less t... | To calculate the angle between two points in 2D space, we can use the `math.atan2()` function which gives us the angle between the positive x-axis and the line connecting the two points, measured in radians. Here's how we can implement the function according to your specifications:
```python
import math
def calculate... | 9,102 |
Here's how you could implement the function:
```python
def inch_to_cm(inches):
return inches * 2.54
``` | Create a Python function that takes a measurement of a length in inches (`in`) and converts it to centimeters (`cm`). The function should return the converted value as a float value.
Use the following formula to convert inches to centimeters:
$$
\text{centimeters} = \text{inches} \times \frac{2.54}{1}
$$
Your code s... | You can create a function that converts inches to centimeters using the formula provided. Here's how you can implement the function in Python:
```python
def inch_to_cm(inches):
return inches * 2.54
# Test case
test_length = 6
expected_result = 15.24
actual_result = inch_to_cm(test_length)
assert actual_result ==... | 9,103 |
The function is designed to determine whether two floating-point numbers are approximately equal. By providing a third argument `epsilon`, it allows the user to define the acceptable difference between the two numbers. If the difference between the two numbers is less than or equal to `epsilon`, the function returns `T... | Develop a Python function `is_equal_epsilon(x, y, epsilon)` that checks whether two floating-point numbers are approximately equal. The function should accept three arguments: x, y, and epsilon. The function should return a boolean value indicating whether the difference between x and y is within epsilon.
Your code sh... | You can create the `is_equal_epsilon` function in Python as follows. This function will compare the absolute difference between two floating-point numbers `x` and `y` to a specified tolerance `epsilon`. If the absolute difference is less than or equal to `epsilon`, the function will return `True`, indicating that the n... | 9,104 |
The main steps to calculate the entropy of a file are:
1. Read the file contents in binary mode, so that it's read as a byte array.
2. Count the occurrences of each byte value in the file.
3. For each byte value, calculate its probability of occurrence using the formula `probability = count / total`.
4. Calculate the ... | Write a Python function to calculate the entropy of a file. The function should take the file path as input and return a non-negative float as output.
Handle all possible file reading errors and return 0 when encountering errors. | Here's a Python function that calculates the entropy of a file. Entropy is a measure of the uncertainty or randomness in a dataset, and in this case, we will compute the entropy based on the frequency of bytes in the file. The function will handle file reading errors and return `0` when any error occurs.
```python
imp... | 9,105 |
You can create a Python function that computes the angle between two vectors using the dot product and cross product. The angle is positive if the rotation is counterclockwise and negative if it is clockwise.
Here's a possible implementation in Python:
```python
import numpy as np
from numpy.linalg import norm
def s... | Create a Python function to compute the signed angle in degrees between two vectors in 3D space. The angle is positive if the rotation from the first vector to the second is counterclockwise and vice versa.
Your code should pass the following test case:
```python
v1 = np.array([1, 0, 0])
v2 = np.array([0, 1, 0])
angl... | To compute the signed angle between two vectors in 3D space, we need to use the cross product and dot product of the vectors. The signed angle can be determined by the angle calculated from the dot product of the two vectors, while the direction of the rotation (clockwise or counterclockwise) can be determined using th... | 9,106 |
To create an object with attributes from the JSON string, you can use a combination of the `json.loads()` function to convert the JSON string into a Python dictionary, and then use the `setattr()` function to create object attributes for each key-value pair.
Here is an example implementation of the `encode_json_to_obj... | Implement a function named `encode_json_to_obj` that converts a JSON string into a Python object. The function should create a dictionary of the JSON string and then map each key-value pair into an object attribute. The JSON string should be of the form:
```json
{
"a": 1,
"b": 2,
"c": 3
}
```
The function... | To implement the `encode_json_to_obj` function that converts a JSON string into a Python object with attributes corresponding to the key-value pairs in the JSON, we can follow these steps:
1. Use the `json` module to parse the JSON string into a Python dictionary.
2. Create a class that can dynamically set attributes ... | 9,107 |
To solve this problem, we need to use regular expressions to extract the input-output pairs from the given string. Regular expressions provide a powerful way to match patterns in text, allowing us to extract the input and output values from the string.
Here's one way to implement the `parse_i_o` function using regular... | Develop a Python function `parse_i_o` that takes a string representing a series of input-output pairs as input and returns a list of tuples containing the input and output values. For example, given the following string:
```
"Input: 1\nOutput: 2\nInput: 3\nOutput: 4"
```
The output of `parse_i_o` should be:
```
[("1... | To implement the `parse_i_o` function in Python that extracts input-output pairs from a given string, we can utilize the `re` module for regular expressions. The goal is to find all occurrences of "Input" and "Output" lines, pair them up as tuples, and return a list of these tuples.
Here’s how you can implement the f... | 9,108 |
Here's how you could implement the function:
```python
import numpy as np
def concatenate_last_two_dimensions(vector_of_vectors):
return np.concatenate([vector.reshape(-1, 1) for vector in vector_of_vectors], axis=1)
```
This function takes a vector of vectors as input and applies the `reshape()` method to each ... | Write a Python function to concatenate the last two dimensions of a vector of vectors into a single dimension. The function should take a vector of vectors as input and return a single vector that consists of the concatenated values. | You can use NumPy, a popular library for numerical computations in Python, to handle the concatenation of the last two dimensions of a vector of vectors. Here's a function that implements this:
```python
import numpy as np
def concatenate_last_two_dimensions(vector_of_vectors):
# Convert the input to a NumPy arra... | 9,109 |
Here's how we can implement this:
```python
def keep_track_of_inventory(items):
inventory = {}
for item in items:
if item in inventory:
inventory[item] += 1
else:
inventory[item] = 1
return inventory
``` | Design a Python function to keep track of items in an inventory. The function takes a list of items and returns a dictionary with the count of each item. If an item occurs multiple times, its count should be incremented.
Your code should pass the following test case:
```python
items = ['apple', 'banana', 'apple', 'ora... | You can achieve this by defining a function that utilizes Python's dictionary to keep track of item counts. Here's the implementation of the function:
```python
def keep_track_of_inventory(items):
inventory = {}
for item in items:
if item in inventory:
inventory[item] += 1
else:
... | 9,110 |
Here is a Python function that implements the required functionality:
```python
import json
def parse_json_log_line(log_line):
try:
data = json.loads(log_line)
return data
except json.JSONDecodeError:
return None
```
This function uses the `loads` method from the `json` module to atte... | Write a Python function `parse_json_log_line` that takes a log line in JSON format and returns a Python object. If the log line is not valid JSON, return None.
The function is used to process log lines from an application and save the parsed data to a file or database. | Certainly! Below is a Python function `parse_json_log_line` that takes a log line in JSON format and attempts to parse it. If the log line is valid JSON, it returns the corresponding Python object. If it's not valid JSON, it returns `None`.
Here's the implementation:
```python
import json
def parse_json_log_line(log... | 9,111 |
To verify whether an object is a boolean sequence, we can use type checking to ensure that it is a sequence and that each element is of type `bool`. For example, we can check whether the object is of type `list` or `tuple`, and then iterate through each element to ensure that it is of type `bool`.
Here is a Python fun... | Write a Python function named `is_boolean_sequence` to determine whether an object is a boolean sequence, such as a list of boolean values. The function should return `True` if the object is a sequence of booleans, or `False` otherwise. Use type checking to verify the object's type and contents.
Your code should pass ... | To determine whether an object is a boolean sequence (i.e., a sequence consisting solely of boolean values `True` or `False`), we can create a function that checks the following:
1. The object should be a sequence type, such as a list or a tuple.
2. All elements within that sequence should be of type `bool`.
Here's h... | 9,112 |
Here's an example of how we can modify the `count_symbols` function to handle non-integer symbols:
```python
def count_symbols(string):
symbol_counts = {}
for symbol in string:
if symbol.isdigit():
symbol = int(symbol)
if symbol not in symbol_counts:
symbol_counts[symbol... | I have a Python function that takes a string as an input and returns a dictionary representing the counts of each symbol. For example, `count_symbols('hello')` returns `{'h': 1, 'e': 1, 'l': 2, 'o': 1}`.
However, I found that when the input string contains non-integer symbols, the function throws a `ValueError` instea... | Sure! Below is a Python function that takes a string as input and returns a dictionary representing the counts of each character in the string, regardless of whether the input contains non-integer symbols or not. The function does not throw any exceptions for non-integer symbols; instead, it counts each character in th... | 9,113 |
To format and interpolate a string as an HTML paragraph, we need to construct the HTML `p` tag with the given string as its content. We can leverage the `format` method to achieve this task. Additionally, we can use the `id` argument to include an `id` attribute in the HTML `p` tag if it is provided.
Here is the imple... | Write a Python function to format and interpolate a string as an HTML paragraph. The function should take the paragraph text and an optional `id` argument, and return the formatted HTML string. Use the `id` argument to include an `id` attribute in the HTML `p` tag.
Your code should pass the following assertions:
```py... | You can create the function `format_html_paragraph` that takes a paragraph text and an optional `id` argument. If the `id` is provided, it will include it in the `<p>` tag; otherwise, it will just return a basic paragraph. Here's how you can implement this:
```python
def format_html_paragraph(text: str, id: str = None... | 9,114 |
To compute the set of all shortest paths between all pairs of nodes in a weighted graph, we can use the Floyd-Warshall algorithm. The algorithm is a dynamic programming approach that utilizes the shortest paths between pairs of nodes to compute the shortest paths between all pairs of nodes.
Below is a Python implement... | Given a weighted graph represented by a dictionary mapping each node to a list of tuples of the form (neighbor, cost), write a Python function that computes the set of all shortest paths between all pairs of nodes in the graph. The function should return a dictionary mapping each pair of nodes to its shortest distance.... | To compute the set of all shortest paths between all pairs of nodes in a weighted graph efficiently, we can use the Floyd-Warshall algorithm. This algorithm is well-suited for dense graphs and can handle graphs where nodes may not be directly connected.
Here is a Python function that implements the Floyd-Warshall algo... | 9,115 |
Converting a NumPy array to a PyTorch tensor is a common operation in machine learning. The `numpy_to_torch_tensor` function provided as a template can be used to achieve this task.
Here is the code for the Python function that converts a NumPy array to a PyTorch tensor:
```python
import numpy as np
import torch
def... | I have a NumPy array of input data `input_data` and I want to convert it to a PyTorch tensor. Write a Python function that takes the NumPy array as an input and returns a PyTorch tensor as the output. Use the `numpy_to_torch_tensor` function as a template. | You can easily convert a NumPy array to a PyTorch tensor using the `torch.from_numpy()` function. Below is a Python function that takes a NumPy array as input and returns a PyTorch tensor.
Here's the function based on your request:
```python
import numpy as np
import torch
def numpy_to_torch_tensor(input_data):
... | 9,116 |
Here's how you can implement this:
```python
import math
def calculate_euclidean_distance(vector_a, vector_b):
if len(vector_a) != len(vector_b):
raise ValueError("Vectors must have the same length")
distance = 0
for i in range(len(vector_a)):
distance += (vector_a[i] - vector_b[i]) ** 2
... | Design a function in Python that calculates the distance between two vectors, given as lists of numbers, using the Euclidean distance formula:
```python
import math
def calculate_euclidean_distance(vector_a, vector_b):
# Check if the vectors have the same length
if len(vector_a) != len(vector_b):
rais... | The function you've provided to calculate the Euclidean distance between two vectors is correctly structured and follows the required mathematical principles. The implementation checks if the vectors have the same length and then computes the distance using the formula for Euclidean distance.
Here’s the provided code... | 9,117 |
To create a Python function that updates the value of a dictionary at a given key with a given value, you can follow these steps:
1. Validate the input values by checking whether `d` is a dictionary, `k` is a string, and `v` is not `None` or `NaN`.
2. Check if the key is already present in the dictionary.
3. If the ke... | Create a Python function `update_value(d, k, v)` that updates the value of a dictionary `d` at a given key `k` with a given value `v`. If the key does not exist, create it with the given value. If the value is `None` or `NaN`, raise an `Exception` with the message "Invalid value". | You can define the `update_value` function as described in your request. The function will check if the value is `None` or `NaN` (using `math.isnan` for the latter), and if so, it raises an exception. Otherwise, it updates the dictionary. Here's the implementation:
```python
import math
def update_value(d, k, v):
... | 9,118 |
```python
def sanitize_input(input_string):
if not input_string:
return ""
sanitized = input_string.strip()
sanitized = sanitized.replace(" ", " ")
sanitized = sanitized.upper()
return sanitized
```
The first condition checks if the input string is empty, and returns an empty string in tha... | Develop a Python function `sanitize_input(input_string)` that takes a string as input, and returns a sanitized version of the string. The function should perform the following operations:
1. If the input string is empty, return an empty string.
2. If the input string contains more than one whitespace character, replac... | Here is a Python function `sanitize_input(input_string)` that implements the specified sanitization rules:
```python
import re
def sanitize_input(input_string):
# Step 1: If the input string is empty, return an empty string
if not input_string:
return ""
# Step 2: Replace multiple whitespace ... | 9,119 |
Here is a possible implementation of the function:
```python
def format_list_of_dicts(list_of_dicts):
formatted_strings = []
keys = list(list_of_dicts[0].keys()) if list_of_dicts else []
for key in sorted(keys):
values = [str(d[key]) for d in list_of_dicts]
formatted_string = f"{key}: {', '... | Write a function that takes a list of dictionaries, where each dictionary has the same keys. The function should return a list of strings that are formatted as follows:
```
Key: value1, value2, ...
```
where key is one of the dictionaries' keys, and value1, value2, etc. are the values associated with key in each of t... | Certainly! Below is a Python function that fulfills your requirements. It processes a list of dictionaries, extracts the keys and their corresponding values, formats them as specified, and returns them in ascending order by key.
```python
def format_dicts(dicts):
if not dicts:
return []
# Create a dic... | 9,120 |
To shift each list cyclically by 1, we can apply a cyclic permutation to each list. A cyclic permutation is a permutation where the elements are shifted by 1 position and the last element is put at the beginning.
Here's a Python implementation of the `shift_lists_cyclically` function:
```python
def shift_lists_cyclic... | Create a Python function `shift_lists_cyclically(lists)` that takes a list of lists and shifts each list cyclically by 1. You can assume the number of elements in each list is greater than 1.
Your code should pass the following test case:
```python
lists = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
shift_lists_cyclically(lists... | Certainly! Below is the implementation of the `shift_lists_cyclically` function. This function will take a list of lists and shift each inner list's elements cyclically to the right by 1 position.
```python
def shift_lists_cyclically(lists):
for i in range(len(lists)):
# Save the last element
last_... | 9,121 |
To calculate the complex part of the sum of elements in a tensor of complex numbers, we can first convert the tensor to a numpy array using `t.numpy()`, then sum all the elements using `np.sum`, and finally extract the complex part using `np.imag()`.
Here is the implementation:
```python
import numpy as np
def sum_c... | Write a Python function to return the complex part of the sum of all the elements in a given tensor `t` of complex numbers. | To compute the complex part of the sum of all elements in a tensor of complex numbers in Python, we can make use of NumPy, a powerful library for numerical computing that provides support for multi-dimensional arrays (tensors) and complex numbers.
Here's a function that accomplishes this:
```python
import numpy as np... | 9,122 |
```python
import ast
def deserialize(data):
objects = ast.literal_eval(data)
def convert(obj):
if isinstance(obj, str):
return obj
elif isinstance(obj, list):
return [convert(item) for item in obj]
elif isinstance(obj, tuple):
return tuple(convert(it... | I need to create a Python function that receives a string (representing serialized data) sent through a socket, deserializes it, and returns the deserialized data. I need to handle various data types, including integers, floats, strings, lists, dictionaries, and tuples.
Please provide me with the Python function that ... | To create a Python function that deserializes a string representation of various data types including integers, floats, strings, lists, dictionaries, and tuples, we can use the `ast.literal_eval()` function from the `ast` module. This function safely evaluates an expression node or a string containing a Python literal ... | 9,123 |
Here is a Python function that implements this approach:
```python
def parse_text_to_int_and_float(text):
numbers = text.split(",")
integers = []
floats = []
for num in numbers:
if num.isdigit():
integers.append(int(num))
else:
floats.append(float(num))
ret... | I have a Python function `parse_text_to_int_and_float(text)` that takes a string of comma-separated numbers and returns two lists. The first list contains the integers from the input string, and the second list contains the floats.
For example, `parse_text_to_int_and_float("12.3,23.4,45,67.8")` should return `([45], [... | Certainly! You can achieve this by splitting the input string by commas, iterating over the resulting items, and then trying to convert each item to an integer or a float. Here's a possible implementation of the function:
```python
def parse_text_to_int_and_float(text):
# Split the input text into a list of string... | 9,124 |
To solve this problem, we can use a recursive approach. We can define a recursive function `helper` that takes a nested list as input and returns the sum of all integers in the list.
The `helper` function will check whether the input list is empty or a flat list of integers. If it's empty, it will return `0`. If it's ... | Write a Python function `tree_sum` that takes in a nested list of integers and returns the sum of all integers in the entire list. The function should implement the following behavior:
- If the input list is empty, the function should return `0`.
- If the input list is a flat list of integers, the function should retu... | You can create the `tree_sum` function by using recursion to handle the nesting of lists. Here’s a possible implementation:
```python
def tree_sum(nested_list):
total = 0 # Initialize a total variable to accumulate the sum
for element in nested_list:
if isinstance(element, list): # Check if the ... | 9,125 |
Here's how you could do it:
```python
def is_job_running(name, device):
parts = name.split('_')
task_id = int(parts[1])
device_type = parts[2]
if device_type == device:
return True
else:
return False
``` | Write a Python function to return whether a job is running on a particular device. The function takes two arguments: `name` is the name of the job, and `device` is the type of device to check. The function should return a boolean value indicating whether the job is running on the specified device.
Here is an example o... | You can implement the desired function by splitting the job name to extract the device type and compare it with the specified device. Here's how you can do that:
```python
def is_job_running(job_name, device):
# Split the job name by underscores to extract components
components = job_name.split('_')
#... | 9,126 |
To compute the dot product of two integer arrays, we need to follow these steps:
1. Check if the two arrays have the same length. If they don't, return `None`.
2. Initialize a variable `dot_product` to 0.
3. Iterate over the elements of the arrays using a `for` loop.
4. For each pair of elements, compute their product... | Write a Python function `print_dot_product(array1, array2)` that takes two integer arrays as input and returns their dot product. If the arrays have different lengths, the function should return `None`. Use type hinting to specify that the arrays are lists of integers. | Certainly! Below is a Python function named `print_dot_product` that calculates the dot product of two integer arrays. The function checks if the lengths of the two arrays are equal and returns `None` if they are not. It utilizes type hinting to specify that the input parameters are lists of integers.
```python
from t... | 9,127 |
You can create a Python function that generates Alexa Skill output based on a given input. The function should take an object of input parameters containing an input text and an intent, and return a structured JSON object with the appropriate Alexa Skill output. The output should be a plain text Alexa Skill output.
He... | Write a Python function to generate an Alexa Skill output based on a given input. The function should take an object of input parameters and return a structured JSON object with the appropriate Alexa Skill output. The input object should contain an input text and an intent, and the output should be a plain text Alexa S... | Certainly! Below is a Python function that takes input parameters for an Alexa Skill and returns a structured JSON output based on the given input. The function uses an `input_parameters` object that will contain the input text and the intent.
```python
import json
def generate_alexa_skill_output(input_parameters):
... | 9,128 |
Here is an implementation of the `validate_coordinates` function in Python:
```python
def validate_coordinates(latitude, longitude):
if not isinstance(latitude, (int, float)):
return False
if not isinstance(longitude, (int, float)):
return False
if not (-90 <= latitude <= 90):
retur... | Write a Python function `validate_coordinates` that checks whether a latitude and longitude pair is valid. The function should return `True` if the following conditions are met:
- Both latitude and longitude are numbers
- Latitude is within the range [-90, 90]
- Longitude is within the range [-180, 180]
Otherwise, th... | Here's a Python function `validate_coordinates` that checks whether a given latitude and longitude pair is valid based on your specified conditions:
```python
def validate_coordinates(latitude, longitude):
# Check if both latitude and longitude are numbers
if not isinstance(latitude, (int, float)) or not isins... | 9,129 |
To check if a point is inside an ellipse with a center at (0, 0) and horizontal radius a and vertical radius b, we can use the equation `(x**2/a**2) + (y**2/b**2) = 1`. If the point is inside the ellipse, the left-hand side of the equation will be less than or equal to 1. Otherwise, it will be greater than 1, indicatin... | Write a Python function to check if a given point is inside an ellipse (or not). The ellipse is centered at (0, 0) and has a horizontal radius of a and a vertical radius of b. The input is two numbers representing the x and y coordinates of the point. The output is True if the point is inside the ellipse, and False oth... | You can create a Python function to check if a given point (x, y) is inside an ellipse centered at (0, 0) with horizontal radius `a` and vertical radius `b` using the provided equation. The point is considered inside the ellipse if the equation is less than 1. Here is how you can implement this:
```python
def is_point... | 9,130 |
Here is a Python function that implements this approach using the `Counter` class:
```python
from typing import List, Dict
from collections import Counter
def find_top_k_keys(data: Dict[str, int], k: int) -> List[str]:
"""
Finds the k keys with the highest frequencies in a dict. The keys are strings and the v... | Write a Python function to find k most frequent keys in a dict, where the keys are strings and the values are integers. Utilize the `collections.Counter` class to count the occurrences of values for each key. Return a list of keys with the highest frequencies.
Your code should pass the following assertion:
```python
a... | You can achieve this by using the `Counter` class from the `collections` module, which makes it easy to count the occurrences of elements. Below is a Python function that implements the required functionality to find the k most frequent keys in a dictionary:
```python
from collections import Counter
def find_top_k_ke... | 9,131 |
```python
import datetime
def convert_date_formats(dates):
new_dates = []
for date in dates:
try:
date_obj = datetime.datetime.strptime(date, "%d/%m/%Y")
except ValueError:
continue
new_date = date_obj.strftime("%m/%d/%Y")
new_dates.append(new_date)
... | Create a Python function to convert a list of dates from one format to another. The function should accept a list of strings containing dates in a specific format and return a list of strings with the converted format. The specific formats are "dd/mm/yyyy" and "mm/dd/yyyy".
- The first format ("dd/mm/yyyy") is a strin... | You can create a Python function to convert between the two specified date formats as follows. We'll use the `datetime` module for parsing and formatting the dates. Here’s how you can implement the function:
```python
from datetime import datetime
def convert_date_format(dates, to_format):
"""
Convert a list ... | 9,132 |
Here's how you could write a Python function to check if a value is a positive integer, positive float number, or not a number:
```python
def check_number_type(value):
if isinstance(value, int):
if value > 0:
return "Positive integer"
else:
return "Not a positive integer"
... | Write a Python function to check whether a given value is a positive integer, positive float number, or not a number at all. If the value is a float, it should be represented as a string with at least one digit before and after the decimal point.
For example, `123` is a positive integer, `12.34` is a positive float, a... | You can achieve this by defining a Python function that checks the type and value of the input. Here's a function that implements the required checks:
```python
def check_value(value):
if isinstance(value, int) and value > 0:
return 'Positive Integer'
elif isinstance(value, float) and value > 0:
... | 9,133 |
You can use the `functools` library and the `operator` library to create a function that combines multiple `get_name()` functions into a single one. Here's how you can do it:
1. Import the `functools` and `operator` libraries.
2. Define a function that takes a variable number of arguments (by using `*args`) representi... | I have several Python functions of the form `get_name()` that I want to combine into a single Python function that returns a tuple `(name, num_items)`. The `get_name()` functions return the name of a piece of data, and `num_items` is the total number of items that the function returns. The function is composed of the g... | To combine multiple `get_name()` functions into a single function that returns a tuple `(name, num_items)`, you can create a new function that calls each of the provided `get_name()` functions, aggregates their names and counts, and constructs the desired output.
Here's a sample implementation to achieve this, assumin... | 9,134 |
To implement a Python function that computes `2 * x + y`, you can follow these steps:
1. Identify the inputs and outputs of the function. In this case, the inputs are two integers `x` and `y`, and the output is the result of `2 * x + y`.
2. Design the function's interface. In this case, the function has two arguments,... | Implement a Python function named `double_add(x, y)` that computes `2 * x + y`. The function should accept two integers as input arguments `x` and `y` and return the result of `2 * x + y`. Include a docstring that describes the function and its arguments.
Your code should pass the following assertions:
```python
asser... | Here is the implementation of the `double_add` function in Python:
```python
def double_add(x: int, y: int) -> int:
"""
Computes the value of 2 * x + y.
Parameters:
x (int): The first integer to be doubled.
y (int): The second integer to be added.
Returns:
int: The result of 2 * x + y.
... | 9,135 |
```python
def matrix_to_list_of_tuples(matrix):
result = []
for row_index, row in enumerate(matrix):
for col_index, element in enumerate(row):
result.append((element, row_index, col_index))
return result
```
This implementation iterates through the matrix using two nested loops, with on... | Design a Python function that takes a matrix (list of lists) as input and returns a list of tuples, where each tuple contains the element and its corresponding row and column indices. For example, given `matrix = [[1, 2], [3, 4]]`, the function should return `[(1, 0, 0), (2, 0, 1), (3, 1, 0), (4, 1, 1)]`.
If the matri... | You can create the desired function by using list comprehensions to iterate over the matrix and capture the elements along with their respective row and column indices. Here’s how you can implement such a function:
```python
def matrix_with_indices(matrix):
# Check if the matrix is empty
if not matrix:
... | 9,136 |
VCR is a Python library for mocking HTTP requests in automated tests. A cassette is a recording of a set of HTTP interactions, which can be used to replay those interactions in future test runs.
In your example, the `clean_body_for_vcr` function is designed to clean the response body of a VCR cassette in order to make... | Develop a Python function `clean_body_for_vcr` to clean the response body of a `vcrpy` (https://github.com/kevin1024/vcrpy) cassette in order for it to be replayed correctly. This task entails removing headers, cookies, and other sensitive information to obfuscate the request and response, while preserving the essentia... | To develop a Python function `clean_body_for_vcr` for cleaning the response body of a `vcrpy` cassette, we want to remove any sensitive information such as headers and cookies, but retain the essential structure of the response data. This is usually done by utilizing regular expressions to target the patterns of data t... | 9,137 |
You can use the `itertools` Python module to generate all possible combinations of elements from both lists and then filter out the invalid tuples that contain duplicate elements from either list.
Here's how you could do it:
```python
import itertools
def distinct_tuples(A, B):
combinations = itertools.product(A... | Implement a Python function that accepts two lists `A` and `B`, both containing integers. The function should return a list of tuples, where each tuple contains two elements. The first element is from `A`, the second element is from `B`. The function should ensure that no two tuples share an element from the same list ... | To achieve this functionality, we can implement a function that generates all possible tuples `(a, b)` where `a` is from list `A` and `b` is from list `B`, while ensuring that each tuple contains distinct elements from the lists. We will utilize nested loops to create these tuples and use a condition to check if the el... | 9,138 |
Here's how you could implement such a function in Python:
```python
import uuid
def generate_uuid_with_structure(num_uuids: int) -> dict:
uuid_with_structure = {}
for _ in range(num_uuids):
generated_uuid = str(uuid.uuid4())
uuid_structure = (generated_uuid, len(generated_uuid), len(generated... | Write a Python function to generate random UUIDs and store them in a dictionary. The function should accept an integer parameter specifying the number of UUIDs to generate. The function should return a dictionary where the keys are UUIDs and the values are a tuple of a predefined structure. The structure should include... | Sure! Below is an implementation of a Python function that generates random UUIDs and stores them in a dictionary. The dictionary's keys will be the generated UUIDs, and the values will be tuples containing the UUID as a string, the length of the UUID, and the number of digits in the UUID.
Here's the code:
```python
... | 9,139 |
To extract the default argument values of a function, you need to ensure that:
1. The function has a signature, which can be obtained using `inspect.signature(func)`.
2. The signature is a `inspect.Signature` object, which has an `parameters` attribute.
3. The `parameters` attribute is a dictionary mapping parameter n... | Create a Python function `get_func_args(func)` that takes a function object as input and returns a dictionary of keyword arguments and their default values. The function should extract the function's signature, including any default argument values, and convert it into a dictionary. The keys of the dictionary should be... | You can achieve this by using the `inspect` module, which provides several helpful functions to retrieve information about live objects, including functions. The `signature` function from the `inspect` module can be utilized to get the parameters of the function and their default values.
Here is the implementation of ... | 9,140 |
To convert a `uint32` integer from little-endian to big-endian, we need to first understand how little-endian and big-endian represent integers. Little-endian is a byte ordering in which the least significant byte (LSB) is stored at the smallest address, while big-endian is a byte ordering in which the most significant... | Write a Python function named `convert_endianness` that takes a `uint32` integer in little-endian format and returns the corresponding value in big-endian format.
Note: You are not allowed to use the Python standard library's `struct` module or any equivalent. Instead, you must use the `ctypes` module to access the sy... | You can use the `ctypes` module to manipulate binary data directly. Below is a Python function named `convert_endianness` that takes a `uint32` integer in little-endian format and returns the corresponding value in big-endian format:
```python
import ctypes
def convert_endianness(uint32le):
# Create a ctypes.c_ui... | 9,141 |
To write this function, we can use a regular expression to match different patterns of names and apply different formatting rules accordingly. The regular expression can capture names with different formats and special characters, and we can handle each case separately to format the names properly.
Here's an example i... | Write a Python function named `split_and_format_person_names` that takes a list of names and formats them according to the following rules:
- If the name contains a single word, it should be capitalized.
- If the name contains multiple words, it should be capitalized and separated by spaces.
- If the name contains hyp... | Certainly! Below is a Python function named `split_and_format_person_names` which adheres to the specified formatting rules for names. The function processes a list of names and formats them accordingly.
```python
import re
def split_and_format_person_names(names):
formatted_names = []
for name in names:
... | 9,142 |
Here's the code for the Python function:
```python
import re
def parse_and_evaluate(expression):
try:
expression = re.sub(r'\s+', '', expression)
result = eval(expression)
return result
except (NameError, SyntaxError, TypeError):
return 'Invalid expression'
``` | Create a Python function to parse a string representation of a mathematical expression and evaluate it. The string may contain numbers, operators (+, -, *, /), parentheses, and spaces. Handle any possible exceptions gracefully and return an error message if the expression is invalid. Also, make sure to include an examp... | You can create a function called `parse_and_evaluate` which utilizes Python's `eval` function to evaluate mathematical expressions. However, to ensure safety and handle exceptions gracefully, you'll need to catch any errors that arise during evaluation.
Below is a Python implementation of the `parse_and_evaluate` func... | 9,143 |
To calculate the difference between two lists, we can use the set operations like `difference` and `intersection`. `difference` returns a set containing all the elements in the first set but not in the second, and `intersection` returns a set containing all the elements that are common in both sets.
Here's how we can ... | Write a Python function `calculate_difference(list1, list2)` that returns the difference between the lists (items in `list1` but not in `list2`) using set operations. | You can use set operations in Python to calculate the difference between two lists efficiently. Here is the function `calculate_difference` that takes two lists as input and returns the items present in `list1` but not in `list2`.
```python
def calculate_difference(list1, list2):
# Convert lists to sets
set1 =... | 9,144 |
```python
import json
def validate_flight_info(json_string):
try:
flight_info = json.loads(json_string)
except json.JSONDecodeError:
return False
required_keys = ["origin", "destination", "airline"]
if not all(key in flight_info for key in required_keys):
return False
if no... | Design a Python function to parse and validate a JSON object containing flight information. The JSON object should contain `origin`, `destination`, and `airline` keys, where `origin` and `destination` are strings and `airline` is an array of strings. The function should validate that all keys are present, and that `ori... | You can create a Python function to parse and validate the specified JSON object as follows:
```python
import json
def validate_flight_info(json_str):
try:
# Parse the JSON string
flight_info = json.loads(json_str)
# Check for required keys
if not all(key in flight_info for key in... | 9,145 |
Here's how you could do it:
```python
import re
def extract_id(comment):
match = re.search(r'ID: (\d+)', comment)
if match:
return match.group(1)
else:
return None
```
This function uses the `re.search` function to search for a pattern matching "ID: " followed by one or more digits (`\d+`... | I have a comment field that contains a string of the form "ID: XXX", where XXX is a string of digits. I need to extract the XXX part of this string. Write a Python function to extract the XXX part of the string. | Sure! You can use Python's regular expressions (regex) to extract the numeric part (XXX) from the string. Below is a simple function that does this:
```python
import re
def extract_id(comment):
# Use regex to search for the pattern 'ID: XXX'
match = re.search(r'ID:\s*(\d+)', comment)
if match:
ret... | 9,146 |
To implement the recursion using dynamic programming, you can use a dictionary to store the previously computed results. This way, you can avoid repeated computations and achieve a more efficient solution.
Here's how you can implement the function using dynamic programming in Python:
```python
def fibonacci(n):
f... | Write a Python function following the following recursion:
$$
f(n) = \begin{cases}
1 & \text{if } n = 0 \\
2 & \text{if } n = 1 \\
f(n - 1) + f(n - 2) & \text{if } n > 1
\end{cases}
$$
Implement the function using dynamic programming, which can be achieved by using a dictionary to store previously compute... | To implement the recursive function `f(n)` as described using dynamic programming, we will use a dictionary to store previously computed results. This will help us avoid redundant calculations and improve efficiency.
Here is the Python function:
```python
def fibonacci(n, memo=None):
# Initialize the memoization ... | 9,147 |
To construct such a sentence, we can use the following steps:
1. Retrieve the `name` and `color` from the input dictionary.
2. Use string formatting to construct the sentence with the given values.
Here is a Python function `create_sentence` that implements the above steps:
```python
def create_sentence(dictionary: ... | Given a dictionary of strings with a `name` and a `color` (e.g., `{"name": "apple", "color": "red"}`), write a Python function `create_sentence` that constructs a sentence such as "The color of the apple is red."
Your code should pass the following test case:
```python
# Provided example
assert create_sentence({"name"... | You can create the `create_sentence` function as follows:
```python
def create_sentence(fruit):
return f"The color of the {fruit['name']} is {fruit['color']}."
# Test cases
assert create_sentence({"name": "apple", "color": "red"}) == "The color of the apple is red."
assert create_sentence({"name": "banana", "colo... | 9,148 |
Here is a possible implementation using Python's `get` method:
```python
def lookup_name_count(obj):
name = obj.info.get('name')
count = obj.info.get('count')
if name is not None and count is not None:
return [name, count]
return None
``` | Given a Python object that has a property `info` which is a dictionary, define a function that looks up two keys `name` and `count` from the `info` dictionary and return their values as a list. If either key is absent, the function should return the value `None`. | You can define a function to achieve this as follows:
```python
def get_name_and_count(obj):
# Check if the obj has the 'info' property
if hasattr(obj, 'info'):
info = obj.info
# Try to get the values for 'name' and 'count'
name = info.get('name')
count = info.get('coun... | 9,149 |
Here's how you could implement the `sample_data_batches` function:
```python
import random
def sample_data_batches(data, batch_size, shuffle=False):
if shuffle:
random.shuffle(data)
if batch_size > len(data):
return [data]
batches = []
while len(data) > 0:
batch = data[:batch_s... | Create a Python function `sample_data_batches` that takes three arguments: `data`, a list of data points, `batch_size`, the number of data points in each batch, and `shuffle`, a boolean indicating whether to shuffle the data before generating the batches. The function should return a list of data batches, where each ba... | To create a function `sample_data_batches` that meets your requirements, we can follow these steps:
1. Shuffle the data if the `shuffle` argument is set to `True`.
2. Generate batches of the specified `batch_size` from the data list.
3. Return a list containing all the batches.
Here's how you can implement this funct... | 9,150 |
Here's an example implementation of the function using a `switch` statement:
```python
def bool_func(input_string):
switcher = {
'a': True,
'b': False,
'c': True,
'd': True,
'e': False,
'f': False,
'g': True,
'h': True,
'i': True,
'j':... | Write a Python function that returns a Boolean value based on the following input strings:
- `a` returns `True`
- `b` returns `False`
- `c` or `d` returns `True`
- `e` or `f` returns `False`
- `g` or `h` or `i` or `j` returns `True`
- `k` or `l` or `m` or `n` returns `False`
- Any other input returns `False`
Call th... | You can implement the specified logic in the function `bool_func` as follows:
```python
def bool_func(input_str):
if input_str == 'a':
return True
elif input_str == 'b':
return False
elif input_str in ('c', 'd'):
return True
elif input_str in ('e', 'f'):
return False
... | 9,151 |
To write a Python function that maps boolean values to strings representing colors, you can follow these steps:
1. Define a dictionary that maps boolean values to strings, such as `{'True': 'green', 'False': 'red'}`.
2. Define a function that takes a boolean value as input and returns the corresponding color.
3. Check... | Write a Python function `convert_boolean_to_color` that accepts a boolean value as input and returns a string representing the color. The function should map `True` to `'green'` and `False` to `'red'`. Additionally, provide hardcoded values for the colors, such as `'green': '#00FF00'` and `'red': '#FF0000'`.
Your code... | Here's the implementation of the function `convert_boolean_to_color` that meets your requirements:
```python
def convert_boolean_to_color(value: bool) -> str:
# Define the mapping for colors
colors = {
True: '#00FF00', # green
False: '#FF0000' # red
}
return colors[value]
# Assertion... | 9,152 |
To write a Python function that takes arguments `event_queue` and `timeout`, and returns the first event from the `event_queue` after `timeout` seconds if no events are available until then. If there are no events in the queue, the function should return `None`:
1. Check if the event queue is empty. If it is, return `... | Write a Python function `event_handler` that takes arguments `event_queue` and `timeout`, and returns the first event from the `event_queue` after `timeout` seconds if no events are available until then. If there are no events in the queue, the function should return `None`. | To implement the `event_handler` function, we can use Python's built-in `queue` module, which provides a thread-safe `Queue` class. We can leverage this along with the `time` module to handle the timeout. The idea is to wait for events to be added to our event queue until the timeout occurs, returning the first availab... | 9,153 |
To parse a string of the format "X,Y,Z" into a list of three integers X, Y, and Z, we can use the `split` method to split the string into a list of strings, and then convert each string into an integer using the `int` function. Finally, we can return the list of integers.
```python
def parse_str(s):
nums = s.split... | Write a Python function to parse a string of the format "X,Y,Z" into a list of three integers X, Y and Z. | You can create a Python function that takes a string formatted as "X,Y,Z", splits the string by the comma, and converts each component into an integer. Here’s a simple implementation of that:
```python
def parse_coordinates(coordinate_str):
# Split the string by commas
parts = coordinate_str.split(',')
... | 9,154 |
You can create a Python function to sort a list of integers, treating None and NaN values as zero. This function should handle corner cases such as empty lists and null/None values gracefully. It should return a new list and should not modify the original list.
Here's how you could implement this function:
```python
... | Create a Python function to sort a list of integers in ascending order. Treat None and NaN values as zero. Handle corner cases like empty lists and null/None values gracefully. The function should return a new list and should not modify the original list.
Your code should pass the following test case:
```python
number... | Certainly! Below is a Python function that sorts a list of integers while treating `None` values as zero, handling empty lists and null values gracefully. It will return a new sorted list without modifying the original list.
```python
def sort_integers(numbers):
# Replace None and NaN (not a number) with 0
pro... | 9,155 |
Here's one possible implementation:
```python
def get_first_index(collection, predicate):
for i, item in enumerate(collection):
if predicate(item):
return i
return -1
```
This function iterates through the collection using a `for` loop and the `enumerate()` function to retrieve the index o... | Write a Python function `get_first_index` that accepts a list and a lambda function. The function should iterate through the collection and return the index of the first element that satisfies the lambda function. If the item does not exist, return -1.
Your code should pass the following test case:
```python
numbers =... | Here’s a Python function `get_first_index` that implements the required behavior. The function takes a list and a lambda function as arguments, iterates through the list, and returns the index of the first element that satisfies the lambda condition. If no element satisfies the condition, it returns -1.
```python
def ... | 9,156 |
To check if an array is out of order, we need to compare the elements of the array and determine whether they are sorted in ascending order.
We can iterate through the array and compare each element with the next element. If an element is greater than the next element, we can conclude that the array is out of order.
... | Write a Python function to check if an array (or list) is "out of order." An array is out of order if two elements' positions in the array are out of order (i.e., a[i] > a[j] but i < j). | Certainly! To determine if an array is "out of order", we can iterate through the array and check if there exists any pair of indices i and j such that `i < j` and `a[i] > a[j]`. If we find such a pair, the array is out of order. Here’s a Python function that implements this logic:
```python
def is_out_of_order(arr):
... | 9,157 |
Here's an example implementation of the function:
```python
def pack_integers_to_bits(integers):
packed_bits = []
for integer in integers:
binary_string = bin(integer)[2:]
if len(binary_string) < 32:
binary_string = binary_string.zfill(32)
packed_bits.append(binary_string)
... | Write a Python function to pack a list of integers into binary strings with the length of each integer represented by 32 bits.
Your code should pass the following test case:
```python
integers = [0, 1, 2]
expected_bits = ['00000000000000000000000000000000', '00000000000000000000000000000001', '000000000000000000000000... | You can write a function to pack a list of integers into 32-bit binary strings. In Python, you can achieve this using the built-in `format` function or using formatted string literals. Here's one way to implement the `pack_integers_to_bits` function:
```python
def pack_integers_to_bits(integers):
return [format(i,... | 9,158 |
Here is a Python function that implements the described sorting criteria using the `sorted()` function:
```python
def sort_objects(objects):
"""
Sorts the objects in-place based on the specified criteria.
"""
def key_function(obj):
return obj["id"], -obj["timestamp"], -obj["weight"]
sorted... | Given a list of objects as input, write a Python function to sort the objects in-place based on their field values in the following order: `id`, `timestamp`, and `weight`. If two objects have the same `id`, then the objects with newer `timestamp` should be placed before the objects with older `timestamp`. If two object... | To sort a list of objects in Python based on multiple criteria, you can use the built-in `sorted()` function along with a custom key or the `sort()` method directly on the list. In this case, since we want to sort the objects in-place, we will use the `sort()` method.
Here is a sample implementation of the function yo... | 9,159 |
We can use Python string formatting techniques to construct the desired JIRA codeblock string from the given codeblock string and language. The JIRA codeblock format requires wrapping the codeblock string within two lines of `{language}` and `{/language}` in order to properly format the codeblock.
Here is the implemen... | Write a Python function to annotate the given codeblock string in JIRA format. The function should take two arguments, `codeblock` and `language`. The function should return a string with the codeblock string formatted as a JIRA codeblock with the given language. The JIRA codeblock format should be as follows:
```
{la... | You can create a function in Python to format a given codeblock according to the JIRA codeblock format specified. Below is the implementation of such a function:
```python
def annotate_codeblock(codeblock, language):
return f'{{sourcecode language="{language}"}}\n{codeblock}\n{{/sourcecode}}'
# Example usage:
cod... | 9,160 |
Here's how you could implement this function:
```python
def convert_table(table, conversions):
for row in table:
for col, target_type in conversions:
if col in row and type(row[col]) != target_type:
row[col] = target_type(row[col])
return table
``` | Implement a Python function that takes a table as input and returns the same table with some of the columns converted to a different type. The function takes two arguments: `table`, a list of dictionaries, and `conversions`, a list of tuples, where each tuple contains the name of a column to be converted and the target... | You can implement the desired functionality in Python by creating a function that iterates over each row in the given table and applies the specified conversions based on the provided conversions list. Here's how you can do that:
```python
def convert_table_columns(table, conversions):
for row in table:
fo... | 9,161 |
```python
def format_number_with_three_decimal_places(number):
if abs(number) < 0.1:
return f"{abs(number):.3f}"
elif abs(number) < 1:
return f"{int(round(number))}"
else:
return f"{number:.3f}"
```
The `format_number_with_three_decimal_places()` function takes a number as an input ... | Write a Python function to format a number with three decimal places, and enforce the following rules:
- If the number's absolute value is less than 0.1, output its absolute value.
- If the number's absolute value is less than 1, output the nearest integer.
- If the number's absolute value is greater than or equal to ... | You can create a Python function that formats a number according to the specified rules. Below is the implementation of that function along with the invocation for the number `0.000345`:
```python
def format_number(num):
# Check if the absolute value is less than 0.1
if abs(num) < 0.1:
return f"{abs(nu... | 9,162 |
Here's how we can implement this check:
```python
def check_nested_field(obj):
if hasattr(obj, 'nested') and hasattr(obj.nested, 'field'):
return f"field:{obj.nested.field}"
else:
return "field:none"
```
First, we check if `obj` has an attribute named `nested` using `hasattr(obj, 'nested')`. I... | Write a Python function that takes one argument `obj`. Implement a check to see whether `obj` has a field `obj.nested.field`. If present, return the string `"field:value"` where `value` is the value of `obj.nested.field`. Otherwise, return `"field:none"`. | You can achieve this by defining a function that uses Python's `getattr` function for safe attribute access. Here's a sample implementation of your requirement:
```python
def check_nested_field(obj):
# Attempt to get the value of the nested field
try:
value = getattr(getattr(obj, 'nested'), 'field')
... | 9,163 |
Here's how you could implement this function:
```python
import pandas as pd
def get_unique_column_values_df(df, column_name):
return pd.Series(df[column_name].unique()).sort_values().tolist()
``` | Write a Python function called `get_unique_column_values_df(df, column_name)` that reads a `pandas.DataFrame` as input and returns a sorted list of unique values contained in a specific column of the DataFrame. Use the `set` data structure to store unique values and avoid duplicate values. Also, use Pandas DataFrame me... | You can create the `get_unique_column_values_df` function as follows:
```python
import pandas as pd
def get_unique_column_values_df(df, column_name):
# Use the Pandas unique() method to get unique values from the specified column
unique_values = df[column_name].unique()
# Convert the result to a set to r... | 9,164 |
To determine if a string ends with a question mark or an exclamation mark, we can use the `endswith()` method of the string class. This method takes a string argument and returns `True` if the string ends with that argument. We can call the `endswith()` method on the string with `?` or `!` as the argument to check if i... | Write a Python function to determine if a string ends with a question mark or an exclamation mark, and return `True` if it does, `False` otherwise.
Your code should pass the following assertion:
```python
assert ends_with_question_or_exclamation('How are you?') == True
``` | You can achieve this by creating a function called `ends_with_question_or_exclamation` that checks if the last character of the string is either a question mark (`?`) or an exclamation mark (`!`). Here's a possible implementation:
```python
def ends_with_question_or_exclamation(s):
return s.endswith('?') or s.ends... | 9,165 |
To check if a given value is not a string or bytes object, you can use the `isinstance` function to check the type of the value. The `isinstance` function takes two arguments: the value to check and the type to compare it against. It returns `True` if the value is an instance of the given type, and `False` otherwise. Y... | Write a Python function `is_not_str_or_bytes` to check if a given value is not a string or bytes object. Your function should check for both string and bytes types, and should not rely on any external libraries or built-in functions. Use `isinstance` to check the types.
Your code should pass the following assertions:
... | You can define the `is_not_str_or_bytes` function using the `isinstance` function to check the types of the input value. The function should return `True` if the value is neither a `str` nor a `bytes` object, and `False` otherwise. Here's how you can implement it:
```python
def is_not_str_or_bytes(value):
# Check ... | 9,166 |
You can use the `re` module to search for the pattern in text and count the occurrences using the `findall` method.
Here's a Python function that implements this logic:
```python
import re
def count_pattern_occurrences(pattern, text):
return len(re.findall(pattern, text))
```
The `re.findall` method returns a l... | Write a Python function to count the number of occurrences of a given pattern in a given text. The function should take two parameters: `pattern` and `text`. The `pattern` is a string that represents a regular expression, and the `text` is a string that represents the text to be searched. The function should return the... | To count the number of occurrences of a pattern in a given text using regular expressions in Python, we can utilize the `re` module. We can use the `re.findall` function, which finds all non-overlapping occurrences of the pattern and returns them as a list. The length of this list will give us the count of occurrences.... | 9,167 |
Here's how you can write the Python function:
```python
def time_string(seconds):
hours = seconds // 3600
minutes = (seconds % 3600) // 60
seconds = (seconds % 3600) % 60
return f"{hours}:{minutes}:{seconds}"
``` | Create a Python function that takes a number of seconds and returns a string representation of the time in the format "{H}:{M}:{S}", where "H", "M", and "S" are the number of hours, minutes, and seconds, respectively. For example, given 3661 seconds, the function should return "1:1:1". | You can achieve this by creating a function that takes the number of seconds and converts it to hours, minutes, and seconds. Here is a sample implementation:
```python
def seconds_to_hms(seconds):
hours = seconds // 3600 # 1 hour = 3600 seconds
minutes = (seconds % 3600) // 60 # 1 minute = 60 seconds
sec... | 9,168 |
The function should be able to handle various cases, including invalid indices, missing values, invalid tensors, and unequal dimensions between the tensor and the index.
1. **Invalid index**: The function should handle invalid indices by returning `None`. This can be achieved by checking if the length of the index lis... | Develop a function to fetch value from a tensor given its index. The function takes two arguments, `tensor` and `idx`. The `tensor` is a multidimensional tensor represented as a nested list, and `idx` is a list of integers representing the index of the element to fetch.
For example, given the tensor `[[[1, 2], [3, 4]]... | You can create a function called `fetch_value_from_tensor` that encompasses all the required functionalities as per your specifications. Here's how the function can be implemented:
```python
def fetch_value_from_tensor(tensor, idx):
# Check if tensor is a valid list
if not isinstance(tensor, list) or any(not i... | 9,169 |
Here's how you could implement the `get_board_state` function in Python:
```python
def get_board_state(board, player):
possible_states = []
for row in range(len(board)):
for col in range(len(board[row])):
if board[row][col] == 0:
next_state = [row, col, player]
... | Write a Python function `get_board_state(board, player)` that takes two arguments: `board` is a list of lists representing the current tic-tac-toe game board, and `player` is either 1 or 2, representing the player making the next move. The function should return a list of lists, representing the possible board states f... | To create the `get_board_state` function for generating possible board states in a tic-tac-toe game, we need to look for empty spots on the board where the current player can place their marker. The function will iterate through the board and compile a list of potential moves for the given player. Let's implement this ... | 9,170 |
We can implement this using the following code:
```python
def get_value_of_first_key(data):
if isinstance(data, dict):
return data[list(data.keys())[0]]
elif isinstance(data, list):
for item in data:
if isinstance(item, dict):
return item[list(item.keys())[0]]
re... | Write a Python function `get_value_of_first_key(data)` that returns the value of the first key in the given `data` argument. The `data` argument can be a dictionary or a list of dictionaries. If `data` is a dictionary, return the value of the first key. If `data` is a list of dictionaries, return the value of the first... | Certainly! Below is a Python function `get_value_of_first_key(data)` that implements the specified functionality:
```python
def get_value_of_first_key(data):
# Check if the data is a dictionary
if isinstance(data, dict):
# Get the first key from the dictionary
first_key = next(iter(data), None)... | 9,171 |
We'll approach this problem by iterating through the input list and comparing its elements against the input set. If any element is found in both the list and the set, we'll return `True` to indicate a duplicate exists. If we finish iterating through the list without finding any duplicates, we'll return `False`.
Here ... | Design a Python function with the following signature and docstring:
```python
def check_dups(input_list, input_set):
"""
Checks if elements in input_list and input_set have any duplicates in common.
Parameters:
input_list (list): A list of values to check for duplicates.
input_set (set): ... | Here is a Python function that meets your requirements, along with the appropriate implementation to check for duplicates between the `input_list` and `input_set`:
```python
def check_dups(input_list, input_set):
"""
Checks if elements in input_list and input_set have any duplicates in common.
Parameters:... | 9,172 |
Here's the code to implement the function:
```python
def layer_number_from_string(layer_string: str) -> int:
layer_number = int(layer_string.replace('layer_', ''))
return layer_number
```
The function `layer_number_from_string` takes a string as input and returns the layer number as an integer. It uses the re... | Write a Python function to infer a layer number and layer name from an input string. The input will be in a format of `layer_n`, where n is the layer number. For example, `layer_10` refers to the 10th layer. The function should return (0, 'layer_1') for `layer_0`, (1, 'layer_1'), (2, 'layer_2'), ..., (10, 'layer_10'), ... | You can create a function that extracts the layer number from the input string and then constructs the corresponding layer name based on that number. Here's a simple implementation:
```python
def infer_layer(input_string):
# Strip any leading or trailing whitespace
input_string = input_string.strip()
... | 9,173 |
Here's how you can do it in one line of Python code:
```python
def sum_multiples(n):
return sum(num for num in range(1, n) if num % 3 == 0 or num % 5 == 0)
```
The `range` function creates a sequence of numbers from 1 to n-1 (excluding n), and the `sum` function adds them together. The `if` clause in the list com... | Write a Python function to calculate the sum of all multiples of 3 or 5 below a given number n.
Your code should pass the following assertion:
```python
assert sum_multiples(10) == 23
``` | You can calculate the sum of all multiples of 3 or 5 below a given number \( n \) using a simple loop or a comprehension. Below is a Python function that accomplishes this task:
```python
def sum_multiples(n):
return sum(i for i in range(n) if i % 3 == 0 or i % 5 == 0)
# This assertion will check that our functio... | 9,174 |
```python
def reverse_endianness(byte_string):
return bytes(reversed(byte_string))
``` | Write a Python function that reverses the endianness of a byte string. The function should take a byte string as input and return a new byte string with the endianness reversed. For example, given the byte string b'\x01\x02\x03\x04', the function should return b'\x04\x03\x02\x01'. | You can achieve the reversal of the endianness of a byte string by slicing it in reverse order. Here's a simple Python function to do that:
```python
def reverse_endianness(byte_string):
return byte_string[::-1]
# Example usage
input_bytes = b'\x01\x02\x03\x04'
output_bytes = reverse_endianness(input_bytes)
print... | 9,175 |
Here's how you can implement this:
```python
def safe_index(string, substring, start):
if not isinstance(string, str) or not isinstance(substring, str) or not isinstance(start, int):
print("Invalid input type.")
return -1
if start < 0 or start >= len(string):
print("Invalid start index... | Write a Python function `safe_index(string, substring, start)` that searches for a substring within a string, starting at the specified index. The function should return the index of the substring if it is found. If the substring is not found or if an invalid index is provided, the function should log the error message... | To create the `safe_index` function in Python, we need to ensure that we handle the cases where the index is invalid and where the substring is not found. The function should log an appropriate error message and return -1 in those situations. Here’s how you can implement this:
```python
def safe_index(string, substrin... | 9,176 |
You can create an HTML element by using the `element` argument to open and close the tag and by iterating through the keys and values of the `attributes` dictionary to add attributes to the tag.
Here's how you can define the function in Python:
```python
def generate_element(element, attributes):
tag = f"<{elemen... | Write a Python function to generate a list of strings that represent the HTML tags for a given HTML element. The function's arguments should be `element`, a string representing the element's name (e.g., 'p' for a paragraph tag), and `attributes`, a dictionary containing key-value pairs for attribute names and values.
... | Here’s a Python function that generates an HTML tag as a string based on the provided element name and attributes. The function will properly format the attributes and construct the tag accordingly.
```python
def generate_element(element, attributes):
# Start building the tag
tag = f'<{element}'
# Add att... | 9,177 |
Here is the implementation of the function using a set:
```python
def check_for_duplicates(nums):
unique_nums = set()
for num in nums:
unique_nums.add(num)
return len(unique_nums) < len(nums)
``` | Write a Python function that takes a list of numbers and checks whether there are any duplicate values in the list. The function should return True if there are any duplicates and False otherwise.
For example, given the list [1, 2, 3, 4, 5, 6, 7, 8, 9, 3], the function should return True because the number 3 appears t... | You can create a Python function to check for duplicates in a list by using a set to keep track of the seen numbers. Here’s a simple implementation of such a function:
```python
def has_duplicates(numbers):
seen = set() # Create an empty set to store seen numbers
for number in numbers:
if number in se... | 9,178 |
Here's how you can implement this function:
```python
def get_user_ids_from_posts(posts):
user_ids = []
for post in posts:
user_ids.append(post['user_id'])
return user_ids
```
This function iterates through the input list and extracts the `user_id` value from each dictionary. It then adds these ex... | Write a Python function `get_user_ids_from_posts` that takes a list of dictionaries representing posts and returns a list of the user IDs of the authors of those posts. The dictionaries have a key-value pair `user_id` that stores this information. | You can create the function `get_user_ids_from_posts` as follows. This function will iterate through the list of post dictionaries and extract the `user_id` from each post, collecting them into a list that it will return.
Here’s how you can implement it:
```python
def get_user_ids_from_posts(posts):
"""
Extra... | 9,179 |
To parse a log file and extract the desired data into an output file, you can follow these steps:
1. Read the log file line by line using `with open(log_file, 'r') as f:`.
2. For each line, check if it's a valid log line by searching for the `:` delimiter.
3. If a valid line is found, split it into parts using `split(... | Write a Python function `extract_log_data` that parses a log file and extracts some data from it. The function should take two string arguments: `log_file` and `output_file`. The `log_file` is a path to a log file, while the `output_file` is the path to the output file where the processed data will be written.
The log... | Certainly! Below is a Python function `extract_log_data` that parses a log file based on the specified format and extracts the desired information into an output file.
```python
def extract_log_data(log_file: str, output_file: str) -> None:
"""
Parses a log file and extracts the level and message to an output ... | 9,180 |
Here's how you could implement a Python function that converts a single-character text string into a decimal number:
```python
def convert_char_to_decimal(text):
if len(text) != 1:
raise ValueError('Invalid input: text must be a single-character string')
decimal_number = ord(text)
if decimal_numbe... | Create a Python function that converts a single-character text string into a decimal number. The function should consider all possible ASCII characters and raise an error for any unrecognized character. Additionally, the function should be designed to be reusable for a variety of conversion tasks.
Your code should pas... | You can create a function called `convert_char_to_decimal` that takes a single-character string as input and converts it to its corresponding ASCII decimal value using the built-in `ord` function. If the input is not a single character, you should raise a `ValueError`. Here's how you can implement this:
```python
def ... | 9,181 |
Here's how you can implement the `get_attribute_from_path` function:
```python
def get_attribute_from_path(obj, path):
keys = path.split('.')
current = obj
for key in keys:
try:
current = getattr(current, key)
except AttributeError:
return None
return current
```... | Write a Python function `get_attribute_from_path` that takes an object and a string representing a path to an attribute as arguments. Return the value of the attribute at the given path, or `None` if the attribute does not exist. Split the path string into individual keys, and use `getattr` to access each key until the... | You can implement the `get_attribute_from_path` function using a loop to traverse the attributes of the object based on the given path. Here's how you can do this:
```python
def get_attribute_from_path(obj, path):
# Split the path string by dots
keys = path.split('.')
# Start with the given object
... | 9,182 |
Here is the Python code to implement this:
```python
def matrix_to_strings(matrix):
result = []
for row in matrix:
row_str = ' '.join(map(str, row))
result.append(row_str)
return result
``` | Design a Python function that takes a 2D array of integers `matrix`, converts it into a 1D array of strings `result`, and concatenate the elements in each row of `matrix` from left to right, followed by a space.
For example, given `matrix = [[1, 2, 3], [4, 5, 6]]`, the result should be `['1 2 3', '4 5 6']`. | To achieve the conversion of a 2D array of integers into a 1D array of strings, we can create a Python function that iterates through each row of the matrix, converts the integers to strings, and concatenates them with a space in between. The final output will be a list of these concatenated strings.
Here's how you ca... | 9,183 |
The `is_json_serializable` function is designed to determine whether a given Python object can be serialized into JSON. This function relies on the `dumps` function from the `json` module, which raises a `TypeError` if the object cannot be serialized.
Here's how you can implement the `is_json_serializable` function:
... | Create a Python function named `is_json_serializable` that takes a Python object and checks whether it can be serialized into JSON. The function should return `True` if the object can be serialized, and `False` otherwise. Type hint the function's argument to accept any Python object.
Your code should pass the followin... | To create the function `is_json_serializable`, we can leverage Python's `json` module, which raises a `TypeError` when we try to serialize an object that cannot be converted to JSON. We can define our function to attempt to serialize the object and catch any exceptions that arise, returning `True` or `False` accordingl... | 9,184 |
Here's an implementation of the `random_code_example` function:
```python
import random
def random_code_example(examples, n):
num_examples_to_sample = len(examples) if n > len(examples) else n
random_examples = random.sample(examples, num_examples_to_sample)
sampled_code_examples = [example.copy() for exa... | Implement a Python function `random_code_example(examples, n)` to randomly sample `n` code examples from the provided `examples` list, which is a list of dictionaries with the following structure:
```json
{
"category": "code generation",
"language": "Python",
"concepts": [
"random number generation",
"ra... | To implement the function `random_code_example(examples, n)`, we will use the `random.sample` function from Python's `random` module. This function allows us to randomly sample unique elements from a list. Here is how we can implement the required function:
```python
import random
def random_code_example(examples, n)... | 9,185 |
Here is a Python function that implements this approach:
```python
import re
def validate_table_name(table_name: str) -> str:
"""
Replaces all non-alphanumeric characters in `table_name` with underscores and returns the modified table name.
"""
return re.sub(r'\W', '_', table_name)
``` | Write a Python function to modify a table name to ensure it does not contain any illegal characters. The function should replace all non-alphanumeric characters, including spaces, dashes, and underscores, with underscores.
Your code should pass the following assertions:
```python
assert validate_table_name('my_table')... | Certainly! Here's a Python function called `validate_table_name` that replaces all non-alphanumeric characters with underscores, which includes handling spaces, dashes, and underscores as described in your requirements:
```python
import re
def validate_table_name(table_name):
# Replace all non-alphanumeric charac... | 9,186 |
Here is the implementation of the function in Python:
```python
def simple_return(x: int) -> int:
"""This function takes a single argument x and simply returns x.
Args:
x (int): The input argument.
Returns:
int: The output of the function, which is the same as the input argument.
"""
... | Write a Python function that takes a single argument x and simply returns x. Write a doc string that describes the function and includes the argument name and type. Make a type hint for the function.
Your code should pass the following assertions:
```python
assert simple_return(5) == 5
assert simple_return(-2) == -2
`... | You can create the function `simple_return` as follows:
```python
def simple_return(x: int) -> int:
"""
Returns the value of x.
Args:
x (int): The input value.
Returns:
int: The same value as x.
"""
return x
# Assertions to verify the function works correctly
assert simple_re... | 9,187 |
Here's how you could do it:
```python
import urllib.parse
def build_query_string(params):
query_params = []
for key, value in params.items():
if isinstance(value, list):
for item in value:
query_params.append(f'{urllib.parse.quote(key)}={urllib.parse.quote(str(item))}')
... | Create a Python function `build_query_string(params)` that takes a dictionary `params` containing URL query parameters as key-value pairs and returns a query string to be appended to a URL. The key and value of each parameter should be URL-encoded. If a key in `params` contains a list, the function should generate a se... | You can achieve this by using the `urllib.parse` module, which provides functions for URL encoding. Below is the implementation of the `build_query_string` function that meets your requirements:
```python
import urllib.parse
def build_query_string(params):
query_parts = []
for key, value in params.items(... | 9,188 |
You can use the `csv` module to read the CSV file and extract the country name for each row in the file. You can return a list of the extracted country names as strings.
Here's how you could do it:
```python
import csv
def get_countries_from_csv(csv_file):
with open(csv_file, 'r') as f:
reader = csv.Dict... | Write a Python function `get_countries_from_csv` that takes a CSV file path as an argument and uses the `csv` module to read the file and extract the country name for each row in the file. The function should return a list of the extracted country names as strings. | Certainly! Below you'll find a Python function `get_countries_from_csv` that uses the `csv` module to read a CSV file and extract country names from it. The function assumes that the country names are located in a specific column, which you'll need to specify. I'll include a parameter `country_column_index` to specify ... | 9,189 |
Here's how you could implement the function using a dictionary:
```python
import numpy as np
def string_to_int_array(string):
character_map = {} # Dictionary to store the mapping of characters to integers
int_array = [] # List to store the integer representations of characters
for i, char in enumerate(st... | Write a Python function that returns a Numpy array containing all of the characters in a given string, where each character is uniquely represented by an integer. For instance, the string 'abc' should return an array [1, 2, 3], since the characters 'a', 'b', and 'c' map to the integers 1, 2, and 3, respectively. Use a ... | You can achieve this by defining a function that creates a mapping from characters to integers and then uses that mapping to convert the input string into a Numpy array of integers. Here's how you can implement that:
```python
import numpy as np
def string_to_int_array(s):
# Create a dictionary to store the mappi... | 9,190 |
Here's how you can implement this function:
```python
import os.path
def is_valid_path(path: str) -> bool:
if not path.startswith('/'):
return False
components = path.split('/')
if any(component in ('.', '..') for component in components):
return False
return True
``` | Write a Python function named `is_valid_path` that takes a path string and returns True if the path is valid. A valid path is defined as follows:
- The path starts with the root `/`
- Each directory or file name is separated by `/`
- The path does not include any `.` or `..` components
If the path is invalid, the fun... | You can create a function named `is_valid_path` that checks the validity of the path according to the specified rules. Here is one way to implement this function in Python:
```python
def is_valid_path(path: str) -> bool:
# Check if the path starts with '/'
if not path.startswith('/'):
raise ValueError(... | 9,191 |
In order to remove all keys and their associated values from a nested dictionary recursively, we can use a recursive function that traverses the dictionary and identifies keys that should be removed. The function should handle nested dictionaries and list-based values.
Here is the implementation of `prune_empty_keys_r... | Design a Python function `prune_empty_keys_recursively(dictionary)` that takes a nested dictionary as input and removes all keys and their associated values from the dictionary recursively. If a key contains None as its value, the key should be removed from the dictionary. The function should not modify the input dicti... | Certainly! Below is a Python function called `prune_empty_keys_recursively` that takes a nested dictionary as input and removes all keys with `None` as their values recursively. The function will create and return a new dictionary without modifying the original one, and it will handle nested dictionaries and lists as w... | 9,192 |
Here is how you can implement the function `negate`:
```python
def negate(bool_value: bool) -> bool:
assert isinstance(bool_value, bool), "Input is not a boolean value"
return not bool_value
```
The function `negate` uses the `not` operator to negate the input `bool_value`. It also includes an `assert` statem... | Design a Python function `negate` that takes a boolean value and returns the logical negation. You can use the `not` operator to accomplish this, but do not use the `!` operator. Make a precondition check through `assert` to ensure the input is a boolean value.
Solve the problem in two lines of code, one for the preco... | You can implement the `negate` function in Python as follows:
```python
def negate(value):
assert isinstance(value, bool), "Input must be a boolean value."
return not value
```
In this code:
1. The first line checks that the input `value` is of type `bool`. If it's not, it raises an AssertionError with a mess... | 9,193 |
Here's a solution using Python's built-in `re` module for regular expression parsing:
```python
import re
def extract_string_between_brackets(text):
match = re.search(r"\[(.*?)\]", text)
if match:
return match.group(1)
else:
return "No match found"
```
The regular expression pattern, `r"\... | Write a Python function called `extract_string_between_brackets(text)` that returns the string enclosed within brackets if it is found, or a default value if not. The function should accept a single argument `text`, a string. The function should use regular expression parsing to extract the string between brackets. If ... | You can implement the `extract_string_between_brackets` function using the `re` module in Python, which provides support for regular expressions. Here's how you can do it:
```python
import re
def extract_string_between_brackets(text):
# Regular expression to find text within brackets
match = re.search(r'\[(.*... | 9,194 |
```python
def decode(encoded_string):
return eval(encoded_string)
```
The `eval` function in Python evaluates a string as a Python expression and returns the resulting value. In our case, the input string is a Python expression that represents a string, so `eval` will return the original string. | Write a Python function to decode a string that contains escaped characters. The input string is encoded using Python's `repr` function.
For example, given `'\n\'`, the function should return `'\n'`. Given `'\\'`, the function should return `'\'`. | You can create a function to decode a string that contains escaped characters by using the built-in `ast` module in Python, which provides a safe way to interpret strings that look like Python literals. Here’s how you can implement such a function:
```python
import ast
def decode_string(encoded_str):
try:
... | 9,195 |
Here's how you can implement this:
```python
from collections import defaultdict
def build_word_frequency_dict(word_list):
word_dict = defaultdict(int) # Initialize default value to 0
for word in word_list:
word_dict[word] += 1
return word_dict
``` | Implement a Python function `build_word_frequency_dict(word_list)` that takes a list of words and returns a dictionary with the words as the keys and the corresponding number of occurrences as the values. If a word appears multiple times in the list, its frequency in the dictionary should increase accordingly. If a wor... | You can implement the `build_word_frequency_dict` function using a simple loop to count the occurrences of each word in the input list. Here's how you can do this:
```python
def build_word_frequency_dict(word_list):
# Initialize an empty dictionary to hold the word frequencies
frequency_dict = {}
# It... | 9,196 |
This problem can be solved using a greedy algorithm. We can start from the first element and keep jumping to the next higher element until we reach the last element or encounter an element that is not higher than the current element. If we reach the last element, we can return `True`, otherwise `False`.
Here is a Pyth... | Write a Python function `is_possible` to determine whether it is possible to jump from the first element of an integer array to the last element by repeatedly jumping to a higher element. Return `True` if it is possible, and `False` otherwise. You can only jump to a higher element if the next element is within the same... | To solve the problem of determining whether it is possible to jump from the first element of an integer array to the last element by only jumping to higher elements, we can use a depth-first search (DFS) approach. This involves exploring all possible jumps from the current position until we either find a way to reach t... | 9,197 |
Here is an example implementation of the `Stack` class in Python:
```python
from typing import TypeVar, Generic
T = TypeVar('T')
class Stack(Generic[T]):
def __init__(self):
self.elements = []
def push(self, element: T) -> None:
self.elements.append(element)
def pop(self) -> T:
i... | Write a template-based generic stack class in Python that supports push, pop, top, and checking if the stack is empty. The class should be implemented using the Python list data structure. The class should be able to handle any data type and should store the elements in a list. The class should have a method to retriev... | Here's a template-based generic stack class in Python that implements the required functionalities using the list data structure. The class allows you to push, pop, check the top element, check if the stack is empty, and retrieve the current size of the stack. In Python, we don't have templates like in C++, but we can ... | 9,198 |
Here's the implementation of the `iter_all_values` function:
```python
from itertools import chain
def iter_all_values(d):
values = []
for k, v in d.items():
if isinstance(v, dict):
values.extend(iter_all_values(v))
elif isinstance(v, list):
values.extend(v)
el... | Develop a Python function `iter_all_values` that takes a dictionary of dictionaries and iterates through all the values, returning them in a flattened list. Each dictionary should be traversed recursively, and the key-value pairs should be validated to be of the same type.
For example, given `d = {'a': {'b': 1, 'c': 2... | To create a function `iter_all_values` that flattens a dictionary of dictionaries recursively, we need to ensure that we check the types of keys and values, and gather all the values in a list. Below is an implementation that accomplishes this:
```python
def iter_all_values(d):
"""
This function iterates throu... | 9,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.