source
stringclasses
6 values
id
int64
0
111k
instruction
stringlengths
167
4.39k
response
stringlengths
244
6.1k
magic_evol_110k
109,714
Write a Python function to transform an array of string elements into a structured dictionary where each key is a tuple representing the position of the element in the array (row, column) and the value is the element itself. The array is a 2D list (list of lists) of strings. The function should handle arrays of any siz...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Dict def array_to_structured_dict(array: List[List[str]]) -> Dict[tuple, str]: """ Transforms a 2D array of string elements into a structured dictionary. Each key in the dictionary is a tuple repres...
magic_evol_110k
109,733
Write a Python script that is executable on Unix-like systems and ensures compatibility with both Python 2.x and Python 3.x. The script should perform error handling to gracefully manage potential issues that might arise due to differences between the two Python versions. The script should also print a message indicati...
Here is the Python code to solve the given problem in the markdown block: ```python #!/usr/bin/env python import sys def main(): """ Main function to determine the Python version and handle potential errors. """ try: # Check the Python version if sys.version_info[0] < 3: # ...
magic_evol_110k
109,739
Write a Python function to determine if a given string contains both an exclamation mark "!" and a question mark "?" in any order. The function should use regular expressions to perform this check efficiently. The code should start with: ```python import re def has_exclamation_and_question(s: str) -> bool: ```
Here is the Python code to solve the given problem in the markdown block: ```python import re def has_exclamation_and_question(s: str) -> bool: """ Determines if a given string contains both an exclamation mark "!" and a question mark "?" in any order. Args: s (str): The string to be checked. ...
magic_evol_110k
109,756
Write a Python function to sort an unsorted list of integers in ascending order without using built-in sorting functions. Implement the Bubble Sort algorithm and provide a runtime analysis of your function, discussing its time complexity. The code should start with: ```python from typing import List def bubble_sort(n...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def bubble_sort(numbers: List[int]) -> List[int]: """ Sorts the given list of integers in ascending order using the Bubble Sort algorithm. Args: numbers (List[int]): The unsorted list of int...
magic_evol_110k
109,773
Write a Python function to identify the top n highest priced products within a provided dataset. The dataset is a list of dictionaries, where each dictionary represents a product with keys 'name' and 'price'. The function should return a list of the top n products sorted by price in descending order. If n is greater th...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Dict def get_top_n_products(products: List[Dict[str, any]], n: int) -> List[Dict[str, any]]: """ Returns the top n highest priced products from the given dataset. Args: products (List[Dict[...
magic_evol_110k
109,783
Write a Python function to determine if a given number is a prime number. The function should return `True` if the number is prime and `False` otherwise. If the input is not a number or less than 2, the function should raise a `ValueError`. The code should start with: ```python def is_prime(num: int) -> bool: ```
Here is the Python code to solve the given problem in the markdown block: ```python def is_prime(num: int) -> bool: """ Determines if a given number is a prime number. Args: num (int): The number to check for primality. Returns: bool: True if the number is prime, False otherwise. ...
magic_evol_110k
109,801
Write a Python function to find the maximum value in a list of numerical inputs. If the input is not a list, or if the list contains elements that are not numbers, the function should raise a `ValueError`. The function should start with: ```python from typing import List, Union def find_max_value(lst: List[Union[int, ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Union def find_max_value(lst: List[Union[int, float]]) -> Union[int, float]: """ Find the maximum value in a list of numerical inputs. Args: lst (List[Union[int, float]]): A list of numeric...
magic_evol_110k
109,802
Write a Python function to transform an input list into a multidimensional list whose cardinality is exactly twice as large, without modifying the core elements of the originating list. The function should handle nested lists recursively. The code should start with: ```python from typing import List, Any def expand_t...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Any def expand_twice(original_list: List[Any]) -> List[Any]: """ Transforms an input list into a multidimensional list whose cardinality is exactly twice as large, without modifying the core element...
magic_evol_110k
109,804
Write a Python function to filter out all elements from a given list that are divisible by two without a remainder. The function should return a new list containing only the even numbers from the original list. The code should start with: ```python from typing import List def filter_even_numbers(numbers: List[int]) -...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def filter_even_numbers(numbers: List[int]) -> List[int]: """ Filters out all elements from the given list that are divisible by two without a remainder. Args: numbers (List[int]): The list ...
magic_evol_110k
109,819
Write a Python function to extract the first `n` elements from a given list of integers. The function should handle cases where `n` is greater than the length of the list by returning the entire list. The function should also handle cases where `n` is less than or equal to zero by returning an empty list. The code shou...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def get_first_n_elements(arr: List[int], n: int) -> List[int]: """ Extracts the first n elements from the given list of integers. Args: arr (List[int]): The list of integers from which to ex...
magic_evol_110k
109,826
Write a Python function to find the maximum sum of a contiguous subarray within a given array of integers using Kadane's algorithm. The function should efficiently compute the maximum sum with a time complexity of O(n). The code should start with: ```python from typing import List def max_subarray_sum(arr: List[int])...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def max_subarray_sum(arr: List[int]) -> int: """ Calculate the maximum sum of a contiguous subarray within the given array using Kadane's algorithm. Args: arr (List[int]): The array of integ...
magic_evol_110k
109,834
Write a Python function to find the maximum value in a given list of numbers. The function should iterate through the list and keep track of the highest value encountered. The code should start with: ```python from typing import List def find_max_value(numbers: List[int]) -> int: ```
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def find_max_value(numbers: List[int]) -> int: """ Find the maximum value in a given list of numbers. Args: numbers (List[int]): A list of integers from which to find the maximum value. ...
magic_evol_110k
109,842
Write a Python function to convert a 2D sparse matrix into a dictionary format where the keys are tuples representing the coordinates of non-zero elements, and the values are the corresponding non-zero elements. The function should handle matrices of any size and efficiently store only the non-zero elements. The code ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Dict def sparse_matrix_to_dict(matrix: List[List[int]]) -> Dict[tuple, int]: """ Converts a 2D sparse matrix into a dictionary format where the keys are tuples representing the coordinates of non-ze...
magic_evol_110k
109,844
Write a Python function to calculate the average value of the elements in a given list of integers. The function should handle empty lists by returning `None` instead of attempting to divide by zero. The code should start with: ```python from typing import List, Optional def calculate_average(arr: List[int]) -> Option...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Optional def calculate_average(arr: List[int]) -> Optional[float]: """ Calculate the average value of the elements in the given list of integers. Args: arr (List[int]): The list of integers...
magic_evol_110k
109,846
Write a Python function to sort a given list of hexadecimal numbers in ascending order without using built-in sort methods. The list may contain both integers and characters representing hexadecimal digits ('A' to 'F'), where 'A' corresponds to 10, 'B' to 11, and so on up to 'F' which corresponds to 15. The function sh...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Union def sort_hex_list(hex_list: List[Union[int, str]]) -> List[Union[int, str]]: """ Sorts a list of hexadecimal numbers in ascending order without using built-in sort methods. Args: hex_...
magic_evol_110k
109,852
Write a Python function to calculate the sum of all even numbers between 1 and 50 and display the result. Additionally, find the smallest prime factor of each of these even numbers, if any, and display them as well. The function should return a dictionary where the keys are the even numbers and the values are their sma...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict def sum_of_even_numbers_and_prime_factors() -> Dict[int, int]: """ Calculate the sum of all even numbers between 1 and 50 and find the smallest prime factor of each even number. Returns: Dic...
magic_evol_110k
109,890
Write a Python function to find the second smallest value among four given integers. The function should be efficient and avoid sorting the list of integers. The code should start with: ```python def find_second_smallest(x1: int, x2: int, x3: int, x4: int) -> int: ```
Here is the Python code to solve the given problem in the markdown block: ```python def find_second_smallest(x1: int, x2: int, x3: int, x4: int) -> int: """ Finds the second smallest value among four given integers. Args: x1 (int): The first integer. x2 (int): The second integer. x3...
magic_evol_110k
109,899
Write a Python function to merge two lists such that all elements from the first list that are divisible by 3 are added to the second list, and the resulting list is sorted in ascending order. The function should handle edge cases such as empty lists and lists with no elements divisible by 3. The code should start wit...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def merge_lists_divisible_by_3(list1: List[int], list2: List[int]) -> List[int]: """ Merges two lists such that all elements from the first list that are divisible by 3 are added to the second list, ...
magic_evol_110k
109,901
Write a Python function to display a provided MxN dimensional 2D matrix in diagonal zigzag order. The function should handle matrices with variable row and column lengths, including edge cases where the matrix could have zero rows or columns. If the matrix contains only one row or one column, the function should print ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def diagonal_zigzag(matrix: List[List[int]]) -> List[int]: """ Display a provided MxN dimensional 2D matrix in diagonal zigzag order. Args: matrix (List[List[int]]): The 2D matrix to be disp...
magic_evol_110k
109,910
Write a Python function to find all prime numbers smaller than a given non-negative integer `n`. The function should return a list of prime numbers below `n`. The function should be efficient and handle edge cases such as `n` being 0 or 1. The code should start with: ```python from typing import List def find_primes_...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List import math def find_primes_below(n: int) -> List[int]: """ Find all prime numbers smaller than a given non-negative integer `n`. Args: n (int): The upper limit (exclusive) for finding prime...
magic_evol_110k
109,911
Write a Python function to sort a given alphanumeric dataset in lexicographical order using the Quick Sort algorithm. The dataset is a list of strings that may contain both alphabetic and numeric characters. The function should handle the sorting efficiently and return the sorted list. The code should start with: ```p...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def quick_sort_lexicographical(arr: List[str]) -> List[str]: """ Sorts a given alphanumeric dataset in lexicographical order using the Quick Sort algorithm. Args: arr (List[str]): The datase...
magic_evol_110k
109,916
Write a Python function to remove duplicate dictionaries from a list based on a comparison with a given dictionary. The uniqueness of each dictionary in the list should be determined by checking if the dictionary's `Name` and `Lastname` keys match the corresponding entries in the dictionary. The function should return ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Dict def remove_duplicates_based_on_dict(list_of_dicts: List[Dict[str, str]], dict_of_names: Dict[str, str]) -> List[Dict[str, str]]: """ Removes duplicate dictionaries from a list based on a comparison...
magic_evol_110k
109,918
Write a Python function to filter values from a list `sol1` based on the corresponding boolean values in another list `cond1`. Specifically, the function should return a list of values from `sol1` where the corresponding value in `cond1` is `False`. The code should start with: ```python from typing import List def fi...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def filter_values(sol1: List[int], cond1: List[bool]) -> List[int]: """ Filters values from `sol1` based on the corresponding boolean values in `cond1`. Args: sol1 (List[int]): The list of i...
magic_evol_110k
109,919
Write a Python function to rearrange a given array such that the highest number is first, followed by the lowest, then the second highest, the second lowest, and so on. The function should handle arrays of any length, including odd and even lengths. The code should start with: ```python from typing import List def re...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def rearrange_array(input_array: List[int]) -> List[int]: """ Rearranges the given array such that the highest number is first, followed by the lowest, then the second highest, the second lowest, an...
magic_evol_110k
109,922
Write a Python function to create a 4D array of a specified size where every element corresponds to a given value. The function should take two arguments: the dimensions of the 4D array and the value to fill the array with. The code should start with: ```python from typing import List import numpy as np def create_4d_...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List import numpy as np def create_4d_array(dimensions: List[int], fill_value: int) -> np.ndarray: """ Create a 4D array of the specified dimensions and fill it with the given value. Args: dimens...
magic_evol_110k
109,931
Write a Python function to generate a random list of numbers from 0 to 10, ensuring no duplicates. Additionally, provide a piece of erroneous code that attempts to solve this problem and identify the mistakes in it. The function should start with: ```python from typing import List def generate_unique_random_numbers() ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List import random def generate_unique_random_numbers() -> List[int]: """ Generates a list of unique random numbers from 0 to 10. Returns: List[int]: A list containing unique random numbers from ...
magic_evol_110k
109,936
Write a Python function to transform a string containing multiple person profiles into a dictionary. Each profile is separated by a semi-colon (`;`), and each profile's details are separated by a comma and a space (`, `). The profiles should be transformed into a dictionary where the person's name is the key, and the v...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict def transform_profiles_to_dict(input_string: str) -> Dict[str, Dict[str, str]]: """ Transforms a string containing multiple person profiles into a dictionary. Args: input_string (str): A str...
magic_evol_110k
109,984
Write a Python function that performs the following tasks: 1. Print the numbers from 1 to 10 on a single line, but replace any even number with its corresponding Roman numeral counterpart. 2. Calculate the sum of all prime numbers in the range from 1 to 10 and print it. 3. Print the even numbers from the range in rever...
Here is the Python code to solve the given problem in the markdown block: ```python def is_prime(n): """Check if a number is a prime number""" if n <= 1: return False elif n <= 3: return True elif n % 2 == 0 or n % 3 == 0: return False i = 5 while i * i <= n: if n...
magic_evol_110k
109,994
Write a Python function to update the value of an existing key in a dictionary. If the key does not exist in the dictionary, the function should add the key-value pair to the dictionary. The function should return the updated dictionary. The code should start with: ```python from typing import Dict, Any def update_or...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict, Any def update_or_add_entry(mydict: Dict[str, Any], key: str, new_value: Any) -> Dict[str, Any]: """ Updates the value of an existing key in the dictionary or adds a new key-value pair if the key does n...
magic_evol_110k
109,997
Write a Python function to find and return the pricing plan with the highest price from a given list of pricing plans. The function should handle cases where the list is empty, the price key is missing, or the price value is `None`. The function should return `None` if no valid pricing plan is found. The code should s...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Dict, Optional def get_highest_price_plan(plans: List[Dict[str, Optional[int]]]) -> Optional[str]: """ Find and return the pricing plan with the highest price from a given list of pricing plans. Ar...
magic_evol_110k
110,014
Write a Python function to perform the bubble sort algorithm on a given list of integers. The function should repeatedly step through the list, compare adjacent elements, and swap them if they are in the wrong order. The process should be repeated until the list is sorted. The function should return the sorted list. T...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def bubble_sort(arr: List[int]) -> List[int]: """ Sorts a list of integers using the bubble sort algorithm. Args: arr (List[int]): The list of integers to be sorted. Returns: Li...
magic_evol_110k
110,021
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
110,073
Write a Python function to calculate the number of unique diagonal elements in a provided square matrix. The function should also handle potential errors due to non-square matrices or non-integer data types within the matrix by raising custom exceptions with descriptive messages. The function should start with: ```pyth...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def count_unique_diagonal_elements(matrix: List[List[int]]) -> int: """ Calculate the number of unique diagonal elements in a provided square matrix. Args: matrix (List[List[int]]): A square...
magic_evol_110k
110,078
Write a Python function to sort a list of numerical values in ascending order using the merge sort algorithm. The function should be efficient and should handle lists of varying sizes. The code should start with: ```python from typing import List def merge_sort(input_list: List[int]) -> List[int]: ```
Here is the Python code to solve the given problem in the markdown block: : ```python from typing import List def merge_sort(input_list: List[int]) -> List[int]: """ Sorts a list of numerical values in ascending order using the merge sort algorithm. Args: input_list (List[int]): The list of numeri...
magic_evol_110k
110,080
Write a Python function to extract the information of the second item from a given dictionary. The dictionary contains multiple items, each represented as a nested dictionary with keys "name", "age", and "city". The function should return the nested dictionary corresponding to the "second" item. The code should start ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict def extract_second_item(data: Dict[str, Dict[str, str]]) -> Dict[str, str]: """ Extracts the information of the second item from a given dictionary. Args: data (Dict[str, Dict[str, str]]): A...
magic_evol_110k
110,101
Write a Python function to calculate the number of contractions for a given integer \( m \) using the family of functions \( g_{m,c,d}(y) \equiv c y + d \mod m \) for \( c, d, y \) integers and \( 0 < c < m, 0 \le d < m, 0 \le y < m \). A function \( g_{m,c,d} \) is called a contraction if \( g_{m,c,d}(g_{m,c,d}(y)) \e...
Here is the Python code to solve the given problem in the markdown block: ```python def count_contractions(m: int) -> int: """ Calculate the number of contractions for a given integer m. A function g_{m,c,d}(y) is defined as g_{m,c,d}(y) ≡ c*y + d (mod m) for 0 < c < m, 0 ≤ d < m, 0 ≤ y < m. A function...
magic_evol_110k
110,103
Write a Python function to find the sum of the maximum subarray and also return the start and end indices of that subarray from a given array. The function should solve the problem in O(n) time complexity and O(1) space complexity. The code should start with: ```python from typing import List, Tuple def max_subarray_s...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Tuple def max_subarray_sum(nums: List[int]) -> Tuple[int, int, int]: """ Find the sum of the maximum subarray and also return the start and end indices of that subarray. Args: nums (List[in...
magic_evol_110k
110,113
Write a Python function to remove all spaces from a given string. The function should handle strings of varying lengths, including empty strings. The code should start with: ```python def remove_spaces(string: str) -> str: ```
Here is the Python code to solve the given problem in the markdown block: ```python def remove_spaces(string: str) -> str: """ Removes all spaces from the given string. Args: string (str): The input string from which spaces are to be removed. Returns: str: The input string with all spa...
magic_evol_110k
110,148
Write a Python function to find the length of the longest substring that contains at most `k` distinct characters in a given string `s`. The function should efficiently handle the constraints provided. The code should start with: ```python def longest_substring_with_k_distinct_chars(s: str, k: int) -> int: ```
Here is the Python code to solve the given problem in the markdown block: ```python def longest_substring_with_k_distinct_chars(s: str, k: int) -> int: """ Find the length of the longest substring that contains at most `k` distinct characters. Args: s (str): The input string. k (int): The m...
magic_evol_110k
110,177
Write a Python function to find the longest substring without repeating characters in a given string. The function should return the longest substring containing no repeated characters. The code should start with: ```python def longest_substring_without_repeating_characters(s: str) -> str: ```
Here is the Python code to solve the given problem in the markdown block: ```python def longest_substring_without_repeating_characters(s: str) -> str: """ Finds the longest substring without repeating characters in the given string. Args: s (str): The input string to search for the longest substrin...
magic_evol_110k
110,182
Write a Python function to sort a list of decimal numbers in ascending order. The function should take a list of decimal numbers as input and return the sorted list. The sorting should be done in-place to avoid unnecessary memory usage. The code should start with: ```python from typing import List def sort_decimals(v...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def sort_decimals(values: List[float]) -> None: """ Sorts a list of decimal numbers in ascending order in-place. Args: values (List[float]): The list of decimal numbers to be sorted. Re...
magic_evol_110k
110,184
Write a Python function to analyze a given integer and return three tuples: 1. The first tuple contains the count of even and odd digits. 2. The second tuple contains the sum of even and odd digits. 3. The third tuple contains the largest and smallest digits among the even and odd digits. The function should start wit...
Here is the Python code to solve the given problem in the markdown block: ```python def even_odd_count(num: int) -> tuple: """ Analyze a given integer and return three tuples: 1. The count of even and odd digits. 2. The sum of even and odd digits. 3. The largest and smallest digits among the even an...
magic_evol_110k
110,202
Write a Python function to find the two elements in a list of real numbers that have the maximum spatial distance between them, ensuring that the elements are returned in ascending order. The function should handle lists with a minimum length of two. The code should start with: ```python from typing import List, Tuple ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Tuple def find_furthest_elements(numbers: List[float]) -> Tuple[float, float]: """ Find the two elements in the list that have the maximum spatial distance between them, and return them in ascending...
magic_evol_110k
110,207
Write a Python function to debug and correct an erroneous Binary Search Algorithm. The function should return the index of the search number if it is present in the sorted list, otherwise it should return -1. The erroneous code provided has logical errors that need to be identified and corrected. The code should start...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def binary_search(data: List[int], search_num: int) -> int: """ Perform a binary search on a sorted list to find the index of the search number. Args: data (List[int]): A sorted list of inte...
magic_evol_110k
110,209
Write a Python function `is_prime_with_divisors(n)` that verifies if a given number `n` is prime. If `n` is not prime, the function should return a tuple where the first element is `False` and the second element is a list of all divisors of `n` excluding `1` and `n` itself. If `n` is prime, the function should return a...
Here is the Python code to solve the given problem in the markdown block: ```python def is_prime_with_divisors(n: int) -> tuple: """ Determines if a given number `n` is prime. If `n` is not prime, returns a list of its divisors excluding 1 and `n` itself. Args: n (int): The number to check for prim...
magic_evol_110k
110,212
Write a Python function to calculate the sum of array elements and the sum of their squares, while handling non-numeric elements gracefully. The function should skip non-numeric elements and print a message indicating which elements were excluded. The code should start with: ```python from typing import List def sum_o...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def sum_of_elements_and_squares(arr: List[int]) -> (int, int): """ Calculate the sum of array elements and the sum of their squares, skipping non-numeric elements. Args: arr (List[int]): The...
magic_evol_110k
110,215
Write a Python function to generate a random n x m matrix using Numpy. The function should take two integers, `n` and `m`, as input and return a 2D Numpy array (matrix) of size n x m filled with random floating-point numbers between 0 and 1. The code should start with: ```python import numpy as np def generate_random...
Here is the Python code to solve the given problem in the markdown block: ```python import numpy as np def generate_random_matrix(n: int, m: int) -> np.ndarray: """ Generate a random n x m matrix filled with floating-point numbers between 0 and 1. Args: n (int): The number of rows in the matrix. ...
magic_evol_110k
110,223
Write a Python function to identify and return the numbers that occur more than once in a given list of integers. The function should return a list of these duplicate numbers, sorted in ascending order. The code should start with: ```python from typing import List def find_duplicates(my_list: List[int]) -> List[int]:...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def find_duplicates(my_list: List[int]) -> List[int]: """ Identify and return the numbers that occur more than once in the given list of integers. Args: my_list (List[int]): The list of inte...
magic_evol_110k
110,235
Write a Python function to transpose the keys and values of a given dictionary. The function should return a new dictionary where the keys are the values from the original dictionary, and the values are the corresponding keys from the original dictionary. The code should start with: ```python from typing import Dict d...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict def transpose_dictionary(original_dict: Dict[str, int]) -> Dict[int, str]: """ Transposes the keys and values of a given dictionary. Args: original_dict (Dict[str, int]): The original dictio...
magic_evol_110k
110,237
Write a Python function to efficiently search for a target number in a given list of integers. The function should return `True` if the target number is found in the list, and `False` otherwise. The function should use an appropriate data structure to optimize the search operation. The code should start with: ```pytho...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def fast_search(num_list: List[int], target: int) -> bool: """ Efficiently searches for a target number in a given list of integers. Args: num_list (List[int]): The list of integers to searc...
magic_evol_110k
110,238
Write a Python function to find the median of a list of integers. The input list may contain unsorted elements and duplicates. The function should first sort the list and then calculate the median. The solution should have a time complexity of O(n log n) due to sorting and should not use any built-in functions or libra...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Optional def find_median(input_list: List[int]) -> Optional[float]: """ Find the median of a list of integers. Args: input_list (List[int]): The list of integers to find the median of. ...
magic_evol_110k
110,243
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 code 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
110,263
Write a Python function to calculate the sum of elements in a given array of numerical values while handling potential edge cases. The function should ensure that all elements in the array are either integers or floats. If any element is not a number, the function should raise an `AssertionError` with a descriptive mes...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def calculate_sum(array: List[int]) -> float: """ Calculate the sum of elements in a given array of numerical values. Args: array (List[int]): The array of numerical values to sum. Retu...
magic_evol_110k
110,280
Write a Python function to determine if a given string is a five-letter palindrome. The function should ensure that the input string is exactly five characters long, consists only of alphabetic characters, and is a palindrome (reads the same forwards and backwards). The function should be case-insensitive. The code sh...
Here is the Python code to solve the given problem in the markdown block: ```python def is_five_letter_palindrome(word: str) -> bool: """ Determines if a given string is a five-letter palindrome. Args: word (str): The input string to be checked. Returns: bool: True if the string is a f...
magic_evol_110k
110,288
Write a Python function to find all occurrences of the tokens "start", "end", and "here" in a given text using a regular expression. The function should return a list of all matched tokens in the order they appear in the text. The code should start with: ```python import re from typing import List def find_tokens(tex...
Here is the Python code to solve the given problem in the markdown block: ```python import re from typing import List def find_tokens(text: str) -> List[str]: """ Find all occurrences of the tokens "start", "end", and "here" in the given text. Args: text (str): The text in which to search for the ...
magic_evol_110k
110,298
Write a Python function to convert a given list of integers into a dictionary where each key is an integer from the list and the value is a list of the square roots of all non-negative integers less than that integer. Use dictionary comprehension for this task. The function should handle both positive and negative inte...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Dict import math def convert_to_dict(my_list: List[int]) -> Dict[int, List[float]]: """ Converts a given list of integers into a dictionary where each key is an integer from the list and the value i...
magic_evol_110k
110,303
Write a Python function that takes in a list of strings and a number `n`. The function should return a new list containing tuples of strings from the original list that are longer than `n` characters, along with their respective indices in the original list. The function should handle edge cases such as an empty list o...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Tuple def filter_strings_with_indices(lst: List[str], n: int) -> List[Tuple[str, int]]: """ Filters strings from the given list that are longer than `n` characters and returns a list of tuples containin...
magic_evol_110k
110,312
Write a Python function to format a given string as a URL slug. The function should validate and clean the input string to remove any non-alphanumeric and special characters before conversion. The input string can be up to 500 characters long. The function should also ensure that the resulting slug does not exceed a sp...
Here is the Python code to solve the given problem in the markdown block: ```python import re def format_as_url_slug(text: str, max_length: int = 50) -> str: """ Formats a given string as a URL slug, ensuring it is cleaned of non-alphanumeric characters and does not exceed a specified maximum length. Args...
magic_evol_110k
110,317
Write a Python function to sort a list of integers using the Merge Sort algorithm, which has a time complexity of O(n log n). The function should be optimized for performance and should handle edge cases such as empty lists and single-element lists. The code should start with: ```python from typing import List def me...
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
110,318
Write a Python function that takes in two parameters: a string `s` and an integer `n`. The function should return a new string where each character in the original string `s` is repeated `n` times. Additionally, the function should print the number of vowels in the new string. The function should start with: ```python ...
Here is the Python code to solve the given problem in the markdown block: ```python def repeat_characters_and_count_vowels(s: str, n: int) -> str: """ Repeats each character in the string `s` `n` times and counts the number of vowels in the resulting string. Args: s (str): The original string. ...
magic_evol_110k
110,325
Write a Python function to check if one set is a subset of another without using Python's built-in set methods. The function should be efficient and correctly determine if every element in the first set is present in the second set. The function should return `True` if the first set is a subset of the second and `False...
Here is the Python code to solve the given problem in the markdown block: ```python def is_subset(s1: set, s2: set) -> bool: """ Check if the first set `s1` is a subset of the second set `s2` without using Python's built-in set methods. Args: s1 (set): The first set to check. s2 (set): The ...
magic_evol_110k
110,353
Write a Python function to find and print all elements in a list that are divisible by any subsequent element in the list. The function should take a list of integers as input and print each element that meets the condition. The function should also analyze and print the time complexity of the given program and propose...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def find_divisible_elements(my_list: List[int]) -> None: """ Finds and prints all elements in the list that are divisible by any subsequent element. Args: my_list (List[int]): The list of in...
magic_evol_110k
110,363
Write a Python function to calculate the arithmetic mean of a given array of integers using the `numpy` library. Additionally, return the data type of the mean. The function should start with: ```python from typing import List, Tuple import numpy as np def calculate_mean_and_type(arr: List[int]) -> Tuple[float, type]:...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Tuple import numpy as np def calculate_mean_and_type(arr: List[int]) -> Tuple[float, type]: """ Calculate the arithmetic mean of a given array of integers and return the mean along with its data type. ...
magic_evol_110k
110,379
Write a Python function to calculate the product of the first n natural numbers using a while loop. The function should handle edge cases such as n being zero or negative, and ensure that the product is calculated correctly. The code should start with: ```python def product_of_first_n_natural_numbers(n: int) -> int: ``...
Here is the Python code to solve the given problem in the markdown block: ```python def product_of_first_n_natural_numbers(n: int) -> int: """ Calculate the product of the first n natural numbers. Args: n (int): The number of natural numbers to include in the product. Returns: int: The...
magic_evol_110k
110,386
Write a Python function that returns the distinct elements that appear in both input lists, sorted in ascending order. The function should avoid using Python's built-in list functions to sort the result and remove duplicates. The function should start with: ```python from typing import List def shared_elements(list1: ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def shared_elements(list1: List[int], list2: List[int]) -> List[int]: """ Return a sorted list of unique elements that are present in both input lists without using Python's built-in list functions. ...
magic_evol_110k
110,409
Write a Python function to compute the volume of a four-dimensional hypercube (tesseract) given its side length. The function should not use built-in power or multiplication functions. Instead, it should implement custom methods for multiplication and exponentiation. The code should start with: ```python def tesseract...
Here is the Python code to solve the given problem in the markdown block: ```python def multiply(x: int, y: int) -> int: """ Custom multiplication function that multiplies two integers using repeated addition. Args: x (int): The first integer. y (int): The second integer. Returns: ...
magic_evol_110k
110,423
Write a Python function to determine the minimum number of non-overlapping intervals needed to cover the entire range of a given set of intervals. The function should handle edge cases such as intervals with similar start or end points. The code should start with: ```python from typing import List def min_non_overlapp...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def min_non_overlapping_intervals(intervals: List[List[int]]) -> int: """ Determine the minimum number of non-overlapping intervals needed to cover the entire range of a given set of intervals. Args...
magic_evol_110k
110,443
Write a Python function to generate a cookie string based on the provided parameters. The function should include methods to set the name, value, max age, path, and flags for HttpOnly and Secure. The function should follow the HTTP state management mechanism as per RFC 6265. The code should start with: ```python def g...
Here is the Python code to solve the given problem in the markdown block: ```python def generate_cookie(name: str, value: str, max_age: int = None, path: str = None, secure: bool = False, http_only: bool = False) -> str: """ Generates a cookie string based on the provided parameters. Args: name (st...
magic_evol_110k
110,467
Refactor the given Python code to eliminate redundancy and improve readability. The original code creates a dictionary `allSubjects` where each key is a string representation of a number from 0 to 4, and each value is a dictionary `subjectData`. The code then creates another dictionary `addedSubjects` using a dictionar...
Here is the Python code to solve the given problem in the markdown block: ```python def create_subject_data(subject_data: dict, num_subjects: int) -> dict: """ Creates a dictionary of subject data for a specified number of subjects. Args: subject_data (dict): A dictionary containing details about a...
magic_evol_110k
110,472
Write a Python function to create and return a dictionary containing personal information. The dictionary should have three keys: "Name", "Address", and "Phone". The function should accept three parameters corresponding to the values for these keys. The code should start with: ```python def create_personal_info(name: ...
Here is the Python code to solve the given problem in the markdown block: ```python def create_personal_info(name: str, address: str, phone: str) -> dict: """ Creates and returns a dictionary containing personal information. Args: name (str): The name of the person. address (str): The addre...
magic_evol_110k
110,475
Write a Python function to simulate the behavior of JavaScript's `for...in` loop, which iterates over all enumerable properties of an object, including those inherited via its prototype chain. The function should take a dictionary representing an object and a list of dictionaries representing its prototype chain. The f...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict, List, Tuple def traverse_object_properties(obj: Dict, prototype_chain: List[Dict]) -> List[Tuple[str, any]]: """ Simulate the behavior of JavaScript's `for...in` loop to traverse all enumerable properti...
magic_evol_110k
110,486
Write a Python function to generate all possible combinations of a specified number of letters from a given array of letters. The function should return a list of strings, where each string is a unique combination of the specified number of letters. The code should start with: ```python from typing import List from it...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List from itertools import combinations def generate_combinations(letters: List[str], num: int) -> List[str]: """ Generate all possible combinations of a specified number of letters from a given array of lett...
magic_evol_110k
110,488
Write a Python function to filter and sort a list of integers, returning only the positive numbers in ascending order. The function should be compatible with the given JavaScript code snippet and should include detailed comments to help understand the translation process. 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 get_positive_numbers(l: List[int]) -> List[int]: """ Filters and sorts a list of integers, returning only the positive numbers in ascending order. Args: l (List[int]): The list of intege...
magic_evol_110k
110,490
Write a Python function to count the occurrences of each character in a given list of characters within a provided string. The string can contain all ASCII characters and can be as long as 1,000,000 characters. The function should be memory efficient. The code should start with: ```python from typing import List, Dict...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Dict def count_character_occurrences(char_list: List[str], string: str) -> Dict[str, int]: """ Counts the occurrences of each character in the given list within the provided string. Args: c...
magic_evol_110k
110,506
Write a Python function to calculate the surface area of a right-angled triangular prism given the base, height of the triangle, and the length of the prism. The function should start with: ```python def calculate_surface_area(base: float, height: float, length: float) -> float: ```
Here is the Python code to solve the given problem in the markdown block: ```python def calculate_surface_area(base: float, height: float, length: float) -> float: """ Calculate the surface area of a right-angled triangular prism. Args: base (float): The base of the right-angled triangle. h...
magic_evol_110k
110,512
Write a Python function to calculate the number of unique elements in a given list of integers. The function should handle lists with both positive and negative integers, as well as zero. The function should also be robust enough to handle potential exceptions or errors, such as an empty list or non-integer values. Th...
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[int]) -> int: """ Calculate the number of unique elements in a given list of integers. Args: arr (List[int]): The list of integers from which to count uni...
magic_evol_110k
110,515
Write a Python function to print each element of a given list along with its index. The function should iterate over the list using a for loop and use the `enumerate` function to get both the index and the element. The function should start with: ```python from typing import List def print_list_with_indices(lst: List[...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def print_list_with_indices(lst: List[int]) -> None: """ Prints each element of the given list along with its index. Args: lst (List[int]): The list of integers to be printed with indices. ...
magic_evol_110k
110,518
Create a Python function that calculates the factorial of a given non-negative integer using an iterative approach. The function should be able to handle edge cases such as zero and large numbers efficiently. The code should start with: ```python def factorial_iterative(n: int) -> int: ```
Here is the Python code to solve the given problem in the markdown block: ```python def factorial_iterative(n: int) -> int: """ Calculate the factorial of a given non-negative integer using an iterative approach. Args: n (int): The non-negative integer for which to calculate the factorial. Ret...
magic_evol_110k
110,547
Write a Python function to find the largest and second largest numerical values from a list of whole numbers. The function should ensure that the input list is not empty and contains only integers. If these conditions are not met, the function should return an appropriate error message. The function should start with: ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Tuple, Union def find_largest_and_second_largest(numbers: List[int]) -> Union[Tuple[int, int], str]: """ Finds the largest and second largest numerical values from a list of whole numbers. Args: ...
magic_evol_110k
110,553
Write a Python function to demonstrate two distinct techniques for sorting elements in an array. The function should accept a list of integers and a boolean flag indicating whether to sort the list in ascending or descending order. The function should return the sorted list. The code should start with: ```python from t...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def sort_array(numbers: List[int], ascending: bool = True) -> List[int]: """ Sorts the given list of integers using two distinct techniques: in-place sorting and creating a new sorted list. Args: ...
magic_evol_110k
110,584
Write a Python function to reverse the digits of a given integer. The function should handle both positive and negative integers. If the input number is negative, the function should return the digits in reverse order with the negative sign preserved. The function should also handle zero correctly. The code should sta...
Here is the Python code to solve the given problem in the markdown block: ```python def reverse_digits(num: int) -> int: """ Reverses the digits of a given integer. If the input number is negative, the negative sign is preserved. Args: num (int): The integer whose digits are to be reversed. Re...
magic_evol_110k
110,591
Write a Python function to count the occurrences of a specific pattern in a given string, where the pattern must be formed by consecutive characters. The function should not use the built-in `str.count` method. Instead, it should implement a custom algorithm to find and count the occurrences of the pattern. The code s...
Here is the Python code to solve the given problem in the markdown block: ```python def count_pattern_occurrences(text: str, pattern: str) -> int: """ Counts the occurrences of a specific pattern in a given string. Args: text (str): The string in which to search for the pattern. pattern (st...
magic_evol_110k
110,609
Write a Python function to simulate memory allocation and deallocation for a string. The function should allocate a specified number of bytes for a string and then attempt to store a string that may exceed the allocated memory. The function should return a tuple containing the allocated memory size, the attempted strin...
Here is the Python code to solve the given problem in the markdown block: ```python def simulate_memory_allocation(allocated_bytes: int, string_to_store: str) -> tuple: """ Simulate memory allocation and deallocation for a string. Args: allocated_bytes (int): The number of bytes to allocate for the...
magic_evol_110k
110,614
Write a Python function to reverse a given list in-place. The function should modify the original list without using any additional data structures or built-in reverse functions. The code should start with: ```python from typing import List def reverse_list_in_place(lst: List[int]) -> None: ```
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def reverse_list_in_place(lst: List[int]) -> None: """ Reverses the given list in-place. Args: lst (List[int]): The list to be reversed. Returns: None: The function modifies the...
magic_evol_110k
110,635
Write a Python function to evaluate a complex conditional expression involving three variables `x`, `y`, and `z`. The function should return `True` if the condition is satisfied and `False` otherwise. The condition should be such that it checks if `x` is greater than 0, and `y` is less than `z`. Additionally, the funct...
Here is the Python code to solve the given problem in the markdown block: ```python def evaluate_complex_condition(x: int, y: int, z: int) -> bool: """ Evaluates a complex conditional expression involving three variables x, y, and z. The condition to be evaluated is: - x must be greater than 0 - y ...
magic_evol_110k
110,647
Write a Python function to sort a given list of integers in ascending order using the built-in `sort` method. The function should return the sorted list. The code should start with: ```python from typing import List def sort_array_ascending(array: List[int]) -> List[int]: ```
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def sort_array_ascending(array: List[int]) -> List[int]: """ Sorts the given list of integers in ascending order and returns the sorted list. Args: array (List[int]): The list of integers to...
magic_evol_110k
110,648
Write a Python function to search for a specific element in a sorted array and calculate its frequency using the binary search algorithm. The function should return the frequency of the element if found, otherwise return 0. The code should start with: ```python from typing import List def find_element_frequency(arr: L...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def find_element_frequency(arr: List[int], x: int) -> int: """ Searches for a specific element in a sorted array and calculates its frequency. Args: arr (List[int]): The sorted array to sear...
magic_evol_110k
110,667
Write a Python function to convert a tuple of strings into a single string without using the built-in `join()` function. Each element in the tuple should be separated by a space in the resulting string. The function should handle tuples of varying lengths, including empty tuples. The code should start with: ```python ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Tuple def tuple_to_string(tuple_of_strings: Tuple[str, ...]) -> str: """ Converts a tuple of strings into a single string without using the built-in join() function. Each element in the tuple is separated...
magic_evol_110k
110,668
Write a Python function to extract and return a list of unique elements from a given collection while preserving the order of their first appearance. The collection is a list of integers that may contain duplicate items. The function should use a while loop to traverse through the collection and a set to track and dist...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def get_unique_elements(input_list: List[int]) -> List[int]: """ Extracts and returns a list of unique elements from the given collection, preserving the order of their first appearance. Args: ...
magic_evol_110k
110,671
Write a Python function to calculate the product of all elements in a given list of integers. The function should handle lists of any length, including empty lists. If the list is empty, the function should return 1 as the product. The code should start with: ```python from typing import List def product_of_elements(l...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def product_of_elements(lst: List[int]) -> int: """ Calculate the product of all elements in a given list of integers. Args: lst (List[int]): The list of integers whose product is to be calc...
magic_evol_110k
110,680
Write a Python function to reverse the order of elements in a given list and return the reversed list. The function should handle lists of any length and any type of elements. The code should start with: ```python from typing import List, Any def reverse_list(arr: List[Any]) -> List[Any]: ```
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Any def reverse_list(arr: List[Any]) -> List[Any]: """ Reverses the order of elements in the given list and returns the reversed list. Args: arr (List[Any]): The list to be reversed. R...
magic_evol_110k
110,696
Write a Python function to compute the factorial of a given non-negative integer using a for-loop. The function should handle the case where the input number is 0 by returning 1, as the factorial of 0 is defined to be 1. The function should also handle larger numbers efficiently. The code should start with: ```python ...
Here is the Python code to solve the given problem in the markdown block: ```python def compute_factorial(n: int) -> int: """ Compute the factorial of a given non-negative integer using a for-loop. Args: n (int): The non-negative integer for which to compute the factorial. Returns: int...
magic_evol_110k
110,702
Write a Python function to generate all possible combinations of a specified length from a given set of characters. The function should return a list of strings, where each string is a unique combination of the characters. The code should start with: ```python from typing import List def generate_combinations(characte...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List import itertools def generate_combinations(characters: str, length: int) -> List[str]: """ Generate all possible combinations of a specified length from a given set of characters. Args: char...
magic_evol_110k
110,707
Write a Python function to calculate the median of three given integers without using sorting. The function should determine the median by comparing the integers directly. The code should start with: ```python def median_of_three(num1: int, num2: int, num3: int) -> int: ```
Here is the Python code to solve the given problem in the markdown block: ```python def median_of_three(num1: int, num2: int, num3: int) -> int: """ Calculate the median of three given integers without using sorting. Args: num1 (int): The first integer. num2 (int): The second integer. ...
magic_evol_110k
110,710
Write a Python function to calculate the cumulative sum of a list of numerical values. The function should take a list of integers as input and return a list of integers where each element at index `i` is the sum of all elements from the input list up to index `i`. The code should start with: ```python from typing imp...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def cumulative_sum(arr: List[int]) -> List[int]: """ Calculate the cumulative sum of a list of numerical values. Args: arr (List[int]): A list of integers for which the cumulative sum is to ...
magic_evol_110k
110,732
Write a Python function to calculate the sum of the highest (maximum) and lowest (minimum) integers within a given list of numerical values. The function should handle lists of any length, including empty lists, and return `None` if the list is empty. The code should start with: ```python from typing import List, Opti...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Optional def sum_of_extremes(numbers: List[int]) -> Optional[int]: """ Calculate the sum of the highest (maximum) and lowest (minimum) integers within a given list of numerical values. Args: ...
magic_evol_110k
110,744
Write a Python function to determine if it is possible to swap elements between two non-empty arrays of integers such that the first array (`lst1`) becomes an array of only even integers without changing the overall sum of both arrays. The function should return "YES" if such a swap is possible, and "NO" otherwise. Th...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def can_swap_to_even(lst1: List[int], lst2: List[int]) -> str: """ Determines if it is possible to swap elements between two arrays such that the first array becomes an array of only even integers wi...
magic_evol_110k
110,748
Write a Python function to compare two poker cards based on their rank and suit, and determine which card is stronger according to the standard poker ranking system. Additionally, implement a function to shuffle a list of cards such that the original order is not easily deducible. The cards are represented as tuples wh...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Tuple import random def compare_cards(card1: Tuple[str, str], card2: Tuple[str, str]) -> Tuple[str, Tuple[str, str]]: """ Compare two poker cards based on their rank and suit, and return the stronger ca...
magic_evol_110k
110,751
Write a Python function to determine the type of the product (even or odd) of two given integers based on their types (even or odd). The function should return a string indicating whether the product is "even" or "odd". The function should also validate the types of the input numbers and raise a ValueError if the types...
Here is the Python code to solve the given problem in the markdown block: ```python def determine_product_type(num1: int, num2: int, num1_type: str, num2_type: str) -> str: """ Determine the type of the product (even or odd) of two given integers based on their types. Args: num1 (int): The first nu...
magic_evol_110k
110,752
Write a Python function to swap elements at two distinct positions within an integer numerical sequence. The function should take a list of integers and two indices, `i` and `j`, and swap the elements at these positions. Ensure the function handles invalid indices gracefully by returning `None` if either index is out o...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Optional def swap_elements(arr: List[int], i: int, j: int) -> Optional[List[int]]: """ Swaps the elements at positions `i` and `j` in the given list `arr`. Args: arr (List[int]): The list o...