Dataset Viewer
Auto-converted to Parquet Duplicate
original_prompt
stringlengths
60
2.92k
original_completion
stringlengths
300
3.38k
enhanced_prompt
float64
enhanced_completion
float64
I am writing a web scraper to extract data from a specific website. The scraper is working but it's not fully robust because the website's HTML code is inconsistent. Sometimes it uses empty `<div>` tags and sometimes it doesn't. I need to write a function that takes the HTML text as an input and returns a boolean indic...
To write a function that takes the HTML text as an input and returns a boolean indicating whether the text has a particular string, you can use regular expressions. Regular expressions are powerful tools for pattern matching and are widely used in text processing and web scraping. Here's an example implementation in P...
null
null
Given a string in the form of an XML document, write a Python function to parse the document and return a dictionary of the tag names and their corresponding values. The value of each tag should be a list of strings representing the text in the tag. For example, if the input string is `<root><tag>text</tag><tag>other t...
Here is how you could implement the function to parse XML documents and return a dictionary of tag names and their corresponding values: ```python import xml.etree.ElementTree as ET def parse_xml(xml_string): root_element = ET.fromstring(xml_string) def traverse_xml(element, tag_values): for child in ...
null
null
Design a Python function `count_attributes` that counts the number of attributes associated with a given object. You can assume the object has a method named `__dict__` that returns a dictionary of its attributes.
To count the number of attributes associated with a given object, you can use the `__dict__` method to retrieve a dictionary of its attributes. The length of this dictionary is the number of attributes. ```python def count_attributes(obj): return len(obj.__dict__) ``` The `__dict__` method returns a dictionary of...
null
null
Design a Python function `convert_time_format` that takes a datetime string in the format `YYYY-MM-DDTHH:MM:SS` and converts it to a different format `YYYY:MM:DD HH:MM:SS`. Additionally, calculate the total number of seconds between the two times.
Here's how you could do it: ```python from datetime import datetime def convert_time_format(datetime_string): datetime_object = datetime.strptime(datetime_string, '%Y-%m-%dT%H:%M:%S') converted_format = datetime_object.strftime('%Y:%m:%d %H:%M:%S') return converted_format def calculate_time_difference(d...
null
null
Write a Python function that returns a constant value. The function should take a single argument, which is the value to be returned. If no argument is provided, the function should return the integer 42. Your code should pass the following assertions: ```python assert return_value() == 42 assert return_value(123) == ...
To construct a function that always returns a constant value, let's follow these steps: 1. Evaluate the argument: Evaluate the argument provided to the function to determine whether it is a valid input. If not, return the default value (in this case, 42). 2. Return the value: If the argument is valid, return it as the...
null
null
Write a Python function named `get_func_info` that takes a string containing code and returns a list of information about the functions contained in the code. The output should be a list of dictionaries, where each dictionary represents a function. The dictionary should contain the function name, decorator names, and w...
```python import ast def get_func_info(code): class FuncVisitor(ast.NodeVisitor): def __init__(self): self.funcs = [] def visit_FunctionDef(self, node): info = {'name': node.name, 'decorators': [], 'is_class_method': False} for decorator in node.decorator_list: ...
null
null
Write a Python function that takes a list of dictionaries representing hierarchical data, and returns a list of tuples containing the name and the parent of each node in the hierarchy. For example, given the following input: ``` data = [ {'name': 'root', 'parent': None}, {'name': 'child1', 'parent': 'root'}, ...
Here's the code for the function: ```python def get_hierarchy(data): hierarchy = [] for item in data: name = item['name'] parent = item['parent'] hierarchy.append((name, parent)) return hierarchy ``` The function `get_hierarchy` takes a list of dictionaries as input and returns a l...
null
null
Design a Python function `extract_words_from_text(text)` that takes a string of text as input and returns a set of unique words that appear in the text, without any punctuation or word-wrapping. This function should utilize a trie structure to efficiently search for words in the text, and use a dictionary comprehensio...
The problem can be solved using a trie structure to efficiently search for words in the text. A trie is a data structure that organizes words or strings in a tree-like structure, where each node represents a character in the word, and the children of each node are the next characters in the word. The function should f...
null
null
Write a function to convert a version number of the form `"X.Y.Z"` to a string-formatted version of the form `"Version X.Y.Z"` if `Z` is non-zero, or `"Version X.Y"` if `Z` is zero.
Here is how you could implement the function: ```python def format_version(version: str) -> str: """ Format a version string of the form "X.Y.Z" to a string-formatted version of the form "Version X.Y.Z" if Z is non-zero, or "Version X.Y" if Z is zero. """ version_parts = version.split(".") if versi...
null
null
I have a function `f(x, y, z)` that takes three arguments and returns a string, and I need to create two new functions based on it: `f1` that takes x and y arguments and returns a function, and `f2` that takes z as an argument and returns the string output of the original function with x and y replaced by their specifi...
To create the `f1` and `f2` functions based on the given `f(x, y, z)`, let's first understand how they work: - `f1` takes x and y arguments and returns a **function**. This function takes z as an argument and returns the string output of the original `f` function with x and y replaced by their specified values. - `f2`...
null
null
Create a Python function `is_prime(n)` that efficiently determines whether a number is prime by factorizing it in the smallest possible way. You should implement this by recursively factorizing the number until you reach a number that is either 1 or a prime. If you reach 1 before reaching a prime, then the number is no...
Here's how you could implement the `is_prime` function: ```python def is_prime(n): factors = [] def factorize(current_num): if current_num == 1: return True is_prime = True for i in range(2, int(current_num ** 0.5) + 1): if current_num % i == 0: ...
null
null
Write a Python function that takes two objects and determines if the objects are equivalent based on the string representations of their constituent objects. The function should traverse the data structures of the objects and compare the string representation of each member.
To check if two objects are equivalent, you can recursively compare the string representation of their constituent objects. You can use the `str()` function to get the string representation of an object. Here's how you can write a Python function to compare two objects based on their constituent members: ```python de...
null
null
Write a Python function named `sort_by_field` that sorts a list of objects based on a specific field. The function should take three parameters: the list, the field name, and the sorting order (either 'ascending' or 'descending'). If the sorting order is not provided, default to ascending order. Return a new list that...
To sort a list of objects based on a specific field in Python, we can use the built-in `sorted` function. The `sorted` function takes a `key` parameter, which allows us to specify a function that returns the value to be used for sorting. In our case, we'll define a `key` function that returns the value of the specified...
null
null
Write a Python function `sample_vector_field` that samples a vector field in a 2D rectangular region. The function takes three arguments: `vector_field` (a PyTorch tensor), `sample_points` (a PyTorch tensor of shape `(N, 2)`), and `cell_size` (a positive integer). `vector_field` is a tensor with shape `(H, W, 2)`, wher...
To sample a vector field in a 2D rectangular region, we need to first establish the relationship between the grid points and the sample points. For this, we need to determine the mapping between the grid points and the sample points, which can be achieved by calculating the cell size and the offset from the origin. Aft...
null
null
Create a Python function to randomly assign items to one of three groups based on their hash values. The function should use the MD5 hashing algorithm to generate a 128-bit hash for each item. The first 25% of the items with the smallest hash values should be assigned to group 1, the next 25% to group 2, and the remain...
To achieve the random assignment of items to groups based on their hash values, we can use the MD5 hashing algorithm to generate a 128-bit hash for each item. The first 25% of the items with the smallest hash values will be assigned to group 1, the next 25% to group 2, and the remaining 50% to group 3. We can use a di...
null
null
Write a Python function to calculate the Mach number of an aircraft traveling at a speed of `TAS` m/s, where `TAS` is the true airspeed. The function should return a single value of the Mach number. Here is the Mach number formula: $$ M = \frac{TAS}{\sqrt{\gamma R T}} $$ where $\gamma$ is the specific heat ratio, $R$...
The Mach number is defined as the ratio of true airspeed to the speed of sound in the medium. In this case, the true airspeed is given as `TAS`, while the speed of sound is a function of the specific heat ratio ($\gamma$), specific gas constant ($R$), and absolute temperature ($T$). To calculate the Mach number, we ca...
null
null
Write a Python function to compute the coverage of a code change history. The function should take a list of files `files` and a list of commits `commits` as input, where each commit is a dictionary representing the changes made in that commit. The function should return a dictionary of the form `{file_name: coverage}...
First, we need to understand the structure of the input data. The `files` argument is a list of files, and each file is represented as a tuple of strings `(file_path, file_content)`. The `commits` argument is a list of commits, and each commit is a dictionary that contains information about the changes made in that com...
null
null
Design a Python function that takes a list of 3-tuples (each tuple representing a 3D point) as an argument and returns a new list of 3-tuples, where each tuple is the result of multiplying each element of the original tuple by 2. Use functional programming and lambda functions to achieve this result. The function shou...
The problem can be solved using functional programming and lambda functions in Python. Functional programming is a programming paradigm focused on expressing logic through functions and their transformations, rather than explicit statements. Lambda functions are anonymous functions that can be passed as arguments to ot...
null
null
Write a Python function `reformat_to_dict` that takes a dictionary and returns a new dictionary with the same keys, but with all values of type `dict` reformatted to only have keys that are strings. If a value is already a string, leave it unchanged; if it is a tuple or list, convert it to a dictionary with string keys...
We can design a Python function called `reformat_to_dict` that takes a dictionary and returns a new dictionary with the same keys, but with all values of type `dict` reformatted to only have keys that are strings. If a value is already a string, leave it unchanged; if it is a tuple or list, convert it to a dictionary w...
null
null
Develop a Python function `convert_record_format` that converts a given record from a dictionary format to a tuple format. The input record is a dictionary where the keys are attribute names and the values are attribute values, and the output format is a tuple, where the first element is a list of attribute names and t...
To convert a record from a dictionary format to a tuple format, we can use the dictionary's `.keys()` and `.values()` methods to get the list of keys and values. We can then combine these lists into a tuple structure where the first element is a list of keys and the second element is a list of values. This tuple can be...
null
null
Implement a Python function that takes a directory path, a list of file names, and a string as inputs, and returns a list of file paths. The function should create file paths by concatenating the directory path and each file name in the list, and append the input string to the end of each file name.
To create file paths by concatenating a directory path and each file name in a list, we can use the `os.path.join()` function from the `os` module. We can also append the input string to the end of each file name using a list comprehension. Here is the implementation of the function using the `os.path.join()` function...
null
null
Write a Python function `expand_variables(template, variables)` to expand variable names in a Jinja2 template string using a dictionary of variable names and values. The return value should be the template string with all variables expanded. The function should replace `{{}}` with the corresponding variable value in th...
To expand variables in a Jinja2 template string, you can use regular expressions to find and replace the variable names with their corresponding values in the dictionary. Here's a Python function that implements this logic: ```python import re def expand_variables(template, variables): pattern = re.compile(r'{{(\...
null
null
Write a Python function named `text_to_html` that takes a string of plain text and converts it into HTML format. The function should support the following features: - Links are converted into `<a>` tags. - Emails are converted into mailto links. - Phone numbers are converted into tel links. - Bold text is converted in...
The function will use regular expressions to match the various features of the plain text and convert them to the appropriate HTML tags. - **Links:** Links are converted into `<a>` tags. The function will look for URLs or hyperlinks in the text and convert them to the appropriate HTML anchor tags. - **Emails:** Emails...
null
null
Write a Python function `reload_page` that takes a `page` object and reloads it. The `page` object has a `.reload()` method that reloads the page. If the object does not have a `.reload()` method, it should be silently ignored and the function should return `False`. For any other type of input, the function should rais...
To check if the object has a `.reload()` method, you can use `hasattr`. This will ensure that the object has the `.reload()` method and you can use it to reload the page. If the object does not have a `.reload()` method, it should be silently ignored and the function should return `False`. If the input is not an object...
null
null
Create a Python function to count the number of times the state of a system switches from its initial state to a different state. The system is represented by a list of strings, and each string represents a state change in the system. The function should take the list as an input and return the number of state changes...
You can create a Python function to count the number of state changes by iterating through the list of strings and comparing each state to the previous state. Here's how you could do it: ```python def count_state_changes(states): if not isinstance(states, list) or not all(isinstance(state, str) for state in state...
null
null
Write a Python function `my_type` that takes one argument and returns a string representation of its type. The function should accept `None` as an input and return a `"NoneType"` string. Furthermore, the function should be documented and type annotated. Example: ```py >>> my_type(1) 'int' >>> my_type(1.0) 'float' >>> ...
The function should handle three cases: `None`, a built-in type, and an object with a user-defined type. Here is a Python function that meets the requirements: ```python from typing import Any def my_type(arg: Any) -> str: """Return a string representation of the type of the argument. Args: arg (Any...
null
null
I have a pandas data frame with the following columns: "name", "age", "major", and "gpa". I want to write a function `filter_by_major(df, major)` that returns a new pandas DataFrame with only the rows corresponding to the specified major. The function definition is provided below: ```python def filter_by_major(df, maj...
To filter rows based on a specific major in a pandas DataFrame, we can use the `loc` method, which allows us to select rows based on a boolean condition. The implementation of the function `filter_by_major(df, major)` is as follows: ```python def filter_by_major(df, major): return df.loc[df['major'] == major] ```...
null
null
Write a Python function `get_nth_fibonacci_number` that accepts a non-negative integer `n` as input and returns the nth number in the Fibonacci sequence. The function should use a recursive approach that meets the following conditions: Return 0 for `n = 0`, 1 for `n = 1`, and 2 for `n = 2`. For any other input, recursi...
Here's an example implementation of the function `get_nth_fibonacci_number` that meets the specified conditions: ```python def get_nth_fibonacci_number(n: int) -> int: if n == 0: return 0 elif n == 1: return 1 elif n == 2: return 2 else: return get_nth_fibonacci_number(n ...
null
null
Write a Python function to convert a number of pounds to kilograms. The function should have a docstring explaining its usage, including the input type and output type. Your code should pass the following assertion: ```python assert convert_pounds_to_kilograms(100) == 45.3592 ```
To convert pounds to kilograms, you need to multiply the number of pounds by 0.453592. Here's how you could write a docstring-enhanced function: ```python def convert_pounds_to_kilograms(pounds): """ Convert pounds to kilograms. Args: pounds (float or int): The number of pounds to be converted. ...
null
null
Write a Python function `type_check_convert(input, expected_type)` that takes an input argument and an expected type as arguments and returns the converted input value if the input is of the expected type or returns a string representation of the input value if not. The function should raise a `ValueError` if the input...
The goal of this function is to perform type checking and conversion for a given input value based on the expected type. It should return the converted input value if it is of the expected type, or return a string representation of the input value if not. Additionally, it should raise a `ValueError` if the input is not...
null
null
Write a Python function to parse a string of the form "x,y,z,..." into a tuple of (x, y, z, ...). You may assume that the string only contains a sequence of integers separated by commas. If the string is empty, return an empty tuple.
To parse the string into a tuple, we can use the Python built-in `str.split()` function to split the string into a list of strings, then convert each string to an integer using the `int()` function. We can then convert the list to a tuple using the `tuple()` function. ```python def parse_into_tuple(string): if not...
null
null
Write a Python function `generate_code(k)` that generates a string of length 6 consisting of uppercase alphanumeric characters. If `k` is 1, it should generate a random string where each character is drawn from the alphabet. If `k` is 2, it should generate a random string where each character is drawn from the numeric ...
```python import random import string def generate_code(k): def generate_from_alphabet(): return random.choices(string.ascii_uppercase, k=6) def generate_from_digits(): return random.choices(string.digits, k=6) def generate_from_alphabet_and_digits(): return random.choices(string....
null
null
Define a Python function `my_dot` that takes two arguments, `a` and `b`, and calculates the dot product of the two vectors `a` and `b` using the Python built-in functions (e.g., `zip`, `map`, `reduce`) and operators (e.g. `+`, `-`, `*`, `/`). The function should return a scalar value.
Here is an implementation of the `my_dot` function in Python: ```python from functools import reduce def my_dot(a, b): return reduce(lambda x, y: x + y, map(lambda x: x[0] * x[1], zip(a, b))) ``` The `zip` function in Python is used to iterate over the elements of the two vectors `a` and `b` simultaneously. The ...
null
null
For a given integer `num` in decimal, write a Python function to return its binary string representation with no leading zeroes. Additionally, the `'b'` format specifier can be used to format an integer as a binary string, which may come in handy. Your code should pass the following assertions: ```python assert decim...
Here's an example: ```python def decimal_to_binary_no_leading_zeroes(num): return format(num, 'b') ``` In this implementation, we use the `'b'` format specifier in the `format` function to convert `num` to a binary string representation. The `'b'` format specifier returns the binary representation of `num` as a s...
null
null
Write a Python function that takes a list of numbers and produces a string containing the numbers in the order they appear in the list, with a comma and a space between each number. The function should also add a prefix to each number (e.g., "X:" for the first number, "Y:" for the second number, etc.) and return the re...
To write a Python function that takes a list of numbers and produces a string containing the numbers in order, with a comma and space between each number, and adds a prefix to each number, you can follow these steps: 1. Check if the input is a valid list of numbers. If the input is empty or `None`, return an empty str...
null
null
Develop a Python function `calculate_production_rate` that calculates the production rate of an oil field over a period of time. The function takes three arguments: `q_i`, the initial production rate in STB/D (standard barrels per day); `b`, the formation volume factor in STB/BBL (standard barrels per barrel); and `t`,...
Let's create a function `calculate_production_rate` to calculate the production rate of an oil field over a period of time. The function takes three arguments: `q_i`, the initial production rate in STB/D (standard barrels per day); `b`, the formation volume factor in STB/BBL (standard barrels per barrel); and `t`, the ...
null
null
I want to compare two lists or dictionaries. The lists or dictionaries should be considered equal if they are the same type (lists or dictionaries) and have the same length. If they are both lists, they are equal if all of their elements are equal. If they are both dictionaries, they are equal if all of their keys are ...
Here's how you can check whether two lists or dictionaries are equal: ```python def compare_lists_or_dicts(list1, list2): if (isinstance(list1, list) and isinstance(list2, list)) or (isinstance(list1, dict) and isinstance(list2, dict)): if len(list1) == len(list2): if isinstance(list1, list) an...
null
null
Write a Python function that takes a string as input and returns the longest substring in that string that is palindromic. A palindrome is a string that is the same in reverse.
To find the longest palindromic substring in a given string, we can use the following approach: 1. Iterate through the string, starting from the first character. 2. For each character, expand outwards to check for palindromes. 3. Keep track of the longest palindrome found so far. 4. Return the longest palindrome found...
null
null
Design a Python function to select atoms from a molecular dynamics simulation trajectory using residue names as a filter. The function should take a list of atom names, a list of residue names, and a list of atom names to select. The function should return a list of atoms that match any of the residue names, and the a...
Here is the implementation of the Python function to select atoms from a molecular dynamics simulation trajectory using residue names as a filter: ```python def select_atoms(atom_names, residue_names, atom_names_to_select): selected_atoms = [] if not residue_names or not atom_names_to_select: return se...
null
null
Write a Python function `boolean_match` that takes two arguments: `a` and `b`. If `a` is a boolean-like value, such as `True` or `False`, or a string that can be converted to a boolean, check whether `a` matches `b`. Return `True` if both `a` and `b` are equal, or if they can be converted to the same boolean value. Oth...
Here's how you can implement this: ```python def boolean_match(a, b): """Check whether a boolean-like value matches another value. Args: a: A boolean-like value, such as True or False, or a string that can be converted to a boolean. b: Another value to compare. Returns: True if bo...
null
null
Write a Python function named `neutron_mass` to compute the mass of a neutron given an input of a non-negative temperature in Kelvin. The function should validate the input and raise an exception if the input is less than zero. Additionally, it should check whether the input is greater than or equal to the critical tem...
Here is how you could implement the function: ```python def neutron_mass(temperature_in_kelvin): if temperature_in_kelvin < 0: raise Exception("Input temperature cannot be less than zero.") elif temperature_in_kelvin >= 59.3: return 0.93827208816e9 else: return 1.674927471 * 10**(-2...
null
null
Write a Python function to generate a random key using a specific format: the first 4 characters should be letters (both uppercase and lowercase), and the remaining 8 characters should be alphanumeric (letters and numbers). For example, the function may generate the following keys: ``, ``, and ``.
Here is a Python function that implements this approach: ```python import random LETTERS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" DIGITS = "0123456789" def generate_random_key() -> str: """Generates a random key using a specific format.""" first_4_chars = random.choices(LETTERS, k=4) rema...
null
null
Write a Python function named `parse_tuples` that takes a string as an argument and returns a list of tuples. Each tuple contains three elements: a string before the first colon as the key, a string between the first colon and the second comma as the value, and a string after the second comma as the type. The function ...
Here's a Python function that implements this approach: ```python import re def parse_tuples(string): """ Parses a string into a list of tuples. Each tuple contains three elements: a string before the first colon as the key, a string between the first colon and the second comma as the value, and a str...
null
null
Develop a Python function that takes a list of numbers and returns a new list with the smallest and largest numbers removed. The function should also validate input and raise `ValueError` if the input is not a list of numbers.
Here's how you can implement this: ```python def remove_smallest_largest(numbers): if not isinstance(numbers, list): raise ValueError("Input must be a list.") for num in numbers: if not isinstance(num, (int, float)): raise ValueError("Input list must contain only numbers.") sor...
null
null
Write a Python function to check whether a given string is a palindrome, ignoring any non-alphanumeric characters. The function should employ early returns and short-circuiting to avoid unnecessary computation.
To check if a string is a palindrome, we can compare the string from both ends, character by character, until we reach the middle of the string. Here are the steps to craft a function that does this efficiently: 1. First, define a helper function `is_alphanumeric` that checks if a character is alphanumeric (letters or...
null
null
Design a Python function to validate a given dictionary against a schema with possible subschemas. The dictionary has the same key-value structure as the schema, but it may contain additional keys that are not in the schema. The function should return True if the dictionary conforms to the schema, or False otherwise. T...
Here's an example implementation of the function: ```python def validate_dict(dict_val, schema): if isinstance(schema, type): return isinstance(dict_val, schema) if isinstance(schema, dict): if not isinstance(dict_val, dict): return False for key, value in schema.items(): ...
null
null
Implement a Python function `curry_dict` that takes a dictionary and returns a curried function that takes a dictionary and applies the dictionary to the input dictionary. The curried function should take a dictionary as an argument and iterate through the dictionary. For each key-value pair, if the key does not exist ...
Here's how you could implement this function: ```python def curry_dict(input_dict): def curried(other_dict): for key, value in other_dict.items(): if key not in input_dict: input_dict[key] = value else: if not isinstance(input_dict[key], list): ...
null
null
I want to modify a function that takes an input string and replaces all instances of a given string `find` with another string `replace`. However, the input string may have an incorrect number of quotation marks. The function should recognize when this occurs and truncate the string to the point where the number of quo...
```python import re def modify_function(input_string, find, replace): if find == replace: count = input_string.count('"') if count % 2 != 0: # Odd number of quotation marks input_string = input_string.partition('"')[2] # Truncate the string after the first quotation mark pattern =...
null
null
Write a Python function that takes in a command line argument and formats it into a specific string. For example, given `arg = "John"`, the function should return ``` Hello, John. Your name is John. ``` The function should check for the existence of the argument, and if it's not there, should return ``` Hello, there...
Here's how you can implement this function: ```python def format_arg(arg): name = arg if arg is not None else "there" return f"Hello, {name}.\nYour name is {name}." ``` In this implementation, we first check if the `arg` is `None` using the ternary operator. If it's not `None`, we assign it to the `name` vari...
null
null
Write a Python decorator function `check_input` that checks if the type of the input argument is `int` or `float`. If the input is neither, raise an error with a custom message.
You can create a decorator function that takes a function as an argument and returns a wrapped function that checks if the input argument is an `int` or `float` type. If it's not, a custom error message can be raised. Here's how you could do it: ```python def check_input(func): def wrapper(*args, **kwargs): ...
null
null
Write a Python function `get_attribute_of_all_modules()` that loops through all modules in the current Python environment and retrieves their attributes. The function should return a list of attribute names for each module. The signature of the function should be `get_attribute_of_all_modules(module_name, attribute_nam...
Here's a possible implementation of the `get_attribute_of_all_modules()` function: ```python import sys def get_attribute_of_all_modules(module_name, attribute_name): attributes = [] for module in sys.modules.values(): if module.__name__ == module_name: if hasattr(module, attribute_name): ...
null
null
Create a Python function to perform large file copying while avoiding integer overflow. The function should take two file paths as input and copy the contents of the source file to the destination file. To avoid overflow, the function should perform file copying in chunks, where each chunk has a size that is a power of...
To perform large file copying while avoiding integer overflow, we can use the Python function `shutil.copyfileobj` from the `shutil` module. This function takes two file objects as input and copies the contents of one file to the other. To avoid overflow, we can split the source file into chunks with a size that is a p...
null
null
Write a Python function to return True if the input is an integer and False otherwise. Return None if the input is null. Your code should pass the following assertion: ```python assert is_int_or_null(123) == True ```
Here's an example implementation: ```python def is_int_or_null(input): if input == None: return None elif isinstance(input, int): return True else: return False ``` This function uses the `==` and `isinstance()` built-in methods to check if the input is null and an integer, respect...
null
null
Implement a Python function `traverse_graph(graph, start_node)`. This function should traverse a reference graph recursively, starting from the provided `start_node`, and return a list of all nodes in the graph that can be reached from the `start_node`. The reference graph is represented as a dictionary where the keys ...
Here's an example implementation of the `traverse_graph` function: ```python class Node: def __init__(self, label, references=[]): self.label = label self.references = references def traverse_graph(graph, start_node): traversed_nodes = [] def traverse(node): if node not in travers...
null
null
Write a Python function that, given a list of lat/lon pairs as input, returns the pair whose distance from the origin is least, formatted as a tuple of floats with a precision of 6 decimal places. Here's an example: ``` Input: [(35.345678, 22.678901), (35.334567, 22.789012), (35.345679, 22.678900)] Output: (35.345678...
```python import math def distance_from_origin(coordinates): lat1, lon1 = coordinates lat2, lon2 = 0, 0 radius_earth = 6371 # Radius of the Earth, in kilometers d_lat = math.radians(lat2 - lat1) d_lon = math.radians(lon2 - lon1) a = math.sin(d_lat / 2) ** 2 + math.cos(math.radians(lat1)) * ma...
null
null
Write a Python function that takes an RGB image as input and returns the average red, green, and blue values of the image. To achieve this, convert the image into a NumPy array using the `numpy.array()` function and then access the `ndim` attribute of the array to check if it is a valid image. If the `ndim` attribute i...
Here's how you can do it in Python: ```python import numpy as np def average_rgb(image): image_array = np.array(image) if image_array.ndim != 3: return None red_avg = image_array[:, :, 0].sum() / image_array.size green_avg = image_array[:, :, 1].sum() / image_array.size blue_avg = image_ar...
null
null
Implement a Python function `cardinality` that calculates the size of a set without actually constructing it. This function should accept one argument `X` and return an `int`. Additionally, the function should be able to handle optional type annotations, making it more flexible and adaptable to different input types.
You can create a Python function that calculates the size of a set without constructing it. The function should accept one argument `X` and return an `int`. Additionally, the function should be able to handle optional type annotations. Here's how you could do it: ```python from typing import Any, TypeVar X = TypeVar...
null
null
I have a CSV file with three columns: customer_id, order_date, and order_amount. The file contains data for each order placed by customers. Design a Python function that reads the CSV file line-by-line and calculates the total order amount for each customer. The function should return a dictionary that maps each custom...
To calculate the total order amount for each customer, we can use a dictionary to store the customer_id as the key and the total order amount as the value. We can iterate through the CSV file line-by-line, extract the customer_id and order_amount from each line, and update the total order amount for the customer in the...
null
null
Implement a Python function to perform a nested loop over two lists `l1` and `l2`, and return a list of dictionaries. The return list should contain a dictionary for each pair of elements from `l1` and `l2` where the first element's value is less than the second element's value. Your code should pass the following ass...
To solve this problem, you can use a nested loop over `l1` and `l2`, and check for each pair of elements if the first element's value is less than the second element's value. If this condition is met, you can create a dictionary with the values of these two elements as keys, and append this dictionary to the return lis...
null
null
Design a Python function to determine whether a dictionary `d1` is a partial order of another dictionary `d2`. The function should return `True` if every key-value pair in `d1` is also present in `d2`, and the values of `d1` are subsets of the corresponding values in `d2`. Otherwise, it should return `False`. If an exc...
This task requires us to design a Python function to determine whether a dictionary `d1` is a partial order of another dictionary `d2`. To do this, we can iterate through the key-value pairs of `d1` and check if they exist in `d2` and if the values of `d1` are subsets of the corresponding values in `d2`. We can use Pyt...
null
null
Develop a Python function to generate a string representation of a binary tree in level order traversal format, where each level is separated by a newline and each node is separated by a space. Example input: ```python class Node: def __init__(self, val): self.val = val self.left = None sel...
To generate a string representation of a binary tree in level order traversal format, we can use a breadth-first search algorithm, which is a common strategy for traversing a tree level by level. We can use a queue to keep track of the nodes at each level and generate the string representation accordingly. Here is a P...
null
null
Define a Python function `generate_random_coordinates` that generates a specified number of random coordinates within a given range of x and y values. The function should return a list of coordinates as tuples, where each tuple represents the x and y values of a coordinate. Generate the coordinates by randomly selectin...
To generate random coordinates, we can use the `random` module to generate random numbers within a given range. We'll use a list comprehension to generate the coordinates by randomly selecting integers within the specified range and creating a tuple of the x and y values. Then, we'll return the list of random coordinat...
null
null
Given a PyTorch model, write a Python function `count_trainable_parameters` to count the number of trainable parameters in the model. The function should return an integer representing the count.
To count the number of trainable parameters in a PyTorch model, we need to iterate over all the trainable parameters and accumulate their sizes. We can utilize PyTorch's built-in `parameters()` method to retrieve the model's trainable parameters, and then use a for loop to iterate over them. For each parameter, we can...
null
null
Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. An input string is valid if: - Open brackets must be closed by the same type of brackets. - Open brackets must be closed in the correct order. Note that an empty string is also considered valid. You...
To determine if a string is valid, we can use a stack to store the opening brackets and check if they match the closing brackets. If they match, we pop the opening bracket from the stack. Here's how we can implement this: ```python def is_valid(s): stack = [] for char in s: if char in ['(', '{', '[']:...
null
null
For this one, write a function that takes an argument `n` and returns a dictionary that has keys 1 through `n` and values equal to the squares of those keys. For example, the function should produce the output: `{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36}` for `n = 6`
Here is the implementation of the function: ```python def square_dict(n): return {i: i**2 for i in range(1, n + 1)} ``` The function uses a dictionary comprehension to create a dictionary with keys 1 through `n` and values equal to the squares of those keys. In the dictionary comprehension, the keys are generate...
null
null
Write a Python function to take a list of two-element tuples as input, where the first element is a string and the second element is an integer. The function should return a string in the format: "String1: Int1, String2: Int2, ..., StringN: IntN". For example, given [('a', 1), ('b', 2), ('c', 3)], the function should r...
Here's how you could do it: ```python def format_two_element_tuples(tuple_list): assert all(len(t) == 2 for t in tuple_list), "Each tuple must have two elements" formatted_string = "" for i, (s, n) in enumerate(tuple_list): formatted_string += f"{s}: {n}" if i < len(tuple_list) - 1: ...
null
null
Create a Python function that takes a list of strings as input and outputs a list of integers representing the number of characters in each string. Develop a test function with example input data and expected output to ensure the correctness of your code.
To solve this problem, you need to iterate through the input list of strings and count the number of characters in each string. To achieve this, you can use a for loop to iterate over the list and a `len()` function to get the length of each string. Here's an example implementation of the function: ```python def coun...
null
null
Create a Python function decorator `only_if_not_none` that takes a single function as an argument. If the decorated function returns a value other than `None`, the decorator should return the value directly. If the decorated function returns `None`, the decorator should return a string `'None'`. Create a docstring for ...
The decorator function `only_if_not_none` takes a function as an argument and returns a wrapper function that checks if the decorated function returns `None`. If it does, the wrapper function returns the string `'None'`, otherwise it returns the original function's return value unchanged. ```python def only_if_not_non...
null
null
Here is an example use case: ```python >>> d = {1: {2: {3: 4}}} >>> get_deepest_value(d) 4 ``` Create a Python function `get_deepest_value` that traverses a given dictionary and returns the deepest value found, which can be of any type. If the input is not a dictionary, the function should return `None`.
Here is a Python function that implements this approach: ```python def get_deepest_value(d: dict) -> object: """ Returns the deepest value in a given dictionary. """ if not isinstance(d, dict): return None deepest_value = None for value in d.values(): if isinstance(value, dict...
null
null
Create a Python function to generate a hash of a given string using the SHA-256 algorithm and encode the hash into a hexadecimal string. The function should take a string as input and return the hexadecimal representation of the SHA-256 hash of the string.
Here's the Python function that generates the SHA-256 hash of a string and encodes it as a hexadecimal string: ```python def generate_sha256_hash(string_to_hash: str) -> str: import hashlib hash = hashlib.sha256(string_to_hash.encode()).hexdigest() return hash ``` This function uses the `hashlib` library ...
null
null
Write a Python function that extracts the top K keys from a Python dictionary based on their values, and returns a list of these keys. The function should take in two arguments: a dictionary and an integer K. The function should return a list of the top K keys in descending order based on their values, which are assum...
Here's how you could implement the required Python function: ```python import logging def top_k_keys(dictionary, k): if not dictionary or k < 0: logging.warning("Input dictionary is empty or K is negative.") return [] sorted_items = sorted(dictionary.items(), key=lambda item: item[1], reverse...
null
null
I have an array of integers like `arr = [3, 1, 2, 5, 4]` and I want to sort it using a recursive version of [heapsort](https://en.wikipedia.org/wiki/Heapsort). I want to write the Python function `heapsort_recursive(arr)` which uses heapsort to sort the array and returns the sorted array. I also want to write a functi...
Based on the instruction, we can see that you want to implement a recursive version of heapsort and use a sifting-down function to help implement it. Here's one way to implement the functions `heapsort_recursive` and `sift_down`: ```python def heapsort_recursive(arr): heap_size = len(arr) start = (heap_size -...
null
null
Write a Python function to find the deepest tree node in a binary tree and return the value. In the function, build a dictionary to map a node's value to its depth, and traverse the tree in a depth-first manner to update the dictionary. Return the value associated with the highest depth found.
To find the deepest tree node in a binary tree, we can traverse the tree in a depth-first manner and keep track of the depth of each node. We can use a dictionary to map a node's value to its depth, and update the dictionary as we traverse the tree. Finally, we can return the value associated with the highest depth fou...
null
null
Write a Python function to format a list of string sentences (like 'a' and 'b') into a single string, where each sentence is separated by a comma (no spaces) and the last sentence is prepended with 'and' (e.g., `a, b, and c`).
You can create a Python function that formats a list of strings into a single string, separating each string with a comma (no spaces) and prepending the last string with 'and'. Here's how you could do it: ```python def format_sentences(sentences): if len(sentences) == 0: return '' elif len(sentences) ...
null
null
I have a list of tensors of shape (N, 5) representing bounding boxes (including the bbox coordinates and the label) in a single batch. I want to group the bounding boxes by their labels. The output should be a dictionary where the keys are the labels and the values are lists of bounding boxes of the corresponding label...
You can use a dictionary to store the grouped bounding boxes, where the keys are the labels and the values are lists of bounding boxes of the corresponding label. You can iterate through the list of bounding boxes and add each bounding box to the corresponding label in the dictionary. Here's how you can group the boun...
null
null
Create a Python function `encode_binary_to_base64` that encodes a binary string to base64. The function should use the `base64` module to perform the base64 encoding. The function should also import the `base64` module at the top of the file. Your code should pass the following assertions: ```python assert encode_bina...
Here is a Python function that uses the `base64` module to encode a binary string to base64: ```python import base64 def encode_binary_to_base64(binary_string): """ Encodes a binary string to base64 using the base64 module. """ encoded_bytes = base64.b64encode(binary_string.encode()) encoded_strin...
null
null
I have a list of dictionaries where each dictionary has fruit names as keys and their corresponding quantities as values. I want to combine the dictionaries into a single dictionary with counts of the fruit names. For example, given the dictionaries {'apples': 3, 'oranges': 4} and {'apples': 1, 'peaches': 2}, the resul...
Here's the Python function that implements this approach: ```python def combine_fruit_counts(dicts): combined_counts = {} for d in dicts: for fruit, count in d.items(): combined_counts[fruit] = combined_counts.get(fruit, 0) + count return combined_counts ``` The `combine_fruit_counts` ...
null
null
Write a function `flatten_one_level` that takes in a list of lists and flattens it one level. The function should be generic enough to accept any type of lists. Also, make sure to add appropriate type hints to the function to specify the type of input and output. Your code should pass the following test case: ```pytho...
Here's a Python function that achieves this using list comprehension: ```python from typing import TypeVar, List T = TypeVar('T') def flatten_one_level(lists: List[List[T]]) -> List[T]: return [item for sublist in lists for item in sublist] def flatten_one_level_sum(lists: List[List[T]]) -> List[T]: return ...
null
null
Write a Python function that parses an SSH URL and returns a tuple of the host, port, and path. The function should take a string as input and return a tuple containing the host, port, and path. If no port is specified, the function should assume the default SSH port of 22. The function should handle invalid URLs and ...
To parse an SSH URL and return a tuple of the host, port, and path, we can use the `urlparse` function from the Python standard library. This function parses a URL string and returns a named tuple containing the components of the URL. We can then extract the host, port, and path from the named tuple and return them as ...
null
null
Write a Python function that takes a dictionary and returns another dictionary with the same structure but with all the values set to None. The function should be able to handle nested dictionaries, and should make deep copies of all the values. Your code should pass the following test case: ```python dictionary = {'k...
Here's how you could do it: ```python def set_to_none(dictionary): dictionary_copy = {} for key, value in dictionary.items(): if isinstance(value, dict): dictionary_copy[key] = set_to_none(value) else: dictionary_copy[key] = None return dictionary_copy ``` This fu...
null
null
Define a Python function `edit_distance(str1, str2)` to compute the minimum number of edits required to transform one string into another. The allowed operations are: insertion, deletion, and substitution. Also, if either of the two strings is empty, return the length of the other string. For example, `edit_distance("a...
Here is the implementation of the `edit_distance` function using dynamic programming with a cache: ```python def edit_distance(str1, str2): m = len(str1) n = len(str2) cache = {} def edit_distance_helper(i, j): if i == m or j == n: return max(m - i, n - j) if (i, j) in cach...
null
null
Write a Python function that takes a list of integers as input and returns the sum of the elements of the list, provided the minimum value is at least 0 and the maximum value is at most 255. If the minimum is less than 0 or the maximum value is greater than 255, return -1.
You can create a Python function that takes a list of integers as input and iterates through it to find the minimum and maximum values. If the minimum is at least 0 and the maximum is at most 255, then you can return the sum of the list. Otherwise, you can return -1. Here's how you could do it: ```python def min_max_...
null
null
Given a genome file `example.fasta`, write a Python function `load_genome(file_name)` to load the genome data from the file in byte format and return it as a byte string. The function should use the `pickle` module to store the byte string for future use. Your code should pass the following test case: ```python genome...
Here's the code: ```python import pickle def load_genome(file_name): with open(file_name, 'rb') as file: genome_data = file.read() genome_string = pickle.dumps(genome_data) with open('genome_dump.pickle', 'wb') as file: pickle.dump(genome_string, file) return genome_string ``` This co...
null
null
Write a Python function to find the maximum length of a sequence of consecutive `1`s in a binary array. If there are multiple sequences of the same length, return the longest one with the lowest index.
To find the maximum length of a sequence of consecutive `1`s in a binary array, we can iterate over the array and keep track of the length of the current sequence and the maximum length. If we encounter a `0`, we reset the current sequence length to 0. If we encounter a `1`, we increment the current sequence length and...
null
null
Generate a Python function that takes a list of student names and a list of scores respectively, and returns a new dictionary where the student names are mapped to the corresponding scores. The scores list should be dynamically calculated based on the input student name list. For example, given `names = ['', '', '']`,...
Here's how you can implement this: ```python def map_names_to_scores(names, scores): if len(names) != len(scores): raise ValueError("The length of the names and scores lists must be equal.") mapping = {} for i, name in enumerate(names): score = scores[i] mapping[name] = score re...
null
null
Develop a Python function named `alpha_range` that takes two strings as arguments and returns a list of all the alphabetical characters in between them, including both endpoints. For example, `alpha_range('a', 'c')` should return `['a', 'b', 'c']` while `alpha_range('m', 'n')` should return `['m', 'n']`. You may assu...
Here's a Python implementation of the `alpha_range()` function: ```python def alpha_range(start, end): start_ord = ord(start) end_ord = ord(end) result = [] for i in range(start_ord, end_ord + 1): result.append(chr(i)) return result ``` The first step is to convert the input strings to t...
null
null
Write a Python function to validate an HTML anchor element's `href` attribute. The function should return True if the `href` is a valid URL, and False otherwise. The URL must be an absolute URL or a relative URL (relative to the current document). The absolute URL must start with one of the following: - http:// - htt...
To validate an HTML anchor `href` attribute, we can use the `urlparse` module from the Python standard library. This module provides a `urlparse` function that parses a URL into its components (scheme, netloc, path, etc.). We can check if the `scheme` component is empty or if it starts with one of the valid protocols. ...
null
null
Write a Python function `unique_occurrences` that takes a list of integers as an input and returns a dictionary mapping each unique occurrence to the number of times it appears in the list. Use dictionary comprehension and the `count` method of the `list` class to achieve this goal. Here's an example of using the `uni...
```python def unique_occurrences(my_list): return {item: my_list.count(item) for item in set(my_list)} ``` This implementation uses a dictionary comprehension to map each unique occurrence in the list to the number of times it appears in the list, using the `count` method of the `list` class. The `set` function is...
null
null
Write a Python function to convert a `bytearray` object to a string representation with each byte separated by commas. For example, the bytearray [1, 2, 3, 4, 5] should convert to the string "1,2,3,4,5".
To convert a `bytearray` object to a string representation with each byte separated by commas, you can follow these steps: 1. Initialize an empty string to store the result. 2. Iterate over each byte in the `bytearray` and append it to the string as a string representation, separated by a comma. 3. If there are more b...
null
null
Given a list of dictionaries, each of which has a key `acc_id` and a value `level` specifying the level of the player, create a new dictionary where the key is the level and the value is a list of the corresponding `acc_id`s. The dictionary should be sorted by key.
Here is the implementation using Python: ```python def create_level_dict(player_dict_list): level_dict = {} for player_dict in player_dict_list: acc_id = player_dict.get('acc_id') level = player_dict.get('level') if acc_id and level: if level not in level_dict: ...
null
null
Implement a Python function that applies a square root transformation to a given array `X` followed by an arcsine transformation. The function should return the transformed array. The square root transformation is defined as $y= \sqrt{x}$ and the arcsine transformation is defined as $y = \sin^{-1}(\sqrt{x})$. This is a...
To apply this square root transformation followed by the arcsine transformation to a given array of numbers, the following steps can be followed: 1. Apply the square root transformation: Calculate the square root of each element in the array using the `np.sqrt` function from the NumPy library. 2. Apply the arcsine tr...
null
null
Given a 3D tensor of shape `(D, H, W)` and a 2D tensor of shape `(H, W)`, write a Python function that multiplies the two tensors using `einsum` with the appropriate indices to produce a 3D tensor. The output tensor should have a shape of `(D, H, W)`. Your code should pass the following test case: ```python tensor_3d ...
To multiply these two tensors using `einsum`, we need to find a way to combine the indices of the two tensors in such a way that the result retains the shape `(D, H, W)`. We can achieve this by multiplying the corresponding elements of the two tensors for each different value of `d`. Here's how we can do this: ```pyt...
null
null
Write a Python function that takes a string as input and returns the type name of the object. The input string is in the format "name(type)". For example, the input string "name(int)" represents an object with the name "name" and the type "int". Your function should return the type name as a string.
To extract the type name from a string in the format "name(type)", we can use the `re` module and write a regular expression that matches the given pattern. The pattern consists of a group named "type" that matches any characters until the closing parenthesis. We can then extract the type name from the group using the ...
null
null
Create a function named `get_incomplete_tasks` that takes a list of tasks (each with a boolean attribute `is_complete`) and returns all the incomplete tasks.
To return all the incomplete tasks in a list, we can first filter the list to only include incomplete tasks using the `filter` function. The `filter` function takes a predicate function that returns `True` for tasks that meet our criteria (in this case, `is_complete == False`). After filtering, we can then use the `lis...
null
null
Write a Python function that defines a custom data type called `DataTime`. Upon initializing a `DataTime` object, it should store a timestamp in the form of a number representing the number of seconds since a specific date. The function should define the following methods: - `timestamp`: Returns the timestamp as a num...
Here's one possible implementation of a `DateTime` class: ```python class DateTime: def __init__(self, timestamp): self.timestamp = timestamp def seconds(self): return self.timestamp def __add__(self, other): return DateTime(self.timestamp + other.timestamp) def __sub__(self,...
null
null
I have an object structure of the following form (the variable `obj` holds the top-level object): ```python class Top: def __init__(self, x, y): self.x = x self.y = y class Mid: def __init__(self, a, b, c): self.a = a self.b = b self.c = c class Bottom: def __ini...
Here is a Python function that implements this approach: ```python def increment_object(obj): """ Increases all attributes of type `int` by 1 in the given object. """ if type(obj) is int: return obj + 1 if not isinstance(obj, (dict, list)): for attr, value in vars(obj).items(): ...
null
null
Write a Python function to merge two dictionaries that represent JSON objects and return the resulting dictionary. Avoid duplicate keys by overwriting the corresponding values with the values from the second dictionary.
You can create a Python function that merges two dictionaries by iterating through the keys in the second dictionary and updating the corresponding key-value pairs in the first dictionary. Here's how you could do it: ```python def merge_json(json1, json2): for key, value in json2.items(): if key not in js...
null
null
Write a Python function that takes two parameters, `x` and `y`, and returns the result of the following expression: $ \begin{cases} x^2 & \text{if $y$ is even, or} \\ x^3 & \text{if $y$ is odd, or} \\ x^4 & \text{if $y$ is a multiple of 4}. \end{cases} $ Your code should pass the following assertions: ```...
To solve this problem, we need to check the conditions for each case and return the appropriate value based on the input. Here is the implementation: ```python def conditional_power(x, y): if y % 4 == 0: # Check if y is a multiple of 4 return x**4 elif y % 2 == 0: # Check if y is even return...
null
null
Create a Python function `parse_column_names` that parses a comma-separated string of column names containing special characters. The function should perform the following operations: 1. Remove all leading and trailing spaces. 2. Remove all leading and trailing commas. 3. Split the string into a list of individual col...
To create a Python function that parses a string of column names containing special characters, we can use the built-in Python string methods such as `.strip()` and `.split()`. Here is the implementation of the `parse_column_names` function: ```python def parse_column_names(column_names_str): column_names = [] ...
null
null
Write a Python function `rearrange_by_position` that takes a list of dictionaries and a list of indices, and returns a new list with the dictionaries reordered based on the given indices. Here's an example: ```python mylist = [{'pos': 0, 'name': 'A'}, {'pos': 1, 'name': 'B'}, {'pos': 2, 'name': 'C'...
I've designed a custom `key` function that takes a dictionary as input and returns the value of the `'pos'` key. This function is used to sort the list of dictionaries based on the `'pos'` key using the `sorted` function. Tuple unpacking is used to extract the `itemgetter` result from the `key` function. Here is the i...
null
null
End of preview. Expand in Data Studio

Self-OSS Code Instructions

Python instructions with execution-filtered solutions.

Rows 2,000
Domain programming
Format data.parquet, one row per example
Licence odc-by
Built for supervised fine-tuning (SFT) experiments on Adaption AutoScientist

Columns

Column Description
original_prompt The prompt (user turn) as uploaded.
original_completion The target response as uploaded.
enhanced_prompt Empty in this dataset.
enhanced_completion Empty in this dataset.

How it was built

Sampled from Self-OSS-Instruct (exec-filtered).

Sources and licence

Notes

  • Columns enhanced_prompt, enhanced_completion are empty in this dataset (the Adaption export reserves them for rewritten text).

Loading

from datasets import load_dataset
ds = load_dataset("rodriguescarson/adaption-codeskill-raw-selfoss-2k", split="train")
import pandas as pd
df = pd.read_parquet("hf://datasets/rodriguescarson/adaption-codeskill-raw-selfoss-2k/data.parquet")

Published by Carson Rodrigues (Hugging Face, Kaggle).

Downloads last month
39