response_seed
stringlengths
53
5.17k
instruction_seed
stringlengths
29
4.02k
response
stringlengths
16
8.81k
__original_row_idx
int64
0
50k
To complete this task, let's refer to the basic formula for converting weight from pounds to kilograms. In Python, we can create a class and a static method within it that accepts a parameter `weight_in_pounds` and calculates the equivalent weight in kilograms. The static method is denoted by the `@staticmethod` decor...
Create a static method in a Python class that converts a weight in pounds to its equivalent in kilograms. The static method should take a single parameter `weight_in_pounds`, which defaults to `100`. The method should return the corresponding weight in kilograms.
You can create a Python class with a static method to convert weight from pounds to kilograms as follows: ```python class WeightConverter: @staticmethod def pounds_to_kilograms(weight_in_pounds=100): # 1 pound is approximately 0.453592 kilograms conversion_factor = 0.453592 weight_in_ki...
13,000
You can achieve this by converting the integer to a string and measuring the length of the string. Here's how you can do it in Python: ```python def num_digits(number): if number < 0: return -1 return len(str(number)) ```
Write a Python function to find the number of digits in a given non-negative integer. Return -1 for negative integers. Your code should pass the following assertion: ```python assert num_digits(123) == 3 ```
You can create a Python function to count the number of digits in a non-negative integer using the following code: ```python def num_digits(n): if n < 0: return -1 # Return -1 for negative integers return len(str(n)) # Convert the number to a string and count the length # Example assertion to test t...
13,001
Here is the implementation of the Python function to compute the md5 hash of a given string: ```python import hashlib def compute_md5_hash(string: str) -> str: md5_hash_object = hashlib.md5() md5_hash_object.update(string.encode('utf8')) return md5_hash_object.hexdigest() ``` This function uses the `hash...
Create a Python function to compute the md5 hash of a given string. Your function should return a string representation of the hash digest. The function should be implemented using a secure hash algorithm. All string encoding and decoding should be done using the `utf8` encoding.
Certainly! You can use Python's built-in `hashlib` library to compute the MD5 hash of a given string. Below is a function that does exactly that. It encodes the string using UTF-8 and then computes the MD5 hash, returning it as a hexadecimal string representation. Here’s the code for the function: ```python import ha...
13,002
Here's how you can implement the `apply_to_mesh` function: ```python def apply_to_mesh(mesh, function, field_name): for node in mesh['nodes']: node[field_name] = function(node) ```
Write a Python function `apply_to_mesh(mesh, function, field_name)` that applies a given function to each node of a mesh and returns a mesh with an additional field. The mesh is provided as a dictionary with keys `nodes`, `edges`, and `faces`. The mesh is guaranteed to be in a valid state, i.e. all nodes are listed in ...
Here's the Python function `apply_to_mesh` that takes a mesh dictionary, a function, and a field name, applying the function to each node and adding the result as a new field in the mesh: ```python def apply_to_mesh(mesh, function, field_name): # Iterate over each node in the mesh for node in mesh['nodes']: ...
13,003
To check the naming convention of a list of dataset files, we need to extract the components from the filenames and compare them with the given pattern. The regular expression pattern is used to extract the components from the filenames, and then we compare each component with the corresponding part of the pattern. He...
Write a Python function `check_dataset_naming_convention` that checks the naming convention of a list of dataset files, given a list of `dataset_files` and a regular expression `pattern`. The function should return `True` if all of the filenames match the pattern. The naming convention pattern is as follows: ``` data...
To implement the `check_dataset_naming_convention` function, we will use the Python `re` module to define a regular expression that adheres to the naming convention you've specified. The function takes a list of dataset filenames and a pre-compiled regular expression pattern, returning `True` if all filenames match the...
13,004
To flatten the list of tuples into a single list of key-string pairs, you can use a list comprehension that iterates over each tuple in the list, extracts the dictionary and list, and then flattens the list of strings using another list comprehension. Additionally, you can handle empty dictionaries and lists by checkin...
You have a list of tuples, where each tuple is a combination of a dictionary and a list of strings. The dictionary contains key-value pairs, where the value is a list of strings. Write a Python function to iterate over this list of tuples and flatten the tuples into a single list of key-string pairs. Additionally, ensu...
To achieve your goal, you can define a function that processes a list of tuples containing a dictionary and a list of strings. The function will flatten these tuples into a single list of key-string pairs, handling empty cases gracefully and ensuring proper structure in the tuples. Below is a Python function that imple...
13,005
Here's a Python function that takes a list of sentences and a vocabulary and returns a list of sentences containing OOV terms: ```python def find_oov_sentences(sentences, vocabulary): oov_sentences = [] vocabulary_set = set(vocabulary) for sentence in sentences: words = sentence.split() if ...
I have a dataset that consists of a list of sentences, each of which is a string. I also have a vocabulary, which is also a list of strings. I want to find all sentences in the dataset that contain at least one out-of-vocabulary (OOV) term, i.e., a term that is not in the vocabulary. Can you write a Python function `f...
Certainly! Below is the implementation of the function `find_oov_sentences` that fulfills your requirement. It checks each sentence in the `sentences` list for any term that is not present in the `vocabulary`. ```python def find_oov_sentences(sentences, vocabulary): # Convert the vocabulary to a set for O(1) avera...
13,006
To solve this problem, we can use regular expressions to match and replace the '#' characters from the first column in each TSV string. Regular expressions provide a flexible and powerful way to handle complex string patterns, making it an efficient solution for this problem. Here is a Python function that uses regula...
Given a list of TSV (tab-separated values) strings, write a Python function to remove the '#' characters from the first column and replace them with spaces. The function should use regular expressions to perform this substitution.
You can achieve this by using Python's `re` module, which provides support for regular expressions. Below is a function that takes a list of TSV strings, removes the `#` characters from the first column, and replaces them with spaces: ```python import re def clean_tsv(tsv_list): cleaned_list = [] for line in ...
13,007
Here is an implementation of the `can_join` function in Python: ```python def can_join(a, b, c): i, j = 0, 0 # Initialize indices for lists a and b for k in range(len(c)): # Iterate over the elements in c if i < len(a) and j < len(b): # Both lists have remaining elements if a[i] <= b[j]:...
Create a Python function `can_join` that checks if it's possible to join two sorted lists `a` and `b` to obtain a sorted list `c`. This is done by inserting elements from `a` and `b` into `c` one by one, while keeping the list sorted at all times. The function should return a boolean value indicating whether it's possi...
To determine if we can join two sorted lists `a` and `b` into a new sorted list `c`, we can use a merging technique similar to that used in the merge step of the Merge Sort algorithm. The key idea here is to attempt to merge the two lists into a single sorted list while maintaining the order. We can accomplish this b...
13,008
```python def generate_python_function(function_name, argument_list, function_body): function_definition = f"def {function_name}({argument_list}):\n\t{function_body}\n" exec(function_definition) return globals()[function_name] ``` The first line of the function defines the function_definition string, which...
Write a Python function named `generate_python_function` that generates a Python function from a string that describes a function's name, argument list, and function body. The argument list should allow for variable-length arguments, keyword arguments, and default values. The function body should take the form of a str...
To create a function that generates a Python function based on a description string, we can utilize the Python `exec` function. Below is an implementation of the `generate_python_function` that can handle variable-length arguments, keyword arguments, and default argument values. The body of the function is executed in ...
13,009
Here's an example implementation of the function: ```python def filter_data_frames(data_frames): filtered_data_frames = [] for data_frame in data_frames: if "party" in data_frame.columns and "state" in data_frame.columns: if data_frame["party"].iloc[0] in ["Democrat", "Republican"]: ...
Create a Python function that takes a list of data frames and returns a list of data frames that contain the columns "state" and "party". The function should filter the data frames in the input list and only keep those that have a "party" column whose value is "Democrat" or "Republican", and contain the column "state".
Certainly! Below is a Python function that takes a list of Pandas data frames and returns a list of data frames that contain both the columns "state" and "party", with the "party" column having values "Democrat" or "Republican". Make sure you have the Pandas library installed to use this function. If you haven't insta...
13,010
To implement the `from_base` function, we can first create a dictionary that maps each digit to its corresponding value in the given base. Then, we can iterate over each digit in the `num_str` and compute the decimal value by multiplying the digit's value by the appropriate power of the given base. Here is a Python fu...
Write a Python function named `from_base` that converts a string representation of an integer from a given base to a decimal number. The function should accept two arguments: `num_str` and `base`. If `base` is not provided, it should default to 2 (binary). The function should also accept any valid string representation...
Here's a Python function named `from_base` that meets your specifications. It converts a string representation of an integer from a given base (or defaults to base 2) to a decimal number: ```python def from_base(num_str, base=2): # Validate the base if base < 2 or base > 36: raise ValueError("Base must...
13,011
To extract the product ID values from the provided XML string, you can use the `xml.etree.ElementTree` module from the Python standard library. This module provides a simple API for parsing and manipulating XML data. Here is the implementation of the `get_product_ids_from_xml` function: ```python import xml.etree.Ele...
Write a Python function named `get_product_ids_from_xml` that retrieves the product ID value from a given XML string and returns it as a list. The XML string has the following format: ```xml <products> <product id="123"> <name>Product 1</name> <price>10.0</price> </product> <product id="456"> <name>P...
To create the function `get_product_ids_from_xml`, we can use Python's built-in `xml.etree.ElementTree` module, which provides functions for parsing and creating XML. We'll parse the given XML string, iterate through the `product` elements, and collect their `id` attributes into a list. Here is the implementation: ``...
13,012
Here is a Python function that implements the desired behavior: ```python def remove_non_digits(s: str) -> str: result = "" for c in s: if c.isdigit(): result += c return result ```
Implement a Python function that removes all characters from a given string that are not numbers (0-9). The function should return the resulting string in a new variable. Your code should pass the following assertions: ```python assert remove_non_digits("123abc456") == "123456" assert remove_non_digits("000abc111") ==...
You can implement the function `remove_non_digits` using a simple comprehension that filters out any character that is not a digit. Here is how you can do it: ```python def remove_non_digits(s): # Using a list comprehension to filter out non-digit characters result = ''.join([char for char in s if char.isdigit...
13,013
To select points from a time-series dataset based on a given interval, you could write a Python function that takes as input a list of tuples representing data points with timestamps and values, and returns a list of tuples containing only the points that fall within a given interval. Here's how you could approach this...
Write a Python function to select points from a time-series dataset based on a given interval. The function should accept as input a list of tuples, each tuple representing a data point with its timestamp and value. The function should then return a list of tuples containing only the points that fall within a given int...
Certainly! Here's a Python function that allows you to select points from a time-series dataset based on a specified interval. The function takes a list of tuples, each representing a data point with its timestamp and value, as well as two timestamps that define the interval. ```python from typing import List, Tuple ...
13,014
Here is the Python function that implements this approach: ```python from typing import Optional def pow_decimal(x: float, y: float, precision: Optional[int] = 10) -> float: """ Computes `x**y` with the specified precision. The default precision is 10. """ value = x ** y rounded = round(value, pre...
Develop a Python function `pow_decimal` that computes `x**y` for given `x` and `y`. The function should accept an optional parameter `precision` that sets the precision of the decimal number. The default value of `precision` should be 10.
To create the `pow_decimal` function that computes `x**y` using Python's `decimal` module with adjustable precision, we can follow these steps: 1. Import the necessary classes and functions from the `decimal` module. 2. Set the precision using the `getcontext().prec` method. 3. Use `Decimal` to create the numbers `x` ...
13,015
Here is how you could implement `run_async_function`: ```python import asyncio from typing import Any, Awaitable, Callable, Optional, TypeVar T = TypeVar("T") async def run_async_function(func: Callable[..., Awaitable[T]], *args: Any, **kwargs: Any) -> Optional[T]: try: result = await func(*args, **kwarg...
Write a Python function `async def run_async_function(func: Callable[..., Awaitable[T]], *args: Any, **kwargs: Any) -> Optional[T]` that takes an asynchronous function `func` with positional and keyword arguments and runs it asynchronously to retrieve its result. If the function fails, it should return `None`.
To create the `run_async_function`, we'll make use of the `asyncio` library in Python, which provides functionality for running asynchronous code. The function will accept an asynchronous function, along with its positional and keyword arguments, and will return the result of the function or `None` if it raises an exce...
13,016
Here's the updated function using a list comprehension: ```python def scale_colors(image_data, scale_factor): return [ (int(r * scale_factor), int(g * scale_factor), int(b * scale_factor)) for (r, g, b) in image_data ] ``` By using a list comprehension, you are transforming the input sequence ...
Here's a function to scale RGB components of an image by a given factor. ```python def scale_colors(image_data, scale_factor): return [ (int(r * scale_factor), int(g * scale_factor), int(b * scale_factor)) for r, g, b in image_data ] ``` Notice that the function uses tuple unpacking to destruc...
The code snippet you've provided already uses a list comprehension to output a new list of scaled RGB components. However, you mentioned converting the generator expression into a list comprehension, which suggests there may have been a misunderstanding. Here's the given function, which is already using a list compre...
13,017
To check if a given string is a valid time string, we can use a regular expression to match the string against a specific pattern. The pattern should include the following requirements: 1. The string should have the format "HH:MM" or "H:MM" 2. The hour value should be a single digit or a two-digit number between 0 and ...
Write a Python function to check if a given string is a valid time string in the format "HH:MM" or "H:MM" (where "H" represents a single digit hour and "MM" represents a two-digit minute). Your function should return `True` if the string is a valid time and `False` otherwise. Your code should pass the following assert...
To create a Python function that checks if a given string is a valid time string in the specified formats, we can use string manipulation and validation. Here is a function that accomplishes that: ```python def is_valid_time_string(time_str): # Split the input string by the colon parts = time_str.split(':') ...
13,018
You can create a Python function that takes a number as an argument and formats it as a string with thousands separators and 2 decimal places. Here's how you could do it: ```python def formatted_number(number): formatted_number = f"{number:,.2f}" return formatted_number ``` The `f"{number:,.2f}"` syntax in P...
Write a Python function `formatted_number` that takes a number and returns it formatted as a string with commas as thousands separators and 2 decimal places. For example, given 56789.12345, the function should return "56,789.12".
You can create a function `formatted_number` that formats a number with commas as thousands separators and two decimal places using Python's built-in functionality. Here's how you can implement this: ```python def formatted_number(num): # Format the number with commas and two decimal places return f"{num:,.2f}...
13,019
To implement this function, you need to use a random number generator to choose a number between 0 and 1. You can then use this number to choose a string from the list based on its weight. Here is a Python function that implements this functionality: ```python import random def weighted_choice(strings, weights): ...
Write a Python function that takes a list of strings and a corresponding list of weights, and returns a randomly selected string based on the weight. The weight should be a floating-point number and can be negative or positive. The function should weight the strings based on the weights provided, and return a randomly...
To implement a function that selects a randomly weighted string from a list based on corresponding weights (which can be negative or positive), you can use the `random.choices()` function from the `random` module in Python. This function allows you to specify weights for each choice. However, since negative weights do...
13,020
To compute the maximum value of a given string of comma separated values (CSV), we need to parse the input string and extract the comma-separated values, convert them to integers, and then find the maximum value among them. To handle invalid input, we should check if the input is a valid string that contains numbers an...
Write a Python function to compute the maximum value of a given string of comma separated values (CSV). The function should handle situations where the input is invalid, such as an empty string, a string that does not contain any numbers, or a string that contains invalid characters. In such cases, the function should ...
Certainly! Below is a Python function that computes the maximum value from a given string of comma-separated values (CSV) while handling various error conditions. The function ensures that it does not raise exceptions, and it returns `None` when it encounters invalid input. Here's the implementation: ```python def ma...
13,021
You can solve this problem by using a nested loop to search for the key in the array. The outer loop will iterate through the rows of the array, while the inner loop will iterate through the columns of the array. Inside the inner loop, you can check if the current element in the array is equal to the key. If it is, ret...
Design a Python function `find_key_position(array, key)` that takes in a 2D array and a string key and returns the position of the key in the array. The function should start from the top-left corner and traverse the array from row to row, from left to right. If the key is not found, the function should return (-1, -1)...
Certainly! Below is a Python function `find_key_position(array, key)` that searches for a specified string key in a 2D array. The function traverses the array from the top-left corner to the bottom-right corner, row by row, from left to right, and returns the position of the key if found. If the key is not found, it re...
13,022
Here's one way to implement the function in Python: ```python def round_and_format_float(float_number): rounded_float = round(float_number, 2) return f"{rounded_float:.2f}" ``` This function takes a float number as an argument and uses the round() function to round it to two decimal places. It then uses the f...
Write a Python function that rounds a float up to two decimal places and converts it to a string. Your function should take a float number as an argument and return a string representing the number rounded to two decimal places. For example, if the input is 1.5678, the output should be the string "1.57". If the input ...
You can create a Python function that rounds a float to two decimal places and converts it to a string as follows: ```python def round_to_two_decimal_places(num): # Round the number to two decimal places and convert it to a string rounded_num = round(num, 2) return format(rounded_num, '.2f') # Example usa...
13,023
To solve this problem, we can use dynamic programming. We can create an `m x n` array to store the number of unique paths for each position on the grid. We can start from the bottom-right corner, and fill the array from right to left and from bottom to top. At each position, we can calculate the number of unique paths ...
A robot is standing on a grid of size `m x n`. It can only move in two directions: right and down. The robot is initially at the top-left corner of the grid, and is trying to reach the bottom-right corner. Write a Python function `count_unique_paths(m, n)` that returns the number of unique paths the robot can take to r...
To solve the problem of counting the unique paths a robot can take from the top-left corner of an `m x n` grid to the bottom-right corner while only moving right or down, we can use a combinatorial approach. When moving from the top-left corner to the bottom-right corner, the robot needs to make exactly `m - 1` down m...
13,024
Here's how we can implement this: ```python def add_http_headers(response_headers, header_ops): for op, header, value in header_ops: if op == 'add': response_headers[header] = value elif op == 'remove': response_headers.pop(header, None) elif op == 'update': ...
Write a Python function named `add_http_headers` that adds, removes, or updates HTTP headers in a dictionary using a list of tuples representing HTTP header operations. Input: A dictionary representing an HTTP response and a list of tuples, where each tuple has three elements: `operation` (string), `header` (string), ...
Certainly! Below is a Python function named `add_http_headers` that processes a dictionary of HTTP headers based on a list of operations provided. Each operation can be either to add, remove, or update headers. Here's how the function works: - It takes in a dictionary representing the HTTP headers and a list of operat...
13,025
To create a function that returns a string in upper case, lower case, or title case based on a specified mode, you can use the built-in `str.upper()`, `str.lower()`, and `str.title()` methods in Python. These methods convert a string to their respective case formats. Here's how we can implement this: ```python def ge...
Create a Python function that takes a string and returns the same string in upper case, lower case, or title case. The mode should be specified as an optional argument, where 0 is for upper case, 1 is for lower case, and 2 is for title case. If the mode is not specified, it should default to lower case.
Here is a Python function that implements the specified functionality: ```python def transform_string(input_string, mode=1): """ Transform the given string based on the specified mode. Parameters: input_string (str): The string to be transformed. mode (int, optional): The transformation mode (...
13,026
Here's how you can implement the `extract_file_ext` function: ```python import re def extract_file_ext(filepath): if not isinstance(filepath, str) or not filepath: return None, False match = re.search(r'\.(\w+)$', filepath) if match and match.group(1) in ['py', 'pyc']: return match.group(...
Define a Python function `extract_file_ext` that takes a string representing a filepath and returns a tuple containing two strings, where the first string is the file's extension (e.g., ".py"), and the second string is a boolean indicating whether the extension is a valid Python extension. The function should handle in...
You can create the `extract_file_ext` function as specified. This function will use regular expressions to match the file extension and check if it's a valid Python extension. Here's the implementation: ```python import re def extract_file_ext(filepath): # Check for invalid input types if not isinstance(filep...
13,027
Here's a possible solution: ```python def sum_attribute(objects, attribute): total = 0 for obj in objects: total += getattr(obj, attribute) return total ``` In this implementation, the `getattr` function is used to access the specified attribute of each object in the list. The `sum_attribute` fun...
Write a Python function that takes a list of objects as input. For each object, the function should calculate the sum of the values of a specified attribute across all the objects. This sum should be returned as the function's output.
Certainly! Below is a Python function that takes a list of objects and a string representing the name of an attribute. The function calculates the sum of the values of that attribute from all the objects in the list and returns the total sum. ```python def sum_attribute(objects, attribute_name): """ Calculate ...
13,028
To write a Python function to replace all occurrences of "with" with "without" in a string, you can follow these steps: 1. Split the string into a list of words, which can be done using the `split()` method. 2. Iterate over the list of words and check if each word is equal to "with". 3. If the word is equal to "with",...
Write a Python function to replace all occurrences of "with" with "without" in a string, ignoring instances where "with" is part of a different word. For example, "I went with dinner" should become "I went without dinner".
You can achieve this by using the `re` module, which allows you to perform regular expression operations. In this case, you want to replace the word "with" only when it appears as a standalone word. Here’s how you can do that: ```python import re def replace_with_without(text): # Use a regular expression to repla...
13,029
Here is a Python function that implements this approach: ```python from datetime import datetime from uuid import uuid4 def generate_unique_filename(prefix: str, suffix: str) -> str: """ Generates a unique filename for a given prefix and suffix. """ timestamp = datetime.now().strftime("%Y-%m-%dT%H:%M:...
Write a Python function `generate_unique_filename` that generates a unique filename for a given prefix and suffix. The function should take two arguments: `prefix` and `suffix`. It should concatenate the prefix with a timestamp and a random UUID to generate a unique filename with the given suffix. The timestamp should ...
Here’s a Python function that generates a unique filename based on the specified requirements. This function uses the `datetime` module to create the timestamp and the `uuid` module to generate a random UUID. ```python import uuid from datetime import datetime def generate_unique_filename(prefix, suffix): # Get t...
13,030
To escape a string literal, we need to replace special characters with their escaped forms. The special characters are `\`, `"`, `'`, and `\n`, and their respective escaped forms are `\\`, `\"`, `\'`, and `\n`. Here's a possible implementation of the `escape_string_literal` function: ```python def escape_string_liter...
Create a Python function `escape_string_literal(s)` that accepts a string and returns a new string with all characters escaped. You should support four special characters: `\`, `"`, `'`, and `\n`. Your code should pass the following assertions: ```python assert escape_string_literal("It's a \"quote\" inside a string."...
You can create the `escape_string_literal(s)` function to handle the specified escaping of characters in a string. The function will replace each character that needs to be escaped with its escaped version. Here's the implementation: ```python def escape_string_literal(s): # Create a translation table for the char...
13,031
This task can be solved using regular expressions and the `re.sub()` function in Python. We can iterate through the replacements list and use regular expressions to find and replace the corresponding patterns in the string. Here's how you can implement the function: ```python import re def regex_replacement(s, repla...
Write a Python function that performs regular expression replacement in a given string. Given a string `s` and a list of replacements `replacements`, the function should replace all occurrences of the pattern in the string with the corresponding replacement. For example, given `s = 'The quick brown fox jumps over the ...
You can use the `re` module in Python to perform regular expression replacements in a string. Below is a function that implements this functionality: ```python import re def replace_patterns(s, replacements): # Iterate through each pattern-replacement pair for pattern, replacement in replacements: # U...
13,032
To solve this problem, we can iterate over the list of players and check if each player is on the team of their respective teammate. To check if a player is on the team of their teammate, we can use the `player_team` dictionary to obtain their teammate's name and then check if their team is the same. If the player is o...
Given a dictionary `player_team` that contains a mapping of players to teams, and a list of players `players`, generate a new dictionary containing only those players who are on the team of their respective teammate. The new dictionary should have the player's name as the key, and their teammate's name as the value.
To create a new dictionary containing only those players who are on the same team as their teammates, you can follow these steps: 1. Iterate through the list of players. 2. For each player, find their team using the `player_team` dictionary. 3. Check for each teammate if they are also in the `player_team` dictionary a...
13,033
```python def batch_slice(x, n): return np.array_split(x, n, axis=0) ``` The `numpy.array_split` function takes an array `x`, an integer `n`, and an optional axis parameter (defaulting to 0) and returns a list of slices of `x` with size `n`. If the array cannot be evenly divided into `n` slices, the remainder is h...
Write a Python function named `batch_slice` that takes a multidimensional array `x` and an integer `n` as input parameters and returns a list of slices of `x` with size `n`. The slices should be evenly divided along the first axis of `x` and the remainder should be handled appropriately.
Certainly! Below is a Python function named `batch_slice` that takes a multidimensional array `x` and an integer `n`. The function divides the array `x` into slices of size `n` along the first axis, and handles any remainder appropriately. ```python import numpy as np def batch_slice(x, n): """ Splits a multi...
13,034
We can use a regular expression to check if a string contains only digits (0-9). Regular expressions are powerful tools for pattern matching and provide a flexible and concise way to define complex string patterns. In this case, we can use a regular expression pattern that matches a string containing only digits. Here...
Write a Python function to check if a string contains only digits (0-9). The function should return True or False. Your code should pass the following assertions: ```python assert is_digit_string("123abc") is False assert is_digit_string("1a2b3c") is False assert is_digit_string("000000000") is True assert is_digit_st...
You can create a Python function called `is_digit_string` that checks if a string contains only digits. Here's one way to implement this: ```python def is_digit_string(s): return s.isdigit() # Test assertions assert is_digit_string("123abc") is False assert is_digit_string("1a2b3c") is False assert is_digit_strin...
13,035
Here's how you can implement the `construct_hash_table` function in Python: ```python import os import hashlib def construct_hash_table(dir_path): hash_table = {} for root, dirs, files in os.walk(dir_path): for file_name in files: file_path = os.path.join(root, file_name) with...
Construct a Python function `construct_hash_table(dir_path)` that takes a directory path and returns a hash table consisting of the file paths and their hash values. The hash table should be a dictionary where the keys are the file paths and the values are the corresponding hash values. To calculate the hash value, uti...
To create the `construct_hash_table` function that calculates the MD5 hash of files in a given directory path and returns a hash table (dictionary) consisting of the file paths and their corresponding hash values, you can use Python's `os` module to navigate through the directory structure and the `hashlib` module to c...
13,036
Here's how you can implement this: ```python def print_score(name, team_score, final_score): width = len(str(team_score)) if final_score < 0: output = "Final Score".rjust(width + 11) else: output = f"{name.ljust(10)} | Team Score: {team_score}".rjust(width + 11) + f" | Final Score: {final_...
Create a Python function `print_score` that takes three arguments: `name`, a string; `team_score`, an integer; and `final_score`, a float. The function should print a string of the format "Team Score | Final Score", with the `${team_score}` and `${final_score}` being right-aligned. If the `final_score` is negative, the...
You can create the `print_score` function as follows: ```python def print_score(name: str, team_score: int, final_score: float): if final_score < 0: print("Final Score") else: # Format the scores to be right-aligned within specific widths formatted_output = f"{team_score:>10} | {final_s...
13,037
To create a directory or file with a given name, we need to make sure that the name is valid and does not already exist. We also need to handle any potential exceptions that may occur during file or directory creation. Here's a potential implementation of the requested function: ```python import os def create_dir_or...
Create a Python function that takes a string as input and creates a directory with that name in the current working directory, if that directory doesn't already exist. Additionally, if the input string contains file type extensions (like `.txt` or `.py`), the function should also create a file with that name in the tar...
Here's a Python function that accomplishes the task you've described. This function checks if the directory exists, creates it if it doesn't, and also creates a file if the input string has a valid file extension. It handles exceptions that might occur during these operations. We will make use of the `os` and `pathlib...
13,038
You can use the `re` module in Python to replace ASCII control characters with spaces. Here's how you could do it: ```python import re def replace_ascii_control_chars(string): return re.sub(r'[\x00-\x1F]', ' ', string) ```
Create a Python function to replace all ASCII control characters in a string with spaces. ASCII control characters are defined as those with a value less than 32. Your code should pass the following test case: ```python string = 'Hello\x01world\x1F!' new_string = replace_ascii_control_chars(string) assert new_string =...
You can create a Python function to replace all ASCII control characters in a string with spaces by using the `str.translate()` method along with `str.maketrans()`. Below is a simple implementation of such a function: ```python def replace_ascii_control_chars(s): # Create a translation table that maps all ASCII co...
13,039
```python def unique_lines(str1, str2): lines1 = set(str1.splitlines(keepends=True)) lines2 = set(str2.splitlines(keepends=True)) unique_lines = lines1.difference(lines2) return list(unique_lines) ``` This implementation uses `splitlines()` with `keepends=True` to split the multi-line strings into line...
Develop a Python function that takes in two multi-line strings and returns a list of the lines that are unique to each string. The function should use set operations to identify the unique lines and return the results as a list of strings.
You can achieve this by defining a function that splits each multi-line string into individual lines, then uses set operations to find lines that are unique to each string. Here's a function that does exactly that: ```python def unique_lines(str1, str2): # Split the input strings into sets of lines lines1 = se...
13,040
To format a Python package name as a snake-case string, we can use the `split()` method to separate the package name by the '.' separator. Then, we can use the `join()` method to join the resulting list of strings with an underscore '_' as the separator. The `join()` method will produce the desired snake-case format. ...
Write a Python function to format a Python package name as a snake-case string. The package name is given as a string with dots ('.') as separators. For example, given `com.example.pandas`, the function should return `com_example_pandas`.
You can achieve this by creating a simple Python function that replaces the dots in the package name with underscores. Here's how you can implement the function: ```python def format_package_name(package_name: str) -> str: """Format a package name with dots to a snake-case string.""" return package_name.replac...
13,041
Here is a Python function to implement this approach: ```python def transform_logs(logs): transformed_logs = {key: [] for key in logs[0].keys()} for log in logs: for key, value in log.items(): transformed_logs[key].append(value) return transformed_logs ```
Given a list of dictionaries `logs`, write a Python function `transform_logs` to convert it into a dictionary where the keys are the keys in the dictionaries and the values are lists with the values in the corresponding dictionaries. For example, given ```python logs = [ {"user_id": 1, "action": "login", "timestam...
To transform the given list of dictionaries into the desired format, you can iterate through the list of dictionaries and aggregate values based on their keys. Here’s how you can implement the `transform_logs` function: ```python def transform_logs(logs): # Initialize an empty dictionary to hold the transformed ou...
13,042
Here's how you can implement this in Python: ```python def apply_func_to_each(func, iterable): transformed_list = [] for element in iterable: transformed_list.append(func(element)) return transformed_list ```
Write a Python function `apply_func_to_each(func, iterable)` to iterate over a given iterable and apply a given function `func` to each element of the iterable. Input: - `func`: A function that takes an element of the iterable as input and returns a transformed value. - `iterable`: An iterable object, such as a list,...
You can create the function `apply_func_to_each` as follows: ```python def apply_func_to_each(func, iterable): return [func(item) for item in iterable] # Example usage def square(x): return x * x result = apply_func_to_each(square, [1, 2, 3, 4]) print(result) # This should print: [1, 4, 9, 16] ``` ### Expl...
13,043
To calculate the power of an integer `x` to an exponent `n` in Python, you can follow these steps: 1. Avoid infinite loops: You can use a precondition check to ensure that `x` is a non-zero integer. If you attempt to calculate the power of 0, it will always result in 0, and you can return 0 without any further calcula...
Write a Python function to calculate the power of a given integer `x` to an exponent `n`, where `n` can be negative. The function should handle negative exponents without requiring a separate case for it. Include a precondition check to ensure that `x` is a non-zero integer. Your code should pass the following assert...
You can create a function to calculate the power of an integer `x` raised to an exponent `n` using Python's built-in capabilities. The function should check for the precondition that `x` is a non-zero integer. Here's a complete implementation: ```python def power_of(x: int, n: int) -> float: # Precondition check ...
13,044
```python import re def generate_regex_function(regex): pattern = re.compile(regex) def is_match(string): match = pattern.match(string) return bool(match) return is_match ``` The `generate_regex_function` function takes a regular expression as an argument and returns a new function that...
Python provides a module `re` for working with regular expressions. Write a function `generate_regex_function` that accepts a regular expression and returns a function that checks if an input string matches the given expression. The function should utilize the `re` module for regular expression compilation and matching...
You can create a function `generate_regex_function` that takes a regular expression as an argument and returns a function that can be used to check whether a given input string matches the provided regex pattern. Below is an implementation of this concept using Python's `re` module: ```python import re def generate_r...
13,045
To achieve the required functionality, you can utilize the `re` module's powerful regular expression capabilities to identify and extract the necessary information from each line of the input file. The file format is specified in the README file as a list of key-value pairs separated by the `:` character. The function ...
Using Python's `re` module, write a function `translate_from_file(filename)` that takes a `filename` as an argument and reads the file line by line. If the file is in a certain format (specified in the README file), translate the content to another format (also specified in the README file). Finally, print the translat...
To implement the `translate_from_file(filename)` function using Python's `re` module, we'll first need to clarify the format of the input file and the desired output format. However, since we don't have the specifics from the README file, I'll provide you with a general structure of how you can read a file, apply regex...
13,046
You can use the `sorted()` function with a custom key function to sort the dictionary by the length of the inner lists. If two lists have the same length, you can sort them in ascending order using `reversed()`. Here's how you could implement this function: ```python def sort_dict_by_list_length(d): sorted_dict =...
Write a Python function to sort a dictionary of lists by the length of each inner list, in descending order. If two lists have the same length, they should be sorted in ascending order of their elements. For example, given `d = {1: [0, 1, 2], 2: [0, 1], 3: [3]}`, the function should return `{1: [0, 1, 2], 2: [0, 1], 3:...
You can achieve this by defining a function that sorts the dictionary based on the criteria you specified. Below is a Python function that does just that: ```python def sort_dict_by_list_length(d): # Sort the dictionary items based on two criteria: # 1. Length of the lists (in descending order) # 2. The li...
13,047
You can accomplish this task by performing the following steps: 1. Check if the input object is valid JSON. 2. Iterate over the "children" array and extract the "id" and "name" values. 3. Build the output string using the provided format. 4. Return the concatenated string. Here's an example implementation of a Python...
I have a JSON object that looks like the following: ```python { "id": "123456789", "name": "", "children": [ { "id": "987654321", "name": "" } ] } ``` I want to extract the `id` and `name` values from the `children` array and concatenate them into a single string with the following format:...
You can achieve this by defining a function that takes the JSON object as input, extracts the `id` and `name` from the `children` array, and formats them accordingly. Here is a sample implementation: ```python import json def extract_child_info(json_object): # Initialize an empty result string result = "" ...
13,048
Here is the implementation of the Python function that takes a list of dictionaries and a search keyword, and returns a list of filtered dictionaries that contain the keyword in any of their keys or values: ```python from itertools import filterfalse, chain def filter_dicts(dictionary_list, search_keyword): matc...
Write a Python function that takes a list of dictionaries and a search keyword, and returns a list of dictionaries that contain the keyword in any of their keys or values. Utilize functional programming with the itertools module to partition the list and filter out the matching dictionaries.
Certainly! You can achieve this using the `filter` function along with a lambda function to check if the keyword exists in any of the keys or values of the dictionaries. Additionally, you can use the `itertools` module to partition the list if needed, but for the filtering process itself, we'll primarily focus on the `...
13,049
To create a formatted string representing the nested structure of a list of schemas, we can leverage the built-in `json` module to convert the schemas to a nested dictionary representation. We can then use the `json.dumps` function to format the dictionary as a JSON string, indenting each level with two spaces (`indent...
You are given a list of schemas that represent various fields. Each schema consists of a field name, a nested schema list, and a field type. Create a Python function that takes a list of schemas and returns a formatted string representing the nested structure of the schemas. You must handle errors if the schemas are ma...
To create a function that formats nested schemas as specified, we will define `format_schemas`. This function will take a list of schema dictionaries, verify that they are correctly formed, and then format them into a specific string representation. Here's the implementation of the `format_schemas` function: ```pytho...
13,050
You can use the `numpy` package to perform mathematical calculations on arrays efficiently. The formula can be easily implemented using `numpy.exp` function, which calculates the exponential value of each element of the input array. Here's how you can implement the function using `numpy`: ```python import numpy as np...
Create a Python function that implements the following mathematical formula for a given x: <img src="https://render.githubusercontent.com/render/math?math=\frac{1}{1 + e^{-x}} = \frac{e^x}{e^x + 1} = 1 - \frac{1}{1 + e^{x}}"> The function should support both scalar inputs and array inputs. The function should also su...
You can create a Python function that implements the given mathematical formula for the logistic function \( \sigma(x) = \frac{1}{1 + e^{-x}} \). This function will use NumPy to handle both scalar and array inputs efficiently. Below is the implementation of the function, along with an explanation of how to use it. ```...
13,051
Here's how you can create the HTML link using Python: ```python def create_html_link(title: str, url: str) -> str: return f'<a href="{url}">{title}</a>' ```
Create a Python function named `create_html_link` that takes a title and URL as arguments and returns a string of HTML formatted as a hyperlink. The function should create an `a` tag with the `href` attribute set to the provided URL, and the link text set to the title. The returned string should be HTML-encoded and not...
You can create the `create_html_link` function as described. Here's the Python function that formats the title and URL into an HTML anchor (`<a>`) tag: ```python def create_html_link(title: str, url: str) -> str: # HTML encode the title and url (for demo purpose, we replace special characters) title_encoded = ...
13,052
Here's an example implementation of the `count_matching_type` function using a list comprehension: ```python def count_matching_type(obj_list, obj_type): return len([obj for obj in obj_list if isinstance(obj, obj_type)]) ``` This function takes a list of objects (`obj_list`) and a type (`obj_type`) as input. It u...
Write a Python function `count_matching_type` that takes a list of objects and a type and returns the number of items in the list that are of that type. Use a list comprehension to filter the list and count the number of items that satisfy the type condition.
You can create the function `count_matching_type` using a list comprehension to filter and count the items in the list that match the specified type. Here’s how you can implement it: ```python def count_matching_type(objects, type_to_count): return sum(1 for obj in objects if isinstance(obj, type_to_count)) # Exa...
13,053
Here is the implementation of the `format_variables` function: ```python def format_variables(strings, numbers): formatted_strings = [] for string, number in zip(strings, numbers): formatted_strings.append("{} is {} years old.".format(string, number)) return "\n".join(formatted_strings) ``` This f...
Define a Python function called `format_variables` that takes a tuple of strings and a tuple of numbers, and returns a string with the strings formatted to contain the corresponding numbers. The function should use string formatting with `.format()` method. Return the formatted string. Here is an example: ```python n...
To achieve the desired functionality, we can define the `format_variables` function that takes two tuples: one for the names (strings) and another for the ages (numbers). We'll use the `.format()` method to format each name with its corresponding age in a single string. Here's how you can implement the `format_variabl...
13,054
To calculate the centers of a list of rectangles, we can use a Python function that iterates through the list of rectangles and determines the center coordinates for each rectangle. The function should take the input list of rectangles as a parameter and return a list of center coordinates. The center coordinates of a...
Implement a Python function that calculates the centers of a list of rectangles. Given a list of rectangles, each rectangle contains its top-left and bottom-right coordinate points as (x1, y1) and (x2, y2). The function should return a list of center coordinates of the rectangles.
You can calculate the center of each rectangle by averaging the x and y coordinates of its top-left and bottom-right corners. The center coordinates can be determined using the following formulas: - Center X coordinate: \( \text{center\_x} = \frac{x1 + x2}{2} \) - Center Y coordinate: \( \text{center\_y} = \frac{y1 + ...
13,055
Here is the implementation of the decorator using a global dictionary to cache results: ```python def cached(func): cache = {} def wrapped(*args): if args not in cache: cache[args] = func(*args) return cache[args] return wrapped ``` The decorator is applied to a function usin...
Implement a Python function decorator that caches the return value for each distinct argument combination. The decorator should work with any function that accepts any number of arguments, including those with default values.
To implement a Python function decorator that caches the return value based on distinct argument combinations, we can utilize a dictionary to store the results of calls to the decorated function. We'll use the function's arguments in a way that allows us to construct a unique key for each call. Here's how to create th...
13,056
Here is a Python function that implements the recursive approach: ```python from itertools import groupby from typing import List, Tuple def group_pairs(pairs: List[Tuple[int, str]], key=lambda x: x[0], nested=False) -> List[List[str]]: """ Groups a list of pairs (index, value) into nested lists based on the ...
Implement a Python function to take a list of pairs (index, value) and group them into nested lists in order of the index. If the index is equal, place them in the same list. For example, given [(0, 'a'), (0, 'b'), (1, 'c'), (1, 'd')], the function should return [['a', 'b'], ['c', 'd']]. You may use the `groupby` funct...
To implement the function that groups a list of pairs (index, value) into nested lists based on the provided specifications, we can utilize the `groupby` function from the `itertools` module. The recursive aspect of the function can be designed to handle sub-elements effectively. Here's an implementation of the functi...
13,057
Here's how you can implement this: ```python def find_longest_prefix(string_list): if not isinstance(string_list, list): return "Input must be a list of strings" if len(string_list) == 0: return "List cannot be empty" if "" in string_list: return "List cannot contain empty strings"...
Write a Python function `find_longest_prefix(string_list)` that takes a list of strings as input and returns the longest common prefix shared by all strings. Importantly, the function should handle errors gracefully and return the appropriate error message if the input is not a list of strings or if the list is empty. ...
Here's a Python function `find_longest_prefix` that meets the specified requirements. It checks the input for various conditions and finds the longest common prefix among the strings in the list. ```python def find_longest_prefix(string_list): # Check if input is a list if not isinstance(string_list, list): ...
13,058
Here is a Python function that implements this calculation: ```python import math def circle_area(radius): if radius < 0: raise ValueError("Radius must be a positive number.") return math.pi * radius**2 ``` In this function: - `import math`: This imports the `math` module which provides the `pi` cons...
Write a Python function that calculates the area of a circle given its radius. The function should take one argument, `radius`, which is expected to be a positive number. If the argument is not a positive number, the function should raise a `ValueError` with an appropriate error message. Your code should pass the foll...
Certainly! Below is a Python function that calculates the area of a circle given its radius, raises a `ValueError` for invalid inputs, and passes the specified assertion. ```python import math def circle_area(radius): # Check if the radius is a positive number if radius < 0: raise ValueError("The radi...
13,059
Here's a Python function that implements this logic: ```python def mean_2d(array): flattened = [item for sublist in array for item in sublist] total = sum(flattened) return total / len(flattened) ``` In this implementation, we use list comprehension to flatten the 2-dimensional array into a 1-dimensional ...
Write a Python function that calculates the mean value of a 2-dimensional array. The function should accept a two-dimensional array as an input, reduce it into a 1-dimensional array of column means, and return the mean value of this array. For example, given `array = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]`, the function sh...
Certainly! You can calculate the mean value of a two-dimensional array in Python using NumPy, which provides efficient methods for numerical operations. Here's a function that does exactly what you've described: ```python import numpy as np def mean_of_column_means(array): # Convert the input list to a NumPy arra...
13,060
A simple solution would be to surround the given string with the HTML `<span>` tags. However, to ensure the generated HTML is valid, we need to perform some additional checks and sanitization. Specifically, we need to: 1. Check if the input string has any special characters or HTML tags. 2. Encode the HTML special cha...
Design a Python function that takes a string and returns an HTML string with the same contents, but surrounded by `<span>` tags with a specified `class` attribute.
You can create a Python function that takes a string and a class name as parameters, then returns an HTML string containing the input string wrapped in `<span>` tags with the specified class. Here’s a simple implementation of such a function: ```python def wrap_in_span(input_string, class_name): """ Wraps the ...
13,061
To list the files in the same directory as the given file, we need to extract the directory path from the given file path and use the `os.listdir` function to return a list of files in that directory. Here's how we can implement this in Python: ```python import os def get_files_in_same_directory(file_path): dire...
Write a Python function that, given a file path, returns a list of file paths pointing to all the files in the same directory as the given file. Include the given file path in the returned list.
You can use the `os` module in Python to accomplish this task. The `os` module contains functions for interacting with the file system, including retrieving the directory of a given file and listing the files in that directory. Here is a function that takes a file path as an argument and returns a list of file paths ...
13,062
Here's the implementation using the `join` method on strings: ```python def string(characters): return ''.join(characters) ``` The `join` method takes a sequence of strings as an argument and concatenates them using a specified delimiter. In this case, the sequence is the list of characters, and the delimiter is ...
Write a Python function `string` that takes a list of characters (or strings as you prefer, but no other types) as an argument and returns the string representation of the given list. ```python assert string(['h', 'e', 'l', 'l', 'o']) == 'hello' assert string(['w', 'o', 'r', 'l', 'd']) == 'world' ```
You can create a function named `string` that takes a list of characters (or strings) and joins them together to form a single string. In Python, you can achieve this by using the `join` method of a string. Here's how you can implement it: ```python def string(char_list): # Join the list of characters into a singl...
13,063
To solve this problem, we'll use regular expression matching in Python to search for the first occurrence of a 10-digit phone number in the input text. We'll use a regular expression pattern that matches a sequence of 10 digits surrounded by word boundaries to ensure that the phone number is not part of a larger sequen...
Create a Python function that accepts a string `text` as input and returns the substring that matches the first occurrence of a 10-digit phone number in the input text. The function should use regular expression matching to find the phone number and return it as a string. If no phone number is found in the input text, ...
You can accomplish this task using Python's `re` module, which provides support for regular expressions. Below is the function `find_phone_number` that searches for the first occurrence of a 10-digit phone number in the input text and returns it: ```python import re def find_phone_number(text): # Define the regul...
13,064
Here's how you could do it: ```python def flatten_hierarchical_dict(hierarchical_dict): flat_dict = {} def flatten_children(parent_name, children_dict): for child_name, grandchildren_dict in children_dict.items(): flat_dict[child_name] = parent_name if grandchildren_dict: ...
Write a Python function to recursively flatten a nested hierarchical dictionary according to its parent-child relationships. The function should take a nested dictionary as input where the keys are names of elements, and the values are their parent elements. The function should recursively flatten the dictionary and re...
To create a function that recursively flattens a nested hierarchical dictionary based on parent-child relationships, we can iterate through the dictionary and build a flat structure that captures the relationships. We'll maintain the order and ensure that each key points to its direct parent. Here's how you can implem...
13,065
Here's how you can implement the function: ```python import numpy as np def scalar_mult(a, vec): if isinstance(vec, np.ndarray): return a * vec else: return [a * x for x in vec] ```
Write a Python function `scalar_mult(a, vec)` that multiplies an input vector by a scalar value. Input: `a`: a scalar value, `vec`: a list of numbers. Output: a list of numbers representing the product of `a * vec`. This function should also accept 1-dimensional NumPy arrays. Your code should pass the following ass...
You can create the `scalar_mult` function that handles both Python lists and NumPy arrays. Here’s how you can implement it: ```python import numpy as np def scalar_mult(a, vec): # Check if vec is a NumPy array if isinstance(vec, np.ndarray): return a * vec # NumPy automatically handles element-wise m...
13,066
Here's how you could implement the `timestamp_to_timestamp` function in Python: ```python from datetime import datetime def timestamp_to_timestamp(timestamp): input_datetime = datetime.strptime(timestamp, '%d/%m/%Y %H:%M:%S') output_timestamp = input_datetime.strftime('%Y-%m-%d %H:%M:%S') return output_ti...
Write a Python function `timestamp_to_timestamp` that takes a `timestamp` as input and returns a new timestamp with the same time but in a different format. The input `timestamp` is represented as a string in the `'dd/mm/yyyy hh:mm:ss'` format, while the output should be in `'yyyy-mm-dd hh:mm:ss'` format. Additionally,...
To achieve the conversion of a timestamp from the format `'dd/mm/yyyy hh:mm:ss'` to `'yyyy-mm-dd hh:mm:ss'`, we will leverage Python's `datetime` module. This module provides functionality to manipulate dates and times easily. Below is the implementation of the `timestamp_to_timestamp` function: ```python from datetim...
13,067
To transform the list of labels into a dictionary of dictionaries, you can use a dictionary comprehension with the `defaultdict` module from the `collections` library. The `defaultdict` provides a convenient way to initialize a dictionary with default values, which can be used to store the semantic segmentation labels ...
Write a function `transform_labels` to transform a list of semantic segmentation labels from their original representation as a list of tuples to a dictionary of dictionaries. Each tuple contains two elements, the first being the name of the label and the second being a list of pairs of indices. For example, given the...
Sure! Below is the implementation of the `transform_labels` function that takes a list of tuples and transforms it into the desired dictionary format. ```python def transform_labels(labels): transformed = {} for label_name, indices in labels: # Initialize the inner dictionary for the label name ...
13,068
Here's how you can implement this function: ```python def flatten_sentences(sentences): flat_words = [] for sentence in sentences: for word in sentence: flat_words.append(word) return flat_words ```
Write a Python function `flatten_sentences` that takes a list of sentences and returns a flattened list of words. Each sentence is a list of strings representing words, and the return value should be a list of words. Your code should pass the following test case: ```python sentences = [["Hello", "world"], ["Good", "mo...
You can achieve this by using a list comprehension in Python that iterates over each sentence and each word within those sentences. Here's a simple implementation of the `flatten_sentences` function: ```python def flatten_sentences(sentences): # Using a list comprehension to flatten the list of sentences retur...
13,069
You can create a Python function that traverses the list of tasks, looks up the GPU count from the dictionary, and updates a running total of GPUs required. If a task is not found in the dictionary, it is assumed to require 1 GPU. Here's how you could do it: ```python def compute_gpu_count(tasks, gpu_counts): gpu...
Write a Python function to compute the total number of GPUs required by a job, given a list of tasks and a dictionary of GPU counts per task. The function should traverse the list of tasks and access the GPU counts from the dictionary. If a task is not found in the dictionary, it should be considered to require 1 GPU. ...
You can implement the function `compute_gpu_count` as described in your request. The function will take in a list of tasks and a dictionary that contains the GPU counts for each task. It will iterate through the list of tasks, retrieve the GPU count from the dictionary (defaulting to 1 if the task is not found), and ac...
13,070
To convert a JSON object to a Python data structure, we can use the `json` module in Python's standard library. This module provides the `loads` function that converts a JSON string into a Python object. However, the `loads` function cannot directly handle nested dictionaries and lists. Here is a Python function that ...
Write a Python function `convert_json_to_python` that takes a JSON object (either a dictionary or a list) and returns the equivalent Python data structure. The function should support nested dictionaries and lists in the JSON object.
To convert a JSON object into a Python data structure, you can utilize Python's built-in `json` library, which can easily handle the conversion of JSON strings to Python dictionaries and lists. Here's how you can write a function called `convert_json_to_python` that takes a JSON object and returns the corresponding Pyt...
13,071
```python def parse_as_tuple(input_string): elements = input_string.split(',') if len(elements) != 2: raise AssertionError(f"Invalid input: {input_string}") try: num1 = float(elements[0]) num2 = float(elements[1]) except ValueError: raise AssertionError(f"Invalid input: ...
Write a Python function `parse_as_tuple` that parses a string representing a pair of numbers separated by a comma (e.g., `"1,2"`) and returns a tuple of two numbers. The function should handle invalid inputs such as `"1,2,3"`, `""`, and blank spaces. If an invalid input is detected, the function should raise an `Assert...
Here is a Python function named `parse_as_tuple` that parses a string representing a pair of numbers separated by a comma. It includes error handling to raise an `AssertionError` with an informative message if the input is invalid. ```python def parse_as_tuple(input_string): # Strip any leading or trailing whitesp...
13,072
```python def dictionary_subtraction(dict_a, dict_b): if not set(dict_b.keys()).issubset(dict_a.keys()): raise KeyError("All keys in dict_b must be in dict_a") result = {key: value for key, value in dict_a.items() if key not in dict_b} return result ``` This function first checks if all keys in `d...
Given two dictionaries `dict_a` and `dict_b`, write a Python function `dictionary_subtraction(dict_a, dict_b)` that returns a new dictionary with all key-value pairs that are in `dict_a` and not in `dict_b`. Raise a `KeyError` if any of the keys in `dict_b` are not in `dict_a`. Use a dictionary comprehension to build t...
Here's a Python function `dictionary_subtraction(dict_a, dict_b)` that performs the described operation. It raises a `KeyError` if any keys in `dict_b` are not present in `dict_a`, and uses dictionary comprehension to construct the resulting dictionary. ```python def dictionary_subtraction(dict_a, dict_b): # Check...
13,073
```python def are_overlapping(str1, str2): return set(str1) & set(str2) != set() ``` This implementation uses the intersection operation (`&`) on the sets of characters in each string. If the resulting set is non-empty, then the two strings are overlapping.
Write a Python function to determine whether the given `str1` and `str2` are overlapping. The two strings are considered overlapping if they share a common non-empty substring. Here is an example of overlapping strings: ```python str1 = "abc" str2 = "cdef" # Both strings contain the overlapping substring "c" ```
You can determine whether two strings overlap by checking if they share any common substring of length at least 1. A simple way to approach this problem is to create a set of substrings from one string and then check if any substring of the other string exists in that set. However, since we only need to check for non-e...
13,074
Here is the implementation: ```python def generate_hierarchy(hierarchy): hierarchy_list = [] current_identifier = "" for identifier in hierarchy.split(","): current_identifier += identifier hierarchy_list.append(current_identifier) current_identifier += "." return hierarchy_li...
Write a Python function that takes a string `hierarchy` (a comma-separated list of string identifiers) and returns a list of identifiers representing the hierarchy. For example, given `hierarchy="A,B,C,D"`, the function should return `['A', 'A.B', 'A.B.C', 'A.B.C.D']`.
You can achieve this by creating a function that splits the input string into individual identifiers and constructs the hierarchy as specified. Here's a Python function to do that: ```python def generate_hierarchy(hierarchy): identifiers = hierarchy.split(',') result = [] # Build the hierarchy cur...
13,075
Here is the implementation of `find_all_attr_on_class`: ```python def find_all_attr_on_class(cls): attrs = set() for base in cls.__mro__: attrs.update(base.__dict__) return attrs ```
Write a Python function `find_all_attr_on_class` to find all attributes on a given class object, including attributes inherited from parent classes. Use `__dict__` to access the class attributes.
You can create a Python function called `find_all_attr_on_class` to retrieve all attributes of a given class object, including those inherited from parent classes. The function will utilize the `__dict__` attribute to access the attributes of the class and its base classes recursively. Here’s how you can implement thi...
13,076
To create such a function, we can use a list comprehension to filter all the functions in a predefined list that match all of the given tags. The list comprehension will iterate through the list of functions, and for each function, it will use the `all` function to check if all of the tags are contained in the function...
I want to write a function that can take a list of tags and return a list of functions that match those tags. The function should have the signature `process_tags(tags)`, where `tags` is a list of strings. Each string in the list represents a tag. The returned list of functions should be those functions that match all ...
To create a function `process_tags(tags)` that returns a list of functions matching all specified tags, you can follow these steps: 1. Define a way to tag functions. One common approach is to use a decorator that allows you to add tags to functions. 2. Implement the `process_tags` function to filter functions based on...
13,077
Here's how you can round up or down a number to the nearest multiple of 8: ```python import math def round_to_8(number, up=True): if up: return round(number / 8) * 8 else: return math.floor(number / 8) * 8 ``` The function uses the `round` function from the `math` module. If the `up` parameter...
I want to develop a Python function that rounds up or down a given number to the nearest multiple of 8. The function will be written as `round_to_8(number, up=True)`. For example, `round_to_8(80)` should return `80`, and `round_to_8(95)` should return `96`.
You can achieve the desired functionality by implementing the `round_to_8` function in Python. The function will use the `up` parameter to determine whether to round the number up or down to the nearest multiple of 8. Here's how you can write it: ```python def round_to_8(number, up=True): remainder = number % 8 ...
13,078
The first step is to check if the given exception is an instance of `FileNotFoundError` or `IsADirectoryError`. We can use the `isinstance` function to check if the exception is a subclass of these exception types. If it is, we can return `True`, otherwise we return `False`. ```python def is_file_open_error(exception)...
Write a function `is_file_open_error` that takes an instance of the `Exception` class and checks whether the exception is a `FileNotFoundError` or `IsADirectoryError`. If it is, return `True`, otherwise return `False`. Additionally, return the exception's message as a second value.
Certainly! Below is a Python function `is_file_open_error` that checks if an exception is either a `FileNotFoundError` or `IsADirectoryError`. The function returns a tuple containing a boolean indicating whether the exception is one of the specified types and the exception's message. ```python def is_file_open_error(e...
13,079
To write a Python function that satisfies the conditions described in the instruction, you should consider the following steps: 1. Split the logic into two cases: `x >= 0` and `x < 0`. 2. In the case where `x >= 0`, you can directly return `x % m`. 3. In the case where `x < 0`, you can return `m - (-x) % m`, which is ...
Write a Python function `mod_range` that takes two arguments: a number `x` and a modulus `m`, and returns the value of `x` within the range `[0, m)`. The function should satisfy the following conditions: - If `x` is positive or zero, the function should return `x % m`, i.e., the remainder of `x` divided by `m`. - If `...
You can implement the `mod_range` function in Python as described in your request. Here's how you can do it: ```python def mod_range(x, m): # Ensure modulus is positive if m <= 0: raise ValueError("Modulus must be a positive integer") if x >= 0: return x % m else: # Calculate t...
13,080
Here's a solution in Python: ```python def rstrip(string): return string.rstrip() ```
In Python, there is a built-in `str.lstrip()` method for removing leading whitespace from a string. However, there is no direct equivalent method for removing trailing whitespace. Write a Python function `rstrip(string)` that takes a string as an argument and returns a copy of the string, with any trailing whitespace r...
You can define the `rstrip` function by using `str.rstrip()` method, which indeed removes trailing whitespace from a string. However, if you're looking to implement `rstrip` from scratch without using that built-in method, you can do so by iterating through the string from the end until you hit a non-whitespace charact...
13,081
To solve this problem, we can utilize the Python built-in functions `str.lower()` and `str.strip()` to convert the input string to lowercase and remove any leading and trailing whitespace. We can then compare the resulting string with the expected "true" values "true", "yes", "y", and "1". Here's an example implementa...
You're writing a Python function that accepts a string value as input and returns a boolean value based on whether the value represents "true", "yes", "y", or "1". If the value does not represent any of these values, the function should return `False`. For example, if the input value is "y", the function should return ...
You can create a function in Python that checks if the input string matches any of the specified truthy values. Here's a simple implementation: ```python def is_truthy(value: str) -> bool: # Define a set of truthy values truthy_values = {"true", "yes", "y", "1"} # Return True if the value is in the tr...
13,082
Here is how you could implement such a function: ```python def pickle_class_field_and_instance_state(obj): class_field = obj.__class__.__dict__ instance_state = obj.__getstate__() return (obj.__class__, (class_field, instance_state)) ``` The `__reduce__` method is called by the `pickle` module during seri...
Write a Python function to pickle a class field and instance state using Python's `__reduce__` method. The function should take a class instance and return a tuple representing the class field and instance state.
To pickle a class field and instance state in Python using the `__reduce__` method, you can define a class that implements this method. The `__reduce__` method should return a tuple that contains the class itself, a tuple of instance attributes (if any), and any class-level fields that you want to include in the pickli...
13,083
To write a Python function to parse and combine a list of strings representing numbers into a single number, consider the following steps: 1. Define a function `parse_number(s)` that returns a float or integer for a single number string. This function should handle various number formats, including integers, floating-...
Write a Python function to parse and combine a list of strings representing numbers into a single number. The input strings may contain extra characters such as whitespace, commas, dashes, and periods. Your function should handle various number formats, including integers, floating-point numbers, and scientific notatio...
To achieve this, we can create a Python function that takes a list of strings, cleans them up by removing unwanted characters, and then combines them into a single string representing the number. Afterward, we will try to convert it into either an integer or a float, depending on the presence of a decimal point. Here...
13,084
To determine whether there is a winning configuration of Xs or Os, we need to check if there are three consecutive positions in any of the rows, columns, or diagonals. Here's a function `x_wins(x_positions, o_positions)` that returns `True` if there is a winning configuration of Xs or Os, `False` otherwise: ```python...
I am writing a function in Python to predict the outcome of a tic-tac-toe game based on the position of the Xs and Os on the board. The function should take in two arguments: `x_positions` and `o_positions`, where each is a list of tuples of size 2 indicating the row and column of an X or O on the board. The function s...
To solve the problem of determining whether X or O has a winning configuration in a tic-tac-toe game, we can define a function `x_wins(x_positions, o_positions)`. This function will check if either player has three of their symbols in a row, either horizontally, vertically, or diagonally. Here is the complete code for...
13,085
You can achieve the desired functionality by checking the string's content using conditional statements and then using the `re` module to match regular expressions. Here's how you can do it in Python: ```python import re def match_string(string): if string == "hello": return string elif string == "wo...
Write a Python function that takes a string as input and returns the first word that matches one of the following: `"hello", "world", or "goodbye"`. If no matches are found, return `None`. Use conditional statements for checking the string's content and the `re` module for matching regular expressions. Your code shou...
You can create a Python function using the `re` module to match the specified words in a string. Below is a function named `match_string` that accomplishes this task, along with the assertions provided. ```python import re def match_string(input_string: str) -> str: # Define the regex pattern to match "hello", "w...
13,086
To clean and normalize a string, we need to perform several operations, such as stripping leading and trailing whitespace, converting to lowercase, removing non-alphanumeric characters, and replacing sequences of multiple spaces with a single space. Here's a simple implementation of the function: ```python import re ...
Write a Python function that takes a string as input and returns the cleaned and normalized version of the string. The function should perform the following tasks: 1. Strip all leading and trailing whitespace. 2. Convert all words to lowercase. 3. Remove all non-alphanumeric characters, except for spaces, underscores,...
You can accomplish the tasks you've outlined by implementing a Python function as follows. This function will use regular expressions to remove unwanted characters and normalize spaces: ```python import re def clean_and_normalize_string(input_string): # Step 1: Strip leading and trailing whitespace cleaned_st...
13,087
Here's how we can implement this: ```python def insert_if_exists(d, old_key, new_key, new_value): if old_key in d: if new_key in d: d[new_key] = new_value else: d[new_key] = new_value return d else: return d def insert_for_each_if_exists(lst, old_key, ne...
Write a function that takes a list of dictionaries and returns a list of dictionaries containing a key named `new_key` with the value of `new_value` if the dictionary contains the `old_key`. If the `old_key` does not exist, then the function should return the original dictionary.
You can achieve this by defining a function that iterates over the list of dictionaries and checks for the presence of `old_key` in each dictionary. If it exists, you can create a new dictionary with `new_key` and `new_value`. If it doesn't, you return the original dictionary. Here's a sample implementation of such a f...
13,088
Here's how you could do it: ```python import re def normalize_line_breaks(text): text = re.sub(r'\r\n', '\n', text) text = re.sub(r'\r', '\n', text) lines = text.splitlines() normalized_text = '\n'.join(lines) return normalized_text ```
Write a Python function to perform a line break normalization on a string containing line breaks in multiple formats (CRLF, LF, or CR). The normalized string should only contain LF line breaks. You can assume that the maximum line length is 80 characters. Your code should pass the following test case: ```python sample...
You can implement the line break normalization function in Python as follows. This function will replace all line break formats (CRLF, LF, and CR) with LF, ensuring that the output string contains only LF line breaks. Here’s how you can do it: ```python def normalize_line_breaks(text): # Replace all CRLF (Windows)...
13,089
To write a Python function that takes an object and a list of attributes as input and returns a dictionary containing the values of the attributes, follow these steps: 1. Define a function `get_attributes_dict` that takes three parameters: `obj`, the object to retrieve attributes from; `attributes`, the list of attrib...
Write a Python function that takes an object and a list of attributes as input and returns a dictionary containing the values of the attributes. If an attribute is not present in the object, return `None` and throw an exception. Handle the exception to gracefully handle the error and return the entire dictionary filled...
You can achieve this by defining a function that iterates over the list of attributes. For each attribute, it will try to get the value from the object. If the attribute does not exist, an exception will be caught, and the function will return a dictionary filled with `None` values. Here's one way to implement this: `...
13,090
Here's how you can implement the function in Python: ```python def bfs_shortest_path(graph, start_node): node_dist = {node: float('inf') for node in graph} node_dist[start_node] = 0 queue = [start_node] while queue: node = queue.pop(0) for neighbor in graph[node]: if node_d...
Given a directed graph, written as an adjacency list, write a Python function to find the shortest path from a starting node to all other nodes in the graph using BFS. Return the distances to each node and the number of edges in the shortest path from the starting node to each node. The function should return a diction...
Certainly! To find the shortest path from a starting node to all other nodes in a directed graph using Breadth-First Search (BFS), we can utilize a queue to explore nodes layer by layer. We'll keep track of the distances and the number of edges used to reach each node. Here's a Python function that does exactly that. ...
13,091
Since the input is a list of data objects with `name` and `age` attributes, it is important to loop through the list and extract the values of these attributes for each object. Then, these values can be added as key-value pairs to a dictionary for each object, and the resulting dictionaries can be added to a list that ...
Develop a Python function to format a list of typed data (a list of objects with `name` and `age` attributes) and print it in a readable, structured format. The function takes a list of data objects and returns a JSON-encoded string with indentations, where each object is represented as a dictionary with key-value pair...
You can create a Python function to format a list of objects containing `name` and `age` attributes by converting them into dictionaries and then using `json.dumps()` to generate a nicely formatted JSON string. Below is a demonstration of how you can implement this: ```python import json class Person: def __init_...
13,092
To create the `translate_coords` function, you'll need to understand how to work with 2D coordinate tuples and how to apply translations to them. Here's how you can reason about the solution: 1. Define the function with the appropriate parameters. 2. Iterate over the input coordinates and translations using `zip`. 3. ...
Create a Python function named `translate_coords` that takes a list of tuples representing coordinates in a 2D coordinate system and a list of 2-element tuples representing translations. The function should return a new list of tuples with the coordinates translated according to the provided translations. The input lis...
Certainly! Here’s a Python function named `translate_coords` that will accomplish what you described. The function takes two parameters: a list of coordinate tuples and a list of translation tuples. It returns a new list of coordinates that have been translated accordingly. ```python def translate_coords(coordinates, ...
13,093
The code generation task can be solved by iterating over the keys in the dictionary and checking if they are in the given list of keys. If the key is in the list, the value associated with that key is appended to the output list. Here is a Python implementation of the code generation task: ```python def code_gen(dict...
Write a Python function that takes a list of strings and creates a dictionary with the strings as keys and their lengths as values. Return the dictionary./README.md # CodeGen-101 This repository hosts the [CodeGen-101](https://github.com/salesforce/CodeGen-101) dataset, which consists of 200 example code generation in...
Here is a Python function that takes a list of strings and creates a dictionary where each string is a key and its length is the corresponding value: ```python def strings_to_lengths(string_list): """ Create a dictionary with strings as keys and their lengths as values. Parameters: string_list (list o...
13,094
Here is the implementation of the `get_japanese_cities_with_coordinates` function: ```python import json def get_japanese_cities_with_coordinates(cities_file): with open(cities_file, 'r') as json_file: cities_data = json.load(json_file) result = [] for city in cities_data: if 'ja' in city[...
Load a JSON file called `cities.json` that contains a list of cities in Japan, their names in different languages, and their coordinates. Write a Python function named `get_japanese_cities_with_coordinates` that takes a list of cities and returns a list of Japanese cities with their coordinates. The function should al...
To create a Python function that loads a JSON file containing a list of cities in Japan, extracts those cities along with their coordinates, and outputs the number of Japanese cities in the list, you can follow these steps: 1. Load the JSON file. 2. Filter the list to only include Japanese cities. 3. Return the list o...
13,095
To create a function that takes a dictionary and interpolates its values into a sentence, let's follow these steps: 1. Extract the values of the keys "name", "age", and "hobby" from the dictionary. 2. Format the string using interpolation to replace the placeholders "{name}", "{age}", and "{hobby}" with the correspond...
Write a Python function that takes a dictionary as an argument and returns a string. The dictionary will contain keys "name", "age", and "hobby". The function should return a string that interpolates the values of these keys into the following sentence: "My name is {name}, I am {age} years old, and my hobby is {hobby}"...
Here's a Python function that takes a dictionary with the specified keys and returns the desired string: ```python def interpolate_info(person_info): name = person_info.get("name") age = person_info.get("age") hobby = person_info.get("hobby") return f"My name is {name}, I am {age} years old, and m...
13,096
To implement a Python function to parse a composite key in the format of `prefix/id` and return the `id` part, you can follow these steps: 1. Validate the input string to ensure it's in the expected format. 2. Split the string using the `/` character as the delimiter. 3. Check if the `prefix` part is missing and retur...
Implement a Python function to parse a composite key in the format of `prefix/id` and return the `id` part. If the `prefix` part is missing, return the original string. If the string cannot be parsed, raise an exception. You can use the existing function `split_composite_key` as a starting point.
To implement the desired functionality, we can define the function that will check for the format of the string, parse the composite key, and return the `id` part or handle cases where the parsing is not successful. Below is a Python implementation of this requirement: ```python class ParsingError(Exception): """C...
13,097
Here's how you could implement this using Python: ```python def find_leaf_nodes(tree: dict, node: str, leaf_nodes: list) -> list: if not tree[node]: leaf_nodes.append(node) else: for child in tree[node]: find_leaf_nodes(tree, child, leaf_nodes) return leaf_nodes tree = { 'A...
Write a Python function that recursively traverses a tree-like dictionary and returns a list of all the leaf nodes in the tree. The tree is represented as a dictionary where each key is a node and its value is a list of child nodes. A leaf node is a node with no children. For example, given the following dictionary re...
You can achieve this by writing a recursive function that checks each node in the tree-like dictionary. If a node has no children (i.e., its value is an empty list), it is considered a leaf node and can be added to the result list. Here's a Python function to traverse the tree and collect all the leaf nodes: ```pytho...
13,098
Here's how you can check if a compiler name is valid in Python using the `re` module and regular expressions: ```python import re def is_valid_compiler_name(name): pattern = r"^(\w+_\d+_)(linux|windows)$" return bool(re.match(pattern, name)) ``` The `re.match` function matches the regular expression pattern ...
Write a Python function to check whether a given compiler name is valid or not. The function should return `True` if the name matches the following pattern: ``` "compiler_name (version, os)" ``` where `compiler_name` is a string of alphanumeric characters and underscores, `version` is a string of digits, and `os` is ...
Certainly! You can use the `re` module in Python to define a regular expression that matches the required pattern for compiler names. Here's how you can implement the function: ```python import re def is_valid_compiler_name(compiler_name): # Define the regex pattern for a valid compiler name pattern = r'^[a-z...
13,099