Dataset Viewer
Auto-converted to Parquet Duplicate
prompt
stringlengths
20
2k
Write a Python function named `get_value` that takes a matrix (represented by a list of lists) and a tuple of indices, and returns the value at that index in the matrix. The function should handle index out of range errors by returning None.
Write a Python function `check_collision` that takes a list of `rectangles` as input and checks if there are any collisions between any two rectangles. A rectangle is represented as a tuple (x, y, w, h) where (x, y) is the top-left corner of the rectangle, `w` is the width, and `h` is the height. The function should r...
Create a Python function to serialize and deserialize an object using the pickle module. The function should take an object and a filename as input, and serialize the object into a file using pickle. The function should also take a filename as input and deserialize the object from the file using pickle. The deserializa...
Implement a Python function `blocked_matrix_multiply` that takes two matrices as inputs and returns their product using blocked matrix multiplication. The function should take advantage of the blocked nature of the matrices to divide them into submatrices, perform the matrix multiplication on these submatrices, and the...
Write a Python function that takes two lists `A` and `B`, each representing a matrix, and returns their sum in the form of a new list. The matrices are of the same size, and each element of the output matrix is the sum of the corresponding elements in `A` and `B`.
Given a list of dictionaries, your goal is to traverse the list and create a new list with the value of the key `'id'` for each dictionary. For example, given `[{'id': 1, 'name': 'John'}, {'id': 2, 'name': 'Bob'}]`, the desired output would be `[1, 2]`. Make use of list comprehension and dictionary lookup to solve the ...
Write a Python function that takes a list of strings and a special string, and returns a list of strings sorted using a lexicographic comparison. However, the special string should be treated as smaller than all other strings. The function should return a sorted list of strings in the same order as the input. For exam...
Write a Python function to generate [Pascal's Triangle](https://en.wikipedia.org/wiki/Pascal%27s_triangle) up to an arbitrary height. The function should take in an integer `n` as input and return a list of `n` lists, where each list represents a row of the triangle. The output should be in the form of integer lists, w...
Implement a Python function to convert a positive integer number from its decimal representation to its binary (base 2) representation as a string. Your function should recursively convert the integer number by repeatedly dividing it by 2 and adding the remainder to the result string. If the integer number is 0, return...
Write a Python function that returns the factorial of a given natural number. The function should support recursion and should be properly commented. The function should check for valid input and return an error message if the input is not a natural number. Here is an example of a factorial function: ```python def fa...
Write a Python function that takes a list of numbers and modifies it in place by squaring all the elements that are divisible by 3. You can do this by modifying the input list directly without returning a new list. ### Instruction (2) Modify the function you wrote in the previous prompt to also modify the input list s...
Write a Python function to encode a list of integers into a string of characters. Convert each integer to its corresponding ASCII character and concatenate all characters together to form the final encoded string. For example, given the list `[65, 66, 67]`, the function should return the string `'ABC'`.
Write a function `append_docstring` that takes a Python function as an argument and a string to append to the function's docstring. The function should return the modified function with the docstring appended. Here is an example of how the function should work: ```python def my_function(): """A function that does...
Write a Python function to convert a list of keys and values into a dictionary. Keys must be unique and values may be duplicated. The function should transform the dictionary by grouping duplicate values into a set for each key. For example, given keys=[1, 2, 3, 4], values=[10, 20, 30, 40], the function should return {...
Write a Python function `unwrap_string` that takes in a wrapped string and unwrapped it into a single string. Each line of the wrapped string is separated by a newline character, and the words in the wrapped string are separated by a single space. For example, given the wrapped string `"Hello\nWorld"`, the output shou...
Write a Python function that takes a string as the first argument and any number of keyword arguments as the second argument. The function should return a URL string that is constructed from the given string and the keyword arguments. Each key-value pair of the keyword arguments should be appended to the URL string as ...
Write a Python function to calculate the sum of the first `n` natural numbers. Implement the function using a list comprehension and arithmetic operations. Your code should pass the following assertions: ```python assert sum_of_natural_numbers(1) == 1 assert sum_of_natural_numbers(5) == 15 ```
Create a Python function that takes two strings, `s1` and `s2`, and return their numerical difference. If either string cannot be converted to a valid number, return 0. Your code should pass the following assertions: ```python assert numerical_difference("123", "100") == 23 assert numerical_difference("abc", "100") ==...
Write a Python function that generates 20 random usernames, each with 10 characters, each character being a random lowercase letter or a random digit. Your code should pass the following test case: ```python usernames = generate_usernames() assert len(set(usernames)) == 20 assert all(len(username) == 10 for username i...
Write a function `sum_dict` that takes two dictionaries, `d1` and `d2`, as input, and returns a new dictionary that contains the sum of the values of the two dictionaries. If a key exists in both dictionaries, then the value of the key in the resulting dictionary should be the sum of the values from the two dictionarie...
Create a Python function that takes a string `s` as input and returns a string where each word is reversed, but the order of the words remains the same. The words in the string are separated by whitespaces. Here are some example inputs and their corresponding outputs: | Input | Output | | --- | --- | | "Hello world" ...
I have a Python script that generates a nested data structure to represent a company's organizational structure. The data structure is a dictionary where each key-value pair represents a department and its employees, respectively. Here's an example: ```python { 'Engineering': [ 'Alice', 'Bob', ...
Write a Python function to calculate the intersection of union (IoU) metric between two bounding boxes represented as dictionaries with the following structure: `{ 'x': <float>, 'y': <float>, 'width': <float>, 'height': <float> }`.
Write a Python function to initialize a table of 0s, where the table size is determined by the input. The input is a list of two integers, `row` and `col`, indicating the number of rows and columns of the table. For example, if the input is `[2, 3]`, the function should return `[[0, 0, 0], [0, 0, 0]]`.
Given a 2D numpy array `arr` and a scalar `threshold`, return a new array with all values from `arr` less than `threshold` set to `0` and all values greater than or equal to `threshold` set to `1`. Make sure the return array is a copy of `arr`, and the function can handle different sizes of `arr`.
Create a Python function named `get_module_names` that takes a list of named tuples, each representing a module, and returns a list of module names. The module is a named tuple with `name` and `description` keys. If the module's description is empty, return the name without its version suffix. If the module's name is n...
Given a list that contains some empty elements, write a Python function to filter out these empty elements and return a new list with only non-empty elements. Your code should pass the following test case: ```python lst = [1, 2, 3, None, 4, None, 5] expected_result = [1, 2, 3, 4, 5] assert remove_empty(lst) == expecte...
Write a Python function `convert_names` that takes a list of strings representing attribute names and returns a new list of modified strings. The conversion involves replacing all occurrences of the pattern `snake_case` with `camelCase`, where the first letter following the underscore is capitalized. Use regular expres...
Write a Python function that takes a non-negative integer, representing a number of seconds, and converts it to a string representing the time in hours:minutes:seconds format. For example, 120 seconds should be converted to "0:02:00".
Given a dictionary `d`, write a Python function that returns a shallow copy of `d` by omitting entries with missing keys. Let's call this new dictionary `d_copy`. If any of the entries of `d_copy` has a value type of dictionary, then delete the entire dictionary entry from `d_copy`. For example, if `d = {'a': 1, 'b': ...
Here is a dataset of JSON-encoded text entries. Each entry contains a `type` field, which may be one of `record`, `document`, `formula`, or `table`. If the entry is a `record`, it contains a `data` field with an object containing a `foo` field. If the entry is a `document`, it contains a `data` field with an object con...
Write a Python function named `filter_and_update_dict`. This function takes two dictionaries as input parameters: `input_dict` and `update_dict`. The function filters the `update_dict` based on the keys that exist in `input_dict` and updates the values of the `input_dict` with the filtered `update_dict`. The function s...
Write a Python function `intersection` that takes two lists `A` and `B` and returns a new list `C` that contains only the elements that are common between the two lists. Use a list comprehension to construct the list `C`. The function should not modify the input lists.
Implement a Python function `compare_integers(n1, n2)` that compares two integers and returns their comparison status as a string. The input integers can be of any type (int, float, or string). The function should handle input validation to ensure that the inputs are valid integers (or can be converted to valid integer...
Develop a Python function `is_prime` that determines whether a given integer `n` is prime. The function should return a Boolean value indicating whether `n` is prime or not. Your code should pass the following assertions: ```python assert is_prime(8) == False assert is_prime(2) == True assert is_prime(3) == True ```
Write a Python function `rng_sampler(n, k)` that generates `k` random integers in the range `[0, n]` uniformly and independently. The function should take the following arguments: - `n` (int): the upper bound of the generated random numbers, inclusive - `k` (int): the number of random numbers to generate The function...
Write a Python function to convert temperature data between Celsius and Fahrenheit. The function takes two arguments: the temperature value and the unit, which is either `'C'` for Celsius or `'F'` for Fahrenheit. The function should return the converted temperature in the chosen unit. Here's the conversion formula: $...
Create a Python function to convert a tuple of HSV (Hue, Saturation, Value) color values to a tuple of RGB (Red, Green, Blue) color values. The input tuple consists of 3 values between 0 and 1, where the first value represents the hue, the second the saturation, and the third the value. The output tuple should consist ...
Write a Python function that accepts a function `func` and arguments `*args`, and returns a function that calls `func` with the provided arguments and returns the result. This function should be named `call_with_args`. For example, given `func = lambda x, y: x + y` and `*args = (5, 10)`, the returned function should r...
I want to return an XML element node as a Python dictionary, where the dictionary keys are element names and the values are element text or nested elements (as dictionaries). If the element has attributes, they should be stored in a _k,v dictionary_ inside of the returned dictionary. If the element has no children or j...
Write a Python function that calculates the interest rate on a loan. Your function should take as input the loan amount, interest rate, and number of years and return the interest. Your code should pass the following test case: ```python loan_amount = 10000 interest_rate = 5 number_of_years = 3 assert calculate_intere...
Create a Python function that returns a list of all the keys in a dictionary that start with a given prefix. For instance, given prefix "a", the function should return ["apple", "aardvark", "avocado"] for the following dictionary: ```python {"apple": 1, "aardvark": 3, "avocado": 2, "banana": 5} ``` Your code should p...
Write a Python function that checks if an object is a subclass of a given class. The function should safely handle exceptions and return `False` if an exception is raised.
Write a Python function that accepts a single parameter `tuple_of_lists` representing a tuple of lists. The function should merge these lists into a single list, preserving the order of elements from the original lists. If a list is None or empty, it should be ignored. The function should return the merged list.
Write a Python function called `batch_convert_floats_to_bytes` that takes a list of floats and converts it to a list of bytes. The function should convert each float in the input list to a byte array of size 4, and return a list of these byte arrays. The function should also handle type checking and conversion, where ...
Write a Python function `write_pickle(filename, data)` to write the `data` to the file named `filename` in binary format using pickle. Then, write another function `read_pickle(filename)` to load the data from the file and return it. Use the `pickle` module to implement these two functions.
Code a Python function that takes a string as input and returns an integer denoting the total number of times the string's first character occurs anywhere in the string. For example, given the string `aaab`, the function should return `3` because the first character `a` occurs three times in the string.
Create a Python function that implements a key derivation function (KDF) and generates an encryption key. The function should accept a user ID and a key derivation salt as input, and should use the `hashlib.pbkdf2_hmac` function from the standard library to generate a 32-byte key. The function should also use an HMAC a...
Create a Python function that takes a list of `uploaded_files` and modifies the `upload_path` field of each object to remove the extension. The function should return a list of modified objects.
We have a function `f` that takes a list and returns a tuple of two elements: the first element is the first element in the list, and the second element is the number of elements in the list. We would like to test the function using mocking techniques to avoid the side effect of actually calling the function. We want t...
Write a Python function `image_mirror` that takes in an image as a list of lists of pixel values, and returns the mirrored image as a new list of lists. The function should mirror the image along the vertical axis and return the mirrored image as a new list. Your code should pass the following test case: ```python # T...
Create a Python function that generates a random string of length `n`, where `n` is an optional argument that defaults to 10. The function should return a string whose characters are randomly chosen from the set of lowercase letters `a` through `z` and the digits `0` through `9`. Additionally, the variable `n` should b...
Define a Python function `sum_ints_as_strings` that takes two strings representing integers, and returns their sum. It should handle input errors like non-numeric inputs, integer overflow, and handle all possible exceptions.
Write a Python function `query_replace` that replaces the values in an object that contains a mix of strings, integers, and floats. The function should take two arguments: `query_obj`, an object that contains objects, strings, and arrays, and `replacement`, the string to replace with. The function should recursively tr...
Write a Python function that takes an array and returns `True` if all its elements are unique, or `False` if there is at least one duplicate. Your code should pass the following test case: ```python arr1 = [1, 2, 3, 4, 5] arr2 = [1, 1, 2, 2, 3] assert has_duplicates(arr1) == False assert has_duplicates(arr2) == True `...
Write a Python function named `simple_cmp` that compares two objects by the result of a custom comparison function. Input: Two objects to compare, and a comparison function that takes two objects as arguments and returns -1, 0, or 1 depending on whether the first object is less than, equal to, or greater than the seco...
Write a Python function `process_data` to process a list of data objects, each of which has a `name` and a `value` property, into a single string. The string should concatenate the `name` and `value` properties for each object, separated by colons and then a newline.
Write a Python function that takes a dictionary d and a list l as parameters and returns a dictionary containing all the key-value pairs from d whose keys are in l. That is, the function should return a dictionary with keys from l and the corresponding values from d. The function should return an empty dictionary if d ...
I am writing a bittorrent client, and I need a function to encode an integer into a byte string in bencode format. Here are the rules: - if the value is an integer, it is represented as `i{value}e`. - if the value is a string, it is represented as `{length}:{value}`, where `{length}` is the length of the string in byt...
Write a Python function `curry` that takes a function `f` and a list of arguments `args` as input and returns a function that takes a list of arguments `rest` and applies them to `f` along with `args`. The returned function should support function currying.
Write a Python function `all_true` that accepts a list or tuple of boolean values and returns True if and only if all values are True. You should solve this problem using only one line of code and without using any conditional statements (if, else, and/or for-loops). Your solution should use Python's `all` function as ...
Given a string `s` consisting of only lowercase English letters, find and replace all occurrences of the letter `"a"` with the letter `"z"`. Additionally, replace all occurrences of the letter `"b"` with the letter `"y"`. All other letters should remain unchanged. Your code should pass the following test case: ```pyth...
Write a Python function that takes a project name as an input and returns a valid project ID for the Google Cloud Platform. The project ID should meet the following criteria: - 6-63 characters long - Only lowercase letters, numbers, and hyphens (-) - Must begin with a lowercase letter - Must end with a lowercase lette...
Develop a Python function named `sum_of_numbers()` that calculates the sum of all numbers in a given input list (either list of numbers or list of lists of numbers) recursively. The input can be a nested list containing integers and other nested lists. Your task is to return the sum of all numbers in the input list. I...
Write a Python function `convert` that accepts two arguments: `number` and `base` (a number between 2 and 16). The function should convert the given number to the corresponding value in the given base. Your solution should not use built-in functions that directly convert numbers to other bases, like `int.to_base()` or ...
Implement a recursive quick sort algorithm in Python. If the input is already sorted, it should return the input without modification. If the input is not sorted, it should sort the input using a recursive algorithm. If the input is empty, it should return an empty list. If the input is invalid, it should raise a `Valu...
Write a Python function that takes a `user_data` JSON object as input and returns a list of all user names with the role "admin". The function should iterate over all users and users' roles, and add the user's name to the list if the user has the role "admin". The input is a JSON object representing a list of users, w...
Write a Python generator function `generate_prime_numbers(n)` that generates prime numbers starting from $1$ until $n$. The generator should yield one number at a time, and should raise a `ValueError` exception if the input `n` is less than $1$.
Write a Python function `binarize_array` to binarize an array. The function takes a 2D array and a threshold value as the input. The function should return a binary array of the same shape as the input, where each element is either 0 or 1. An element in the output array is 1 if the corresponding element in the input ar...
Write a Python function that takes a string as input and returns a new string where all ANSI color sequences (i.e., sequences of escape codes starting with the escape character, `\x1b`, and ending with the letter `m`) are removed. Use regular expression to match the ANSI color sequence. Your code should pass the follo...
Write a Python function that takes a list of dictionaries representing a JSON array of objects, and returns a Python list of the objects after deserializing the JSON. If any of the objects have a "type" field with the value 'string', raise a `ValueError`.
Write a Python function that generates random `Node3D` objects with `x`, `y`, and `z` coordinates between 0 and 100. The function should take in three parameters: - `n`: the number of nodes to generate - `xmin`, `xmax`: the minimum and maximum values for the x-coordinate - `ymin`, `ymax`: the minimum and maximum value...
Write a Python function `flatten_paths` that takes a dictionary of paths and values and flattens it into a list of tuples, where each tuple consists of a single path string and its corresponding value. The path strings should be created by joining the dictionary's nested keys with a forward slash (/) separator. For exa...
For a given dictionary, recursively flatten all nested dictionaries to a single dictionary. For example, given `{'a': 1, 'b': {'c': 2, 'd': 3}}`, the output should be `{'a': 1, 'b.c': 2, 'b.d': 3}`.
Write a Python function `select_only_allowed` that takes two arguments: `iterable`, a list of tuples of strings and integers, and `allowed`, a list of integers. The function should iterate through the tuples in `iterable` and return a list of the elements in the second position of each tuple if they are allowed by the ...
Define a Python function that takes a string and an optional parameter `sep` with a default value of `' '`. If `sep` is provided, the function should return the string split by the separator, otherwise the function should return a list of individual characters in the string. Your code should pass the following asserti...
Write a function in Python to clip all the values below 0.5 in a given numpy array `a` to 0.5. The clipping operation should be element-wise and the output should be a numpy array with the same shape as `a`. Your code should pass the following test case: ```python a = np.array([0.2, 0.5, 0.7, 1.0]) b = clip_values(a) ...
Create a Python function that takes in a list of integers, sorts them in ascending order, and returns a new list containing the sorted elements. Write the docstring in the following format: ``` Parameters: num_list (list): A list of integers. Returns: list: A sorted list of integers, with the smallest element...
Create a Python function that takes two integers as input and returns their sum, difference, product, and quotient as a tuple. The function's signature should use type hints to indicate the expected types and return type. Your code should pass the following assertions: ```python assert arithmetic_operations(1, 2) == (...
I have a list of numbers like `[1, 2, 3, 4, 5, 6]`. I want to rotate the list to the left by 2 positions and return the new list. For example, `[1, 2, 3, 4, 5, 6]` rotated to the left by 2 positions becomes `[3, 4, 5, 6, 1, 2]`. Can you write a Python function to perform the left rotation?
Write a Python function `sum_nodes(node)` that takes the root of a tree as input and returns the sum of all node values. The tree is represented by a binary tree, where each node has a `val` attribute and a `left` and `right` child attribute. You may assume that the tree is a valid binary tree and does not contain any...
Write a python function `get_stop_words(filepath)` that takes a filepath to a file containing a list of stop words and returns a list of stop words. The file contains one stop word per line.
Write a Python function, `clean_text(text, stopwords)`, that takes two arguments: `text` (a string) and `stopwords` (a list of stopwords). The function should return a cleaned string without any stopwords. The stopwords should be removed from the string and the remaining words should be joined together with spaces.
Write a Python function `format_assignment_statement` that takes a string representing an assignment statement in Python, and adds a comment to the right-hand side of the statement. The comment should include the variable name, the value of the variable, and the type of the value. The function should not modify the ori...
Write a Python function to generate a random string of given length and with characters from a given set. If no set is provided, use the standard alphabet (uppercase and lowercase letters, digits, and punctuation). Your code should pass the following assertion: ```python assert len(random_string(100)) == 100 ```
Write a Python function that takes a list of JSON objects, each representing a user with a name, email, and a list of friends. The function should return a list of objects sorted by the number of friends, from the most friends to the least. Here's an example input and the expected output (formatted for readability): ...
Write a Python function to merge two dictionaries. The function should accept two dictionaries as arguments, and return a single merged dictionary. If any dictionary contains the same key, their values should be added together. If any dictionary contains a key that the other dictionary does not, the key should be added...
Write a Python function `has_substring(string1, string2)` that returns whether or not `string2` is a substring of `string1`. Additionally, if `string2` is a substring, include the line of code that performs the check. For example: ```python has_substring("apple", "ppl") ``` should return a boolean `True` and a strin...
Implement a function that takes a NumPy array and performs mixed precision training on it using PyTorch tensors. The function should first convert the NumPy array to a PyTorch tensor of mixed precision and perform matrix multiplication with the tensor. Then, it should divide the result by a scalar value (e.g., 2.0) and...
Write a Python function `get_random_seed` that takes a list of integers and returns a random integer between 0 and 99999. Use `random.seed` and `random.randint` to generate the random number.
Create a Python function to convert a nested list with specific patterns into a nested tuple. For instance, given the following input list: ```python input_list = [[1, 2, 3], [4, 5], [6, 7, 8, 9]] ``` The function should return a nested tuple as follows: ```python output_tuple = ((1, 2, 3), (4, 5), (6, 7, 8, 9)) ```
Write a Python function `convert_hex_to_dec` to convert an input string of hexadecimal numbers into a list of decimal numbers. The input string is a sequence of hexadecimal numbers separated by commas (','). Each hexadecimal number is between 0 and 255 (both inclusive), and the output list must have the same length as ...
Given a list of tuples `(index, value)` representing indexed values, create a dictionary such that for each unique value present in the list, a new entry is created in the dictionary, with the key being the unique value and the value a list of the indices corresponding to that value. For example, given the list `[(0, ...
Write a function that accepts two NumPy arrays, `a` and `b`, and performs element-wise multiplication. If the inputs are not NumPy arrays, raise an exception.
Create a Python function to update a dictionary with new keys and values. The function should take two parameters: the dictionary to be updated and a list of tuples, where each tuple contains a key and a value. The keys in the list should be checked against the dictionary's keys to see whether they already exist. If a ...
Write a Python function that takes an array of strings as input and returns a single string with the first letter of each string capitalized. Include documentation that describes the function, its parameters, and its return value. Be sure to use meaningful variable names, as well as a conditional expression to handle t...
Write a Python function that takes a string as input and returns the same string with a space inserted in every position. For example, given "abc", the function should return "a b c". Use string interpolation to achieve this result.
Write a Python function named `logistic` to compute the logistic function, given a value `x` and a parameter `a`. This function should return the result of the logistic function, which is defined as follows: $$ f(x) = \frac{1}{1 + e^{-x/a}} $$ The function should also include type hints and type annotations for the p...
Write a Python function that concatenates two strings. If one of the strings is `None` or empty, return the other string. Your code should pass the following assertions: ```python assert concatenate_strings(None, "World") == "World" assert concatenate_strings("Hello", None) == "Hello" assert concatenate_strings("Hello...
Write a Python function `is_int(s)` that takes a string `s` and returns `True` if `s` can be parsed as an integer, and `False` otherwise. Utilize exception handling to handle any potential errors and return `False` if an exception occurs. Your code should pass the following assertions: ```python assert is_int('123') i...
End of preview. Expand in Data Studio

No dataset card yet

Downloads last month
30