source stringclasses 6
values | id int64 0 111k | instruction stringlengths 167 4.39k | response stringlengths 244 6.1k |
|---|---|---|---|
magic_evol_110k | 74,802 | Write a Python function to generate and manipulate a Fibonacci sequence. The task involves implementing four functions:
1. **`fibonacci_sequence(n)`**: This function generates the Fibonacci sequence up to `n`.
2. **`fibonacci_sum(n)`**: This function calculates and returns the sum of the Fibonacci sequence up to `n`.
... | Here is the Python code to solve the given problem in the markdown block:
```python
def fibonacci_sequence(n):
"""Generate a Fibonacci sequence up to n.
Args:
n (int): The upper limit for the Fibonacci sequence.
Returns:
list: A list of Fibonacci numbers up to n.
"""
fib_sequence =... |
magic_evol_110k | 74,807 | Write a Python function to calculate the number of unique paths from the top-left corner to the bottom-right corner of an m x n grid, where you can only move right or down. The function should start with:
```python
from typing import List
def unique_paths(m: int, n: int) -> int:
```
| Here is the Python code to solve the given problem in the markdown block:
:
```python
from typing import List
def unique_paths(m: int, n: int) -> int:
"""
Calculate the number of unique paths from the top-left corner to the bottom-right corner of an m x n grid.
Args:
m (int): The number of row... |
magic_evol_110k | 74,809 | Write a Python function to determine the total number of non-repeating elements in a given 2D array. The function should take a 2D list of integers as input and return the count of unique elements present in the entire 2D array.
The code should start with:
```python
from typing import List
def count_unique_elements(a... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def count_unique_elements(arr: List[List[int]]) -> int:
"""
Counts the total number of non-repeating elements in a given 2D array.
Args:
arr (List[List[int]]): A 2D list of integers.
Re... |
magic_evol_110k | 74,822 | Write a Python function to calculate the least common multiple (LCM) of pairs of positive integers from two lists. The function should handle edge cases such as empty lists and lists of different lengths. The function should return a list of LCMs corresponding to each pair of integers from the input lists.
The code sh... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
from math import gcd
def lowest_common_multiple(x: List[int], y: List[int]) -> List[int]:
"""
Calculate the least common multiple (LCM) of each pair of positive integers from two lists.
Args:
... |
magic_evol_110k | 74,827 | Write a Python function to calculate and return the average of a given list of numbers. The function should handle lists of any length, including empty lists. If the list is empty, the function should return `None`. The code should start with:
```python
from typing import List, Optional
def calculate_average(numbers: ... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Optional
def calculate_average(numbers: List[int]) -> Optional[float]:
"""
Calculate the average of a given list of numbers.
Args:
numbers (List[int]): The list of numbers to calculate the ... |
magic_evol_110k | 74,849 | Write a Python function to calculate the smaller angle between the hour and minute hands of a clock given the `hour` and `minutes`. The function should handle edge cases such as when the hour is 12 or when the minutes are 60. The function should return the angle in degrees, ensuring the result is within `10^-5` of the ... | Here is the Python code to solve the given problem in the markdown block:
```python
def find_clock_angle(hour: int, minutes: int) -> float:
"""
Calculate the smaller angle between the hour and minute hands of a clock.
Args:
hour (int): The hour hand position (1 <= hour <= 12).
minutes (int)... |
magic_evol_110k | 74,854 | Write a Python function to count the occurrences of each unique alphabetical character (both upper-case and lower-case) in a given string and return the result as a dictionary. The function should be optimized for performance, especially when handling large volumes of textual data. The dictionary should map each charac... | Here is the Python code to solve the given problem in the markdown block:
```python
from collections import defaultdict
def count_character_occurrences(input_string: str) -> dict:
"""
Count the occurrences of each unique alphabetical character (both upper-case and lower-case) in the given string.
Args:
... |
magic_evol_110k | 74,855 | Write a Python function to identify variations of the phrase "an apple a day keeps the doctor away" where 1-3 words within the phrase may be replaced by synonyms. The function should use regular expressions to match the input phrase against all possible variations of the original phrase with synonyms.
The code should ... | Here is the Python code to solve the given problem in the markdown block:
```python
import re
from typing import List, Dict
def match_phrase_with_synonyms(input_phrase: str, synonyms: Dict[str, List[str]], original_phrase: str) -> bool:
"""
Identifies if the input phrase matches any variation of the original p... |
magic_evol_110k | 74,863 | Write a Python function to perform bitwise XOR operation on two binary strings and return the result as a binary string of the same length as the input strings. The function should handle binary strings of equal length.
The code should start with:
```python
from typing import List
def string_xor(a: str, b: str) -> st... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def string_xor(a: str, b: str) -> str:
"""
Perform bitwise XOR operation on two binary strings and return the result as a binary string of the same length.
Args:
a (str): The first binary st... |
magic_evol_110k | 74,878 | Write a Python function to determine if a given numerical input represents a perfect square by examining the decimal portion of its square root. The function should return `True` if the input is a perfect square and `False` otherwise. The code should start with:
```python
import math
def is_perfect_square(n: int) -> b... | Here is the Python code to solve the given problem in the markdown block:
```python
import math
def is_perfect_square(n: int) -> bool:
"""
Determine if a given integer n is a perfect square by examining the decimal portion of its square root.
Args:
n (int): The integer to check for being a perfect... |
magic_evol_110k | 74,882 | Write a Python function to generate a list of exactly four strings, where each string is a randomly generated alphanumeric string of length 5. The function should return this list.
The code should start with:
```python
from typing import List
import random
import string
def generate_random_string_list() -> List[str]:... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
import random
import string
def generate_random_string_list() -> List[str]:
"""
Generates a list of exactly four strings, where each string is a randomly generated alphanumeric string of length 5.
R... |
magic_evol_110k | 74,884 | Write a Python function to sort a list of integers using an optimized bubble sort algorithm. The function should allow sorting in both ascending and descending order. The function should start with:
```python
from typing import List
def optimized_bubble_sort(nums: List[int], order: str) -> List[int]:
```
| Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def optimized_bubble_sort(nums: List[int], order: str) -> List[int]:
"""
Sorts a list of integers using an optimized bubble sort algorithm.
Args:
nums (List[int]): The list of integers to be... |
magic_evol_110k | 74,886 | Write a Python function to sort a list that may contain nested lists, either in ascending or descending order based on a boolean parameter. The function should flatten any nested lists before sorting.
The code should start with:
```python
from typing import List, Union
def sort_nested_list(lst: List[Union[int, List[i... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Union
def flatten(lst: List[Union[int, List[int]]]) -> List[int]:
"""
Flattens a nested list of integers into a single list of integers.
Args:
lst (List[Union[int, List[int]]]): The nested ... |
magic_evol_110k | 74,912 | Write a Python function to find the first and last occurrence of a target value in a sorted list, as well as the number of occurrences of each unique value in the list. The list can consist of different data types, such as integers, floats, and strings. The function should handle cases where the target value does not e... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Union, Dict
def find_occurrences(lst: List[Union[int, float, str]], target: Union[int, float, str]) -> Union[Dict[str, Union[int, Dict[Union[int, float, str], int]]], str]:
"""
Finds the first and last ... |
magic_evol_110k | 74,918 | Write a Python function to transpose a given 2-dimensional array. The function should take a list of lists (representing a matrix) as input and return its transpose. The transpose of a matrix is obtained by swapping its rows with its columns. The code should start with:
```python
from typing import List
def transpose_... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def transpose_matrix(matrix: List[List[int]]) -> List[List[int]]:
"""
Transposes the given 2-dimensional array (matrix).
Args:
matrix (List[List[int]]): The input matrix to be transposed.
... |
magic_evol_110k | 74,922 | Write a Python function to generate all prime numbers within a specified range `[start, end]`. The function should return a list of prime numbers within this range. The function should be efficient and correctly identify prime numbers using logical or mathematical reasoning.
The code should start with:
```python
from ... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
import math
def generate_primes_in_range(start: int, end: int) -> List[int]:
"""
Generate a list of prime numbers within the specified range [start, end].
Args:
start (int): The starting val... |
magic_evol_110k | 74,929 | Write a Python function to generate a list of `n` random numbers within a specified range `[min_value, max_value]`. The function should return the list of random numbers. The code should start with:
```python
from typing import List
import random
def generate_random_numbers(n: int, min_value: int, max_value: int) -> L... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
import random
def generate_random_numbers(n: int, min_value: int, max_value: int) -> List[int]:
"""
Generates a list of `n` random numbers within the specified range `[min_value, max_value]`.
Args:
... |
magic_evol_110k | 74,939 | Write a Python function to identify all the even integers within a specified range defined by `min_num` and `max_num`. The function should return a list of even numbers within this range, inclusive of both `min_num` and `max_num`. The code should start with:
```python
from typing import List
def find_even_numbers(min_... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def find_even_numbers(min_num: int, max_num: int) -> List[int]:
"""
Returns a list of all even numbers within the specified range [min_num, max_num].
Args:
min_num (int): The lower bound of ... |
magic_evol_110k | 74,940 | Write a Python function to generate a dictionary that maps each unique character in a given string to its respective occurrence frequency. The function should handle any string input, including empty strings and strings with special characters. The code should start with:
```python
from typing import Dict
def characte... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Dict
def character_frequency(input_string: str) -> Dict[str, int]:
"""
Generates a dictionary with each unique character from the input string as keys
and their respective occurrence frequency as values.
... |
magic_evol_110k | 74,942 | Write a Python function to determine the square root of the smaller number between two given numbers. The function should handle cases where the numbers are equal and return the square root of either number in such cases. The function should also handle non-negative integers only.
The code should start with:
```python... | Here is the Python code to solve the given problem in the markdown block:
```python
import math
def square_root_of_smaller_number(num1: int, num2: int) -> float:
"""
Calculate the square root of the smaller number between two given non-negative integers.
Args:
num1 (int): The first non-negative in... |
magic_evol_110k | 74,957 | Write a Python function to find the keys that are common between two dictionaries. The function should return a list of keys from the second dictionary that also exist in the first dictionary. The code should start with:
```python
from typing import Dict, List
def find_common_keys(dict1: Dict[str, int], dict2: Dict[st... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Dict, List
def find_common_keys(dict1: Dict[str, int], dict2: Dict[str, int]) -> List[str]:
"""
Find the keys that are common between two dictionaries.
Args:
dict1 (Dict[str, int]): The first dic... |
magic_evol_110k | 74,959 | Write a Python function to perform a mutually one-to-one multiplication operation on two mutually exclusive rational integers. The function should take two integers as input and return their product. The function should also handle cases where the input integers are negative.
The code should start with:
```python
def ... | Here is the Python code to solve the given problem in the markdown block:
```python
def multiply_integers(num_1: int, num_2: int) -> int:
"""
Perform a mutually one-to-one multiplication operation on two mutually exclusive rational integers.
Args:
num_1 (int): The first integer.
num_2 (int)... |
magic_evol_110k | 74,964 | Write a Python function to iterate over the characters of a given string and return a list of tuples where each tuple contains the character and its index in the string. The function should handle strings of any length, including empty strings.
The code should start with:
```python
from typing import List, Tuple
def ... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Tuple
def character_index_pairs(s: str) -> List[Tuple[str, int]]:
"""
Returns a list of tuples where each tuple contains a character from the string and its index.
Args:
s (str): The input ... |
magic_evol_110k | 74,971 | Write a Python function to calculate the occurrence rate of each distinct word in a given English paragraph, considering case sensitivity. Additionally, the function should calculate the frequency of vowel and consonant occurrences in the entire paragraph. The function should return a dictionary of word frequencies, th... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Dict, Tuple
def count_frequencies(paragraph: str) -> Tuple[Dict[str, int], int, int]:
"""
Calculate the occurrence rate of each distinct word in the given paragraph,
considering case sensitivity. Addition... |
magic_evol_110k | 74,984 | Write a Python function to find the shared unique elements between two lists in ascending order, ensuring the function runs in O(n log n) time complexity. The function should handle exceptions for non-identical data types and empty entries. Do not use Python's built-in list functionalities for set operations or sorting... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Union
def merge_sort(arr: List[Union[int, str]]) -> List[Union[int, str]]:
"""
Custom merge sort implementation to sort the list in O(n log n) time.
Args:
arr (List[Union[int, str]]): The l... |
magic_evol_110k | 74,986 | Write a Python function to merge two alphanumeric strings character by character, forming a new string. If the input strings are not of the same length, the extra characters from the longer string should follow sequentially after the intertwined section. The function should start with:
```python
def merge_strings(str1:... | Here is the Python code to solve the given problem in the markdown block:
```python
def merge_strings(str1: str, str2: str) -> str:
"""
Merges two alphanumeric strings character by character.
Args:
str1 (str): The first alphanumeric string.
str2 (str): The second alphanumeric string.
R... |
magic_evol_110k | 74,991 | Write a Python function to filter and sort a list of greeting messages based on a given search term and sorting order. The function should return a list of filtered and sorted messages. The default greeting message should be "Hello World". The filter functionality should include a search bar where users can input text ... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Tuple
def filter_and_sort_greetings(messages: List[Tuple[str, str]], search_term: str = "", sort_order: str = "asc") -> List[Tuple[str, str]]:
"""
Filters and sorts a list of greeting messages based on ... |
magic_evol_110k | 75,004 | Write a Python function to reverse the order of words in a given string without using any built-in string manipulation methods or functions. The function should handle cases where multiple spaces exist between words and should return a string with single spaces between words, irrespective of the number of spaces in the... | Here is the Python code to solve the given problem in the markdown block:
```python
def reverse_order_of_words(s: str) -> str:
"""
Reverses the order of words in a given string without using any built-in string manipulation methods.
Handles multiple spaces between words and returns a string with single spac... |
magic_evol_110k | 75,006 | Write a Python function to replace occurrences of a pattern in a string with a specified replacement string, allowing for a maximum number of replacements. The function should use the `re.sub()` method and handle the `count` parameter to limit the number of substitutions.
The code should start with:
```python
import r... | Here is the Python code to solve the given problem in the markdown block:
```python
import re
def replace_with_limit(pattern: str, replace: str, string: str, count: int = 0) -> str:
"""
Replace occurrences of a pattern in a string with a specified replacement string,
allowing for a maximum number of replac... |
magic_evol_110k | 75,009 | Write a Python function to find the largest number in an unsorted array without using the built-in `max()` function. The function should iterate through the array and keep track of the largest number encountered.
The code should start with:
```python
from typing import List
def find_largest_number(arr: List[int]) -> ... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def find_largest_number(arr: List[int]) -> int:
"""
Find the largest number in an unsorted array.
Args:
arr (List[int]): The unsorted array of integers.
Returns:
int: The larges... |
magic_evol_110k | 75,015 | Write a Python function to implement a switch-case mechanism using a dictionary for processing a given input string. The function should map specific words in the input string to corresponding values defined in a dictionary. If a word in the input string is not found in the dictionary, it should be mapped to a default ... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def switch_case_mechanism(input_string: str, case_dict: dict) -> List[str]:
"""
Implements a switch-case mechanism using a dictionary to process a given input string.
Args:
input_string (str... |
magic_evol_110k | 75,040 | Write a Python function to find the most frequent item(s) in a given list. If there are multiple items with the same highest frequency, return all of them. If the list is empty, return `None`.
The code should start with:
```python
from typing import List, Union
from collections import Counter
def find_most_frequent_i... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Union
from collections import Counter
def find_most_frequent_items(lst: List[int]) -> Union[int, List[int], None]:
"""
Find the most frequent item(s) in a given list.
Args:
lst (List[int]):... |
magic_evol_110k | 75,064 | Write a Python function to generate a random sequence of unique numbers from 1 to 100. The sequence should be of a specified length `n`, where `n` is a positive integer not exceeding 100. If `n` is greater than 100, the function should return an empty list. The function should use Python's `random` module to ensure ran... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
import random
def generate_random_sequence(n: int) -> List[int]:
"""
Generates a random sequence of unique numbers from 1 to 100 of length n.
Args:
n (int): The length of the desired random ... |
magic_evol_110k | 75,089 | Write a Python function to find the character with the highest frequency in a given string. If there are multiple characters with the same highest frequency, return the one that appears first in the string. The function should be case-insensitive and should ignore non-alphabetic characters. The code should start with:
... | Here is the Python code to solve the given problem in the markdown block:
:
```python
def most_frequent_char(s: str) -> str:
"""
Find the character with the highest frequency in a given string.
If there are multiple characters with the same highest frequency,
return the one that appears first in the str... |
magic_evol_110k | 75,091 | Write a Python function `apply_to_each` that takes a lambda function and a list of elements as parameters. The function should apply the lambda function to each element in the list, handling any non-numeric inputs by printing an error message and skipping the element. The function should return the list of results afte... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Callable
def apply_to_each(function: Callable[[int], int], lst: List[int]) -> List[int]:
"""
Applies the given lambda function to each numeric element in the list and returns the result.
Non-numeric... |
magic_evol_110k | 75,094 | Write a Python function to translate a given set of individual specifics into a precisely articulated JavaScript Object Notation (JSON) structure. The specifics include the full legal name, biological epoch years, and gender identity. The function should return a dictionary that can be easily converted to JSON.
The co... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Dict
def translate_to_json(full_legal_name: str, biological_epoch_years: int, gender_identity: str) -> Dict[str, str]:
"""
Translates the supplied individual specifics into a precisely articulated JSON struct... |
magic_evol_110k | 75,098 | Write a Python function to determine the expected printed result based on the given integer values assigned to variables `a`, `b`, `c`, and `d`, and applying bitwise operators with nested conditional statements. The function should return the string "Yes", "No", or "Maybe" based on the evaluation of the conditions.
Th... | Here is the Python code to solve the given problem in the markdown block:
```python
def determine_result(a: int, b: int, c: int, d: int) -> str:
"""
Determine the expected printed result based on the given integer values and bitwise operations.
Args:
a (int): The first integer.
b (int): The... |
magic_evol_110k | 75,100 | Write a Python function to merge two given dictionaries. The dictionaries may contain lists as values. If both dictionaries have the same key, the values should be merged into a single list. If the values are not lists, they should be converted to lists before merging.
The code should start with:
```python
from typing... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Dict, Any
def merge_dictionaries(dict1: Dict[str, Any], dict2: Dict[str, Any]) -> Dict[str, Any]:
"""
Merge two dictionaries. If both dictionaries have the same key, the values are merged into a single list.
... |
magic_evol_110k | 75,101 | Write a Python function to calculate the product of all non-negative, even elements in a given list. The function should handle empty lists and negative numbers. The code should start with:
```python
from typing import List
def product_of_non_negative_evens(num_list: List[int]) -> int:
```
| Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def product_of_non_negative_evens(num_list: List[int]) -> int:
"""
Calculate the product of all non-negative, even elements in the given list.
Args:
num_list (List[int]): The list of integer... |
magic_evol_110k | 75,112 | Write a Python function to compute the sum of all elements in a multidimensional numpy array along different axes (rows, columns). Additionally, identify the row and column with the highest sum. Importantly, you should implement this without using numpy's built-in sum or max function. The function should start with:
``... | Here is the Python code to solve the given problem in the markdown block:
```python
import numpy as np
from typing import Tuple
def compute_sums_and_max_indices(arr: np.ndarray) -> Tuple[np.ndarray, np.ndarray, int, int]:
"""
Compute the sum of all elements in a multidimensional numpy array along rows and colu... |
magic_evol_110k | 75,122 | Write a Python function to find the index of the first occurrence of a target element in a list. If the target element is not found, return `None`. The function should be efficient and avoid unnecessary iterations.
The code should start with:
```python
from typing import List, Optional
def find_index(list_of_nums: Li... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Optional
def find_index(list_of_nums: List[int], target: int) -> Optional[int]:
"""
Find the index of the first occurrence of the target element in the list.
If the target element is not found, retu... |
magic_evol_110k | 75,132 | Write a Python function to check if a given string of parentheses is properly nested and matched. The string consists exclusively of parentheses characters ('(' and ')'). The function should return `True` if all parentheses are matched and nested correctly, and `False` otherwise. The code should start with:
```python
d... | Here is the Python code to solve the given problem in the markdown block:
```python
def is_properly_nested(brackets: str) -> bool:
"""
Check if the given string of parentheses is properly nested and matched.
Args:
brackets (str): The string consisting exclusively of parentheses characters ('(' and ... |
magic_evol_110k | 75,141 | Write a Python function to evaluate a mathematical expression while correctly handling the order of operations, division by zero, and complex number results. The function should return the result as a complex number, and if the result is a real number, it should be returned in a simplified form without the imaginary pa... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Union
import cmath
def evaluate_expression(expression: str) -> Union[complex, str]:
"""
Evaluates a mathematical expression while correctly handling the order of operations,
division by zero, and complex ... |
magic_evol_110k | 75,147 | Write a Python function to construct a dictionary with a specified structure. The dictionary should have keys 'a', 'b', and 'c', with corresponding values 1, 2, and 3 respectively. The function should return the constructed dictionary.
The code should start with:
```python
def construct_specified_dictionary() -> dict:... | Here is the Python code to solve the given problem in the markdown block:
```python
def construct_specified_dictionary() -> dict:
"""
Constructs a dictionary with the specified structure: {'a': 1, 'b': 2, 'c': 3}.
Returns:
dict: A dictionary with keys 'a', 'b', and 'c' and corresponding values 1, 2... |
magic_evol_110k | 75,158 | Write a Python function to find the last even number in a given list of integers. If no even number is found, the function should return a message indicating that no even number was found. The function should iterate through the list from left to right and handle cases where the list might be empty or contain no even n... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def find_last_even_number(numbers: List[int]) -> str:
"""
Finds the last even number in a given list of integers.
Args:
numbers (List[int]): The list of integers to search for the last even ... |
magic_evol_110k | 75,159 | Write a Python function to identify if a given string exists within a two-dimensional array of strings and return its index position coordinates (i, j). If the string is found more than once, the function should return all locations. The function should start with:
```python
from typing import List, Tuple
def find_str... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Tuple
def find_string_positions(arr: List[List[str]], x: str) -> List[Tuple[int, int]]:
"""
Identifies if a given string exists within a two-dimensional array of strings and returns its index position c... |
magic_evol_110k | 75,174 | Write a Python function called `convert_to_string` that takes a list of integers as input and returns the list as a string. Each integer in the list should be converted to its corresponding character based on ASCII values, and then each character should be shifted by a given shift value using a Caesar cipher. The funct... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def caesar_cipher(char: int, shift: int) -> str:
"""
Applies a Caesar cipher shift to a given character (as an integer).
Args:
char (int): The ASCII value of the character to be shifted.
... |
magic_evol_110k | 75,204 | Write a Python function to find and return the prime factors of a given integer `n`. The function should return a list of prime factors in ascending order. The code should start with:
```python
from typing import List
def prime_factors(n: int) -> List[int]:
```
| Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def prime_factors(n: int) -> List[int]:
"""
Returns the prime factors of a given integer `n` in ascending order.
Args:
n (int): The integer for which to find the prime factors.
Returns:... |
magic_evol_110k | 75,205 | Write a Python function to perform a mathematical computation that involves multiple operations (addition, subtraction, multiplication, and division) on a given set of numbers. The function should take a list of integers and a list of corresponding operations as input and return the final computed result. The operation... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def compute_result(numbers: List[int], operations: List[str]) -> int:
"""
Perform a sequence of mathematical operations on a list of numbers.
Args:
numbers (List[int]): A list of integers to... |
magic_evol_110k | 75,207 | Write a Python function to create an n x m matrix with all elements initialized to a specified value. The function should take three parameters: `n` (number of rows), `m` (number of columns), and `value` (the value to initialize all elements with). The function should return the created matrix.
The code should start w... | Here is the Python code to solve the given problem in the markdown block:
```python
import numpy as np
def create_matrix(n: int, m: int, value: float) -> np.ndarray:
"""
Create an n x m matrix with all elements initialized to the specified value.
Args:
n (int): The number of rows in the matrix.
... |
magic_evol_110k | 75,216 | Refactor the given Python code to remove redundant if-else statements and improve its time complexity without using any built-in Python functions. The original code checks the value of `x` and assigns a value to `result` based on the conditions. The refactored code should achieve the same functionality with fewer and m... | Here is the Python code to solve the given problem in the markdown block:
```python
def refactor_conditional(x: int) -> int:
"""
Refactor the given conditional logic to remove redundant checks and improve readability.
Args:
x (int): The input integer to evaluate.
Returns:
int: The resu... |
magic_evol_110k | 75,218 | Write a Python function to sort a given list of integers using the Merge Sort algorithm, ensuring that the time complexity is O(n log n). The function should be able to handle lists of any length, including empty lists and lists with a single element.
The code should start with:
```python
from typing import List
def ... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def merge_sort(arr: List[int]) -> List[int]:
"""
Sorts a list of integers using the Merge Sort algorithm.
Args:
arr (List[int]): The list of integers to be sorted.
Returns:
List... |
magic_evol_110k | 75,221 | Write a Python function to transform a given mathematical adjacency matrix of a simple undirected weighted graph into its corresponding adjacency list representation. The adjacency list should include the weights of the edges. The function should start with:
```python
from typing import List, Dict, Tuple
def adjacency... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Dict, Tuple
from collections import defaultdict
def adjacency_matrix_to_list(matrix: List[List[int]]) -> Dict[int, List[Tuple[int, int]]]:
"""
Transforms a given adjacency matrix of a simple undirected ... |
magic_evol_110k | 75,222 | Write a Python function to generate a new list where each string from a given list of strings is repeated according to the corresponding number in a given list of numbers. The function should handle cases where the lengths of the two input lists are not equal by truncating the longer list to match the length of the sho... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def repeat_strings(str_list: List[str], num_list: List[int]) -> List[str]:
"""
Generates a new list where each string from the given list of strings is repeated according to the corresponding number in t... |
magic_evol_110k | 75,225 | Write a Python function that calculates and returns the sum, difference, product, and quotient of two given numbers. The function should handle potential exceptions such as division by zero and should return appropriate error messages in such cases. The function should return a dictionary with keys "sum", "difference",... | Here is the Python code to solve the given problem in the markdown block:
```python
def calculate_operations(first_number: float, second_number: float) -> dict:
"""
Calculate the sum, difference, product, and quotient of two numbers.
Handle potential exceptions such as division by zero.
Args:
f... |
magic_evol_110k | 75,240 | Write a Python function to create a four-dimensional tensor from a given sequence of integer components. The tensor should be of size `2x2x2x2` and should be filled using nested loops. Avoid using built-in tensor manipulation functions or high-level libraries. The function should start with:
```python
from typing impor... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def create_4d_tensor(numbers: List[int]) -> List[List[List[List[int]]]]:
"""
Creates a four-dimensional tensor of size 2x2x2x2 from a given sequence of integer components.
Args:
numbers (Lis... |
magic_evol_110k | 75,249 | Write a Python function to create a dictionary from a given list of tuples, where the keys are the ASCII values of the characters in the tuples, and the values remain the same. The function should handle lists of tuples where each tuple contains exactly two elements: a character and an integer.
The code should start w... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Tuple
def map_tuples_to_ascii_dict(tuples: List[Tuple[str, int]]) -> dict:
"""
Creates a dictionary from a given list of tuples, where the keys are the ASCII values of the characters and the values rema... |
magic_evol_110k | 75,253 | Write a Python function to simulate the potential decrease in audio quality due to compression and data loss during file transfers. The function should take the original bit rate, audio length, and a compression factor as inputs. It should then compute the new bit rate after applying the compression factor and calculat... | Here is the Python code to solve the given problem in the markdown block:
```python
def simulate_audio_quality_loss(bit_rate: int, audio_length: int, compression_factor: float) -> tuple:
"""
Simulate the potential decrease in audio quality due to compression and data loss during file transfers.
Args:
... |
magic_evol_110k | 75,254 | Write a Python function to find the maximum number in a given list of integers. The function should handle an empty list by returning `None`. The code should start with:
```python
from typing import List, Optional
def find_max(nums: List[int]) -> Optional[int]:
```
| Here is the Python code to solve the given problem in the markdown block:
:
```python
from typing import List, Optional
def find_max(nums: List[int]) -> Optional[int]:
"""
Find the maximum number in a given list of integers.
Args:
nums (List[int]): The list of integers from which to find the maxim... |
magic_evol_110k | 75,261 | Write a Python function to find the top 5 most frequent characters in a given string. The function should return a list of tuples where each tuple contains a character and its frequency in descending order of frequency. If there are fewer than 5 unique characters, the function should return as many as are available.
T... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Tuple
from collections import Counter
def top_5_frequent_characters(s: str) -> List[Tuple[str, int]]:
"""
Find the top 5 most frequent characters in a given string.
Args:
s (str): The input... |
magic_evol_110k | 75,274 | Write a Python function to verify whether two multi-level nested lists containing string elements are identical, disregarding the sequence in which they occur at each level. The function should handle nested lists of arbitrary depth and ensure that the elements and sub-elements are the same, regardless of their order.
... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Union
def flatten_list(nested_list: List[Union[str, List]]) -> List[str]:
"""
Transform a multi-level nested list into a flat list of strings.
Args:
nested_list: A list containing strings o... |
magic_evol_110k | 75,277 | Write a Python function to reorder numerical elements in a given data array following an incremental sequence. The function should return the sorted list.
The code should start with:
```python
from typing import List
def reorder_incremental_sequence(data: List[int]) -> List[int]:
```
| Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def reorder_incremental_sequence(data: List[int]) -> List[int]:
"""
Reorders the numerical elements in the given data array following an incremental sequence.
Args:
data (List[int]): The dat... |
magic_evol_110k | 75,278 | Write a Python function to filter out empty tuples from a given list of tuples. The function should return a new list containing only the non-empty tuples. The code should start with:
```python
from typing import List, Tuple
def filter_empty_tuples(tuples_list: List[Tuple]) -> List[Tuple]:
```
| Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Tuple
def filter_empty_tuples(tuples_list: List[Tuple]) -> List[Tuple]:
"""
Filters out empty tuples from a given list of tuples.
Args:
tuples_list (List[Tuple]): A list of tuples, which ma... |
magic_evol_110k | 75,284 | Write a Python function to determine if a given string consists of ASCII printable characters only. ASCII printable characters are those that have a character code between 32 and 126, inclusive. The function should return `True` if all characters in the string are printable, and `False` otherwise.
The code should star... | Here is the Python code to solve the given problem in the markdown block:
```python
def is_string_printable(s: str) -> bool:
"""
Determines if a given string consists of ASCII printable characters only.
Args:
s (str): The string to be checked.
Returns:
bool: True if all characters in t... |
magic_evol_110k | 75,287 | Write a Python function to capitalize the first letter of a given string and make the rest of the letters lowercase. The function should handle strings of any length, including empty strings. The code should start with:
```python
def capitalize_first_letter(s: str) -> str:
```
| Here is the Python code to solve the given problem in the markdown block:
```python
def capitalize_first_letter(s: str) -> str:
"""
Capitalizes the first letter of the given string and makes the rest of the letters lowercase.
Args:
s (str): The input string to be processed.
Returns:
st... |
magic_evol_110k | 75,300 | Write a Python function to validate and format a list of choices for a Django model field. The function should ensure that each choice is a tuple of two elements, where the first element is the actual value and the second element is the human-readable name. If any choice does not meet this requirement, it should be exc... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Tuple
def format_choices(choices: List[Tuple[str, str]]) -> List[Tuple[str, str]]:
"""
Validates and formats a list of choices for a Django model field.
Args:
choices (List[Tuple[str, str]]... |
magic_evol_110k | 75,301 | Write a Python function to determine the most efficient sorting algorithm to use based on the size of the input array. The function should return the name of the sorting algorithm ("Quick Sort" or "Merge Sort") that is most efficient for the given array size. The efficiency is determined by the average time complexity ... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def most_efficient_sort(arr: List[int], threshold: int = 10) -> str:
"""
Determines the most efficient sorting algorithm to use based on the size of the input array.
Args:
arr (List[int]): T... |
magic_evol_110k | 75,328 | Write a Python function to find all the indices of the number 23 in a given unsorted array of integers. If the number 23 does not exist in the list, return "Number not found." The function should handle erroneous input and provide a useful error message when the input is not a list of integers. The function should have... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Union
def find_indices_of_23(arr: List[int]) -> Union[List[int], str]:
"""
Find all indices of the number 23 in a given unsorted array of integers.
Args:
arr (List[int]): The unsorted array... |
magic_evol_110k | 75,339 | Write a Python function to filter out a list of numbers and keep only those that are prime. The function should take a list of integers as input and return a list of integers containing only the prime numbers from the input list. The code should start with:
```python
from typing import List
def filter_primes(nums: Lis... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def is_prime(n: int) -> bool:
"""
Check if a given number is prime.
Args:
n (int): The number to check for primality.
Returns:
bool: True if the number is prime, False otherwise... |
magic_evol_110k | 75,343 | Write a Python function to compute the trimmed mean of a given collection of numerical data. The function should allow the user to specify a percentage of observations to be trimmed from both ends of the sorted data. If no trimming percentage is provided, the function should compute the regular mean. The function shoul... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Optional
def trimmed_mean(data: List[float], trim_percentage: Optional[float] = None) -> Optional[float]:
"""
Computes the trimmed mean of a given collection of numerical data.
Args:
data (... |
magic_evol_110k | 75,344 | Write a Python function to generate the Fibonacci series up to the Nth term. The function should handle input validation to ensure the input is a positive integer. Additionally, the function should be scalable to handle large values of N. The function should return a list containing the Fibonacci series up to the Nth t... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def generate_fibonacci_series(n: int) -> List[int]:
"""
Generate the Fibonacci series up to the Nth term.
Args:
n (int): The number of terms in the Fibonacci series to generate.
Returns... |
magic_evol_110k | 75,354 | Write a Python function to automate the creation of a multi-level directory structure within an already existing Unix directory structure. The desired directories should be specified as input parameters to the function, and the program should also handle relative and absolute pathnames. The function should account for ... | Here is the Python code to solve the given problem in the markdown block:
```python
import os
import logging
from pathlib import Path
def create_directory_structure(base_path: str, directories: list, user: str, group: str, mode: int = 0o755) -> None:
"""
Automates the creation of a multi-level directory struct... |
magic_evol_110k | 75,360 | Write a Python function to rearrange the elements of a given tuple in descending order. The function should take a tuple of integers as input and return a new tuple with the elements sorted in descending order. The original tuple should not be modified.
The code should start with:
```python
from typing import Tuple
d... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Tuple
def sort_tuple_descending(input_tuple: Tuple[int, ...]) -> Tuple[int, ...]:
"""
Sorts the elements of a given tuple in descending order.
Args:
input_tuple (Tuple[int, ...]): A tuple of inte... |
magic_evol_110k | 75,361 | Write a Python function to construct a dictionary where the keys are numbers starting from a given `start_number` and decrementing (or incrementing for negative numbers) until zero, and the values are the binary representations of these numbers. The function should handle both positive and negative `start_number` value... | Here is the Python code to solve the given problem in the markdown block:
```python
def binary_representation(start_number: int) -> dict:
"""
Constructs a dictionary where the keys are numbers starting from a given `start_number`
and decrementing (or incrementing for negative numbers) until zero, and the va... |
magic_evol_110k | 75,362 | Write a Python function to load all Python files from a specified directory as extensions into a bot object. The function should handle the loading of extensions without using `await`, as the bot object does not support asynchronous operations in this context. The function should also ensure that only `.py` files are l... | Here is the Python code to solve the given problem in the markdown block:
```python
import os
def load_extensions(bot, directory: str):
"""
Load all Python files from the specified directory as extensions into the bot object.
Args:
bot: The bot object that supports the load_extension method.
... |
magic_evol_110k | 75,369 | Write a Python function to merge two sorted lists into a new sorted list without using built-in sort functions. The merged list should maintain the original ascending order of the elements within each list. The function should start with:
```python
from typing import List
def merge_sorted_lists(list1: List[int], list2... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def merge_sorted_lists(list1: List[int], list2: List[int]) -> List[int]:
"""
Merges two sorted lists into a new sorted list without using built-in sort functions.
Args:
list1 (List[int]): Th... |
magic_evol_110k | 75,407 | Write two Python functions to perform the following tasks on an array of integers:
1. **Check for Duplicates**: Implement a function `has_no_duplicates` that returns `True` if the array does not contain any duplicates, and `False` if it does. This function should be implemented using loops and conditionals without usi... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Dict
def has_no_duplicates(arr: List[int]) -> bool:
"""
Check if the array contains any duplicates.
Args:
arr (List[int]): The array of integers to check for duplicates.
Returns:
... |
magic_evol_110k | 75,409 | Write a Python function to determine if a given undirected graph is a tree. The graph is represented by a 2D array `graph`, where `graph[u]` is an array of nodes that node `u` is adjacent to. The function should return `True` if the graph is a tree, and `False` otherwise.
The code should start with:
```python
from typ... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def is_graph_a_tree(graph: List[List[int]]) -> bool:
"""
Determines if the given undirected graph is a tree.
Args:
graph (List[List[int]]): A 2D list representing the adjacency list of the g... |
magic_evol_110k | 75,411 | Write a Python function to calculate the number of unique paths from the top-left corner to the bottom-right corner of an m x n grid, where you can only move right or down. The function should start with:
```python
from typing import List
def unique_paths(m: int, n: int) -> int:
```
| Here is the Python code to solve the given problem in the markdown block:
:
```python
from typing import List
def unique_paths(m: int, n: int) -> int:
"""
Calculate the number of unique paths from the top-left corner to the bottom-right corner of an m x n grid.
Args:
m (int): The number of row... |
magic_evol_110k | 75,413 | Write a Python function to sort a list of integers in ascending order using the `sorted()` function and return the sorted list. Additionally, write another function to sort the same list of integers in-place using the `sort()` method. The functions should handle lists of any length, including empty lists.
The code sho... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def sort_list_with_sorted(numbers: List[int]) -> List[int]:
"""
Sort a list of integers using the sorted() function and return the sorted list.
Args:
numbers (List[int]): The list of integer... |
magic_evol_110k | 75,416 | Write a Python function to find the common elements between two lists of strings, considering case sensitivity. If the elements are case-insensitive, they should be considered the same. The function should return a list of common elements in the same case as they appear in the first list.
The code should start with:
`... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def find_common_elements(list_1: List[str], list_2: List[str]) -> List[str]:
"""
Find common elements between two lists of strings, considering case insensitivity.
Args:
list_1 (List[str]): ... |
magic_evol_110k | 75,422 | Write a Python function to insert an element into a sorted list at a specified index while preserving the order of the remaining elements. The function should take three parameters: the list, the element to be inserted, and the index at which the element should be inserted. The function should return the modified list.... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def insert_element_at_index(sorted_list: List[int], element: int, index: int) -> List[int]:
"""
Inserts an element into a sorted list at a specified index while preserving the order of the remaining elem... |
magic_evol_110k | 75,423 | Write a Python function to determine the position of the first occurrence of a predetermined integer within a systematically organized array of positive integers. If the integer is not found in the array, the function should return -1. The function should handle arrays with duplicate elements and should be efficient in... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def find_first_occurrence(arr: List[int], target: int) -> int:
"""
Determine the position of the first occurrence of a predetermined integer within a systematically organized array of positive integers.
... |
magic_evol_110k | 75,425 | Write a Python function to transform a given phrase by converting it to lowercase, removing any special characters and numbers, and reversing the order of the words. The function should return the transformed phrase.
The code should start with:
```python
import re
def transform_phrase(phrase: str) -> str:
```
| Here is the Python code to solve the given problem in the markdown block:
```python
import re
def transform_phrase(phrase: str) -> str:
"""
Transforms the given phrase by converting it to lowercase, removing any special characters and numbers,
and reversing the order of the words.
Args:
phrase... |
magic_evol_110k | 75,431 | Write a Python function to identify the length of the most extensive sublist within a nested list structure and the index of the most extensive sublist. If multiple sublists share the longest length, the function should return the index of the earliest one.
The code should start with:
```python
from typing import List... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Tuple
def longest_sublist(lst: List[List[int]]) -> Tuple[int, int]:
"""
Identify the length of the most extensive sublist within a nested list structure and the index of the most extensive sublist.
... |
magic_evol_110k | 75,436 | Write a Python function to evaluate the total sum of a 2-dimensional list. The function should utilize nested loops while making sure to iteratively parse through each sub-list efficiently. The function should handle lists of varying dimensions and ensure that all elements are summed correctly.
The code should start w... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def sum_2d_list(arr: List[List[int]]) -> int:
"""
Calculate the total sum of all elements in a 2-dimensional list.
Args:
arr (List[List[int]]): A 2-dimensional list of integers.
Returns... |
magic_evol_110k | 75,440 | Write a Python function to calculate the mode of a list of floats. The mode is the value that appears most frequently in the list. If there are multiple values with the same highest frequency, the function should return all of them. The function should handle lists with a single mode, multiple modes, and an empty list.... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def calculate_mode(data: List[float]) -> List[float]:
"""
Calculate the mode(s) of a list of floats. The mode is the value(s) that appear most frequently in the list.
Args:
data (List[float]... |
magic_evol_110k | 75,451 | Write a Python function to sort the text strings in a mixed list of integers and strings, while keeping the integers in their original positions. The function should return a new list with the strings sorted lexicographically and the integers unchanged.
The code should start with:
```python
from typing import List, Un... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Union
def sort_mixed_list(mixed_list: List[Union[int, str]]) -> List[Union[int, str]]:
"""
Sorts the text strings in a mixed list of integers and strings, while keeping the integers in their original po... |
magic_evol_110k | 75,468 | Write a Python function to reverse the order of words in a given string. The function should handle strings with multiple spaces between words and leading/trailing spaces. The code should start with:
```python
def reverse_words_order(s: str) -> str:
```
| Here is the Python code to solve the given problem in the markdown block:
:
```python
def reverse_words_order(s: str) -> str:
"""
Reverses the order of words in a given string.
Args:
s (str): The input string containing words to be reversed.
Returns:
str: A string with the words in rev... |
magic_evol_110k | 75,474 | Write a Python function to merge two tuples element-by-element alternately. If the tuples are of unequal length, the remaining elements of the longer tuple should be appended to the end of the resulting tuple. The function should start with:
```python
def merge_tuples(tuple1: tuple, tuple2: tuple) -> tuple:
```
| Here is the Python code to solve the given problem in the markdown block:
```python
def merge_tuples(tuple1: tuple, tuple2: tuple) -> tuple:
"""
Merges two tuples element-by-element alternately. If the tuples are of unequal length,
the remaining elements of the longer tuple are appended to the end of the re... |
magic_evol_110k | 75,480 | Write a Python function to sort and return a list of prime even numbers from two input lists. The function should raise a `ValueError` if any negative number is present in the input lists. The returned list should be sorted in descending order.
The code should start with:
```python
from typing import List
def complex... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def complex_prime_sort(l1: List[int], l2: List[int]) -> List[int]:
"""
Sorts and returns a list of prime even numbers from two input lists.
Raises a ValueError if any negative number is present in th... |
magic_evol_110k | 75,487 | Write a Python function to find all the integers in a given array that have an uneven frequency, i.e., their frequency is not divisible by 2. The function should return these integers in the order they first appear in the array. The time complexity of the solution should be O(n), where n is the size of the input array.... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def find_uneven_frequencies(arr: List[int]) -> List[int]:
"""
Finds all integers in the given array that have an uneven frequency.
Args:
arr (List[int]): The array of integers to analyze.
... |
magic_evol_110k | 75,495 | Write a Python function to find the lowest common ancestor (LCA) of two nodes in a binary tree, given that each node has a reference to its parent node. Additionally, implement a function to check if the tree is a valid binary search tree (BST).
The code should start with:
```python
class Node:
def __init__(self, ... | Here is the Python code to solve the given problem in the markdown block:
```python
class Node:
def __init__(self, val, left=None, right=None, parent=None):
self.val = val
self.left = left
self.right = right
self.parent = parent
def lowest_common_ancestor(p: Node, q: Node) -> Node:
... |
magic_evol_110k | 75,496 | Write a Python function to count the frequency of each word in a given string and return the result as a dictionary where the keys are the distinct words and the values are their respective frequencies. The function should handle multiple spaces between words and leading/trailing spaces gracefully.
The code should sta... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Dict
def word_frequency(input_string: str) -> Dict[str, int]:
"""
Counts the frequency of each word in the given input string and returns a dictionary
where the keys are the distinct words and the values ... |
magic_evol_110k | 75,504 | Write a Python function to classify network connections based on their status (listening, established, etc.) and deduce the application/process responsible for each connection. The function should also identify and alert on suspicious connections, such as those from unrecognized IP addresses or unexpected high-traffic ... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Dict, Tuple
def classify_network_connections(connections: List[Tuple[str, str, str, str]], suspicious_ips: List[str], high_traffic_threshold: int) -> Dict[str, List[Tuple[str, str, str]]]:
"""
Classify ... |
magic_evol_110k | 75,508 | Write a Python function to compare two given text strings and determine if they have identical sets of distinct words. The function should return a tuple containing the count of distinct words in each string, the set of overlapping words, and the set of distinct words between both phrases.
The code should start with:
... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Tuple, Set
def compare_word_sets(phrase1: str, phrase2: str) -> Tuple[int, int, Set[str], Set[str]]:
"""
Compare two phrases and determine if they have identical sets of distinct words.
Return a tuple con... |
magic_evol_110k | 75,510 | Write a Python function to extract the integer part and the fractional part of a given floating-point number, with optional rounding based on specified methods. The function should return the integer part, the fractional part, and a boolean indicating whether the integer part is non-zero. The rounding methods include '... | Here is the Python code to solve the given problem in the markdown block:
```python
from decimal import Decimal, ROUND_HALF_UP, ROUND_HALF_EVEN, ROUND_HALF_DOWN
from typing import Union
def extract_integer(number: float, round: bool = True, precision: int = 2, method: str = 'traditional') -> Union[int, tuple]:
"""... |
magic_evol_110k | 75,513 | Write a Python function to safely divide two numbers and handle potential exceptions, such as division by zero. The function should return the result of the division if it is successful, and a custom error message if an exception occurs. The code should start with:
```python
def safe_division(numerator: float, denomina... | Here is the Python code to solve the given problem in the markdown block:
```python
def safe_division(numerator: float, denominator: float) -> float:
"""
Safely divides two numbers and returns the result. If a division by zero occurs,
a custom error message is returned.
Args:
numerator (float):... |
magic_evol_110k | 75,525 | Write a Python function to calculate the total number of words in a given sentence, considering various punctuation marks and multiple spaces between words. The function should handle sentences with punctuation marks (like commas, periods, question marks, etc.) and multiple spaces gracefully.
The code should start wit... | Here is the Python code to solve the given problem in the markdown block:
```python
def count_words(sentence: str) -> int:
"""
Calculate the total number of words in a given sentence, considering punctuation and multiple spaces.
Args:
sentence (str): The input sentence to count words from.
Ret... |
magic_evol_110k | 75,528 | Write a Python function to categorize customers based on their total purchases into three categories: high-value, mid-value, and low-value. The thresholds for each category should be provided as input parameters. The function should take a list of customers and their orders, and return a dictionary where the keys are t... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Dict, Tuple
def categorize_customers(customers: List[Tuple[str, str]], orders: List[Tuple[str, float]], high_threshold: float, mid_threshold: float) -> Dict[str, str]:
"""
Categorize customers into high... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.