```python
from typing import List

def has_close_elements(numbers: List[float], threshold: float) -> bool:
    """ Check if in given list of numbers, are any two numbers closer to each other than
    given threshold.
    >>> has_close_elements([1.0, 2.0, 3.0], 0.5)
    False
    >>> has_close_elements([1.0, 2.8, 3.0, 4.0, 5.0, 2.0], 0.3)
    True
    """
    if len(numbers) < 2:
        return False

    sorted_numbers = sorted(numbers)

    for i in range(len(sorted_numbers) - 1):
        if sorted_numbers[i + 1] - sorted_numbers[i] < threshold:
            return True

    return False
```


```python
from typing import List

def separate_paren_groups(paren_string: str) -> List[str]:
    """ Input to this function is a string containing multiple groups of nested parentheses. Your goal is to
    separate those group into separate strings and return the list of those.
    Separate groups are balanced (each open brace is properly closed) and not nested within each other
    Ignore any spaces in the input string.
    >>> separate_paren_groups('( ) (( )) (( )( ))')
    ['()', '(())', '(()())']
    """
    # Remove all spaces from the input
    stripped = paren_string.replace(' ', '')

    result = []
    current_group = ""
    balance = 0

    for ch in stripped:
        current_group += ch
        if ch == '(':
            balance += 1
        elif ch == ')':
            balance -= 1

        # When balance reaches 0, we have a complete balanced group
        if balance == 0:
            result.append(current_group)
            current_group = ""

    return result
```


```python

def truncate_number(number: float) -> float:
    """ Given a positive floating point number, it can be decomposed into
    and integer part (largest integer smaller than given number) and decimals
    (leftover part always smaller than 1).

    Return the decimal part of the number.
    >>> truncate_number(3.5)
    0.5
    """
    return number - int(number)

```


```python

from typing import List

def below_zero(operations: List[int]) -> bool:
    balance = 0
    for op in operations:
        balance += op
        if balance < 0:
            return True
    return False

```


```python
from typing import List

def mean_absolute_deviation(numbers: List[float]) -> float:
    """ For a given list of input numbers, calculate Mean Absolute Deviation
    around the mean of this dataset.
    Mean Absolute Deviation is the average absolute difference between each
    element and a centerpoint (mean in this case):
    MAD = average | x - x_mean |
    >>> mean_absolute_deviation([1.0, 2.0, 3.0, 4.0])
    1.0
    """
    if not numbers:
        return 0.0
    mean = sum(numbers) / len(numbers)
    total_abs_dev = sum(abs(x - mean) for x in numbers)
    return total_abs_dev / len(numbers)
```


```python
from typing import List

def intersperse(numbers: List[int], delimeter: int) -> List[int]:
    """ Insert a number 'delimeter' between every two consecutive elements of input list `numbers'
    >>> intersperse([], 4)
    []
    >>> intersperse([1, 2, 3], 4)
    [1, 4, 2, 4, 3]
    """
    if not numbers:
        return []

    result = []
    for i, num in enumerate(numbers):
        result.append(num)
        if i < len(numbers) - 1:
            result.append(delimeter)
    return result
```


```python
from typing import List

def parse_nested_parens(paren_string: str) -> List[int]:
    """ Input to this function is a string represented multiple groups for nested parentheses separated by spaces.
    For each of the group, output the deepest level of nesting of parentheses.
    E.g. (()()) has maximum two levels of nesting while ((())) has three.

    >>> parse_nested_parens('(()()) ((())) () ((())()())')
    [2, 3, 1, 3]
    """
    groups = paren_string.split()
    result = []

    for group in groups:
        max_depth = 0
        current_depth = 0

        for char in group:
            if char == '(':
                current_depth += 1
                max_depth = max(max_depth, current_depth)
            elif char == ')':
                current_depth -= 1

        result.append(max_depth)

    return result
```


```python
from typing import List

def filter_by_substring(strings: List[str], substring: str) -> List[str]:
    """ Filter an input list of strings only for ones that contain given substring
    >>> filter_by_substring([], 'a')
    []
    >>> filter_by_substring(['abc', 'bacd', 'cde', 'array'], 'a')
    ['abc', 'bacd', 'array']
    """
    return [s for s in strings if substring in s]
```


```python
from typing import List, Tuple

def sum_product(numbers: List[int]) -> Tuple[int, int]:
    """ For a given list of integers, return a tuple consisting of a sum and a product of all the integers in a list.
    Empty sum should be equal to 0 and empty product should be equal to 1.
    >>> sum_product([])
    (0, 1)
    >>> sum_product([1, 2, 3, 4])
    (10, 24)
    """
    if not numbers:
        return (0, 1)

    total_sum = 0
    total_product = 1
    for num in numbers:
        total_sum += num
        total_product *= num

    return (total_sum, total_product)
```


```python
from typing import List

def rolling_max(numbers: List[int]) -> List[int]:
    result = []
    current_max = float('-inf')
    for num in numbers:
        if num > current_max:
            current_max = num
        result.append(current_max)
    return result
```


```python

def is_palindrome(string: str) -> bool:
    """ Test if given string is a palindrome """
    return string == string[::-1]

def make_palindrome(string: str) -> str:
    """ Find the shortest palindrome that begins with a supplied string.
    Algorithm idea is simple:
    - Find the longest postfix of supplied string that is a palindrome.
    - Append to the end of the string reverse of a string prefix that comes before the palindromic suffix.
    >>> make_palindrome('')
    ''
    >>> make_palindrome('cat')
    'catac'
    >>> make_palindrome('cata')
    'catac'
    """
    if not string:
        return ""

    # Find the longest palindromic suffix
    for i in range(len(string), 0, -1):
        suffix = string[-i:]
        if is_palindrome(suffix):
            # The prefix is everything before the suffix
            prefix = string[:-i]
            # Reverse the prefix and append
            return string + prefix[::-1]

    # Should never reach here because single character is always a palindrome
    return string

```


```python
from typing import List

def string_xor(a: str, b: str) -> str:
    """ Input are two strings a and b consisting only of 1s and 0s.
    Perform binary XOR on these inputs and return result also as a string.
    >>> string_xor('010', '110')
    '100'
    """
    result = []
    for i in range(len(a)):
        if a[i] == b[i]:
            result.append('0')
        else:
            result.append('1')
    return ''.join(result)
```


```python
from typing import List, Optional

def longest(strings: List[str]) -> Optional[str]:
    """ Out of list of strings, return the longest one. Return the first one in case of multiple
    strings of the same length. Return None in case the input list is empty.
    >>> longest([])

    >>> longest(['a', 'b', 'c'])
    'a'
    >>> longest(['a', 'bb', 'ccc'])
    'ccc'
    """
    if not strings:
        return None

    longest_str = strings[0]
    for s in strings[1:]:
        if len(s) > len(longest_str):
            longest_str = s
    return longest_str
```


```python
def greatest_common_divisor(a: int, b: int) -> int:
    """ Return a greatest common divisor of two integers a and b
    >>> greatest_common_divisor(3, 5)
    1
    >>> greatest_common_divisor(25, 15)
    5
    """
    a, b = abs(a), abs(b)
    while b:
        a, b = b, a % b
    return a
```


```python
from typing import List

def all_prefixes(string: str) -> List[str]:
    """ Return list of all prefixes from shortest to longest of the input string
    >>> all_prefixes('abc')
    ['a', 'ab', 'abc']
    """
    return [string[:i] for i in range(1, len(string) + 1)]
```


```python

def string_sequence(n: int) -> str:
    """ Return a string containing space-delimited numbers starting from 0 upto n inclusive.
    >>> string_sequence(0)
    '0'
    >>> string_sequence(5)
    '0 1 2 3 4 5'
    """
    return ' '.join(str(i) for i in range(n + 1))

```


```python

def count_distinct_characters(string: str) -> int:
    """ Given a string, find out how many distinct characters (regardless of case) does it consist of
    >>> count_distinct_characters('xyzXYZ')
    3
    >>> count_distinct_characters('Jerry')
    4
    """
    return len(set(string.lower()))

```


```python
from typing import List

def parse_music(music_string: str) -> List[int]:
    """ Input to this function is a string representing musical notes in a special ASCII format.
    Your task is to parse this string and return list of integers corresponding to how many beats does each
    not last.

    Here is a legend:
    'o' - whole note, lasts four beats
    'o|' - half note, lasts two beats
    '.|' - quater note, lasts one beat

    >>> parse_music('o o| .| o| o| .| .| .| .| o o')
    [4, 2, 1, 2, 2, 1, 1, 1, 1, 4, 4]
    """
    result = []
    i = 0
    tokens = music_string.split()
    for token in tokens:
        if token == 'o':
            result.append(4)
        elif token == 'o|':
            result.append(2)
        elif token == '.|':
            result.append(1)
    return result
```


```python

def how_many_times(string: str, substring: str) -> int:
    """ Find how many times a given substring can be found in the original string. Count overlaping cases.
    >>> how_many_times('', 'a')
    0
    >>> how_many_times('aaa', 'a')
    3
    >>> how_many_times('aaaa', 'aa')
    3
    """
    if not substring:
        return 0
    count = 0
    start = 0
    while True:
        pos = string.find(substring, start)
        if pos == -1:
            break
        count += 1
        start = pos + 1
    return count

```


```python
from typing import List

def sort_numbers(numbers: str) -> str:
    """ Input is a space-delimited string of numberals from 'zero' to 'nine'.
    Valid choices are 'zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight' and 'nine'.
    Return the string with numbers sorted from smallest to largest
    >>> sort_numbers('three one five')
    'one three five'
    """
    word_to_num = {
        'zero': 0, 'one': 1, 'two': 2, 'three': 3, 'four': 4,
        'five': 5, 'six': 6, 'seven': 7, 'eight': 8, 'nine': 9
    }
    num_to_word = {v: k for k, v in word_to_num.items()}

    words = numbers.split()
    nums = [word_to_num[w] for w in words]
    nums.sort()
    sorted_words = [num_to_word[n] for n in nums]
    return ' '.join(sorted_words)
```


```python
from typing import List, Tuple

def find_closest_elements(numbers: List[float]) -> Tuple[float, float]:
    """ From a supplied list of numbers (of length at least two) select and return two that are the closest to each
    other and return them in order (smaller number, larger number).
    >>> find_closest_elements([1.0, 2.0, 3.0, 4.0, 5.0, 2.2])
    (2.0, 2.2)
    >>> find_closest_elements([1.0, 2.0, 3.0, 4.0, 5.0, 2.0])
    (2.0, 2.0)
    """
    numbers.sort()
    min_diff = float('inf')
    closest_pair = (0.0, 0.0)

    for i in range(len(numbers) - 1):
        diff = numbers[i+1] - numbers[i]
        if diff < min_diff:
            min_diff = diff
            closest_pair = (numbers[i], numbers[i+1])

    return closest_pair
```


```python
from typing import List

def rescale_to_unit(numbers: List[float]) -> List[float]:
    """ Given list of numbers (of at least two elements), apply a linear transform to that list,
    such that the smallest number will become 0 and the largest will become 1
    >>> rescale_to_unit([1.0, 2.0, 3.0, 4.0, 5.0])
    [0.0, 0.25, 0.5, 0.75, 1.0]
    """
    min_val = min(numbers)
    max_val = max(numbers)
    range_val = max_val - min_val
    if range_val == 0:
        # If all numbers are the same, return list of zeros (or handle as needed)
        return [0.0] * len(numbers)
    return [(x - min_val) / range_val for x in numbers]
```


```python
from typing import List, Any

def filter_integers(values: List[Any]) -> List[int]:
    """ Filter given list of any python values only for integers
    >>> filter_integers(['a', 3.14, 5])
    [5]
    >>> filter_integers([1, 2, 3, 'abc', {}, []])
    [1, 2, 3]
    """
    return [v for v in values if isinstance(v, int)]
```


```python
def strlen(string: str) -> int:
    """ Return length of given string
    >>> strlen('')
    0
    >>> strlen('abc')
    3
    """
    return len(string)
```


```python
def largest_divisor(n: int) -> int:
    """ For a given number n, find the largest number that divides n evenly, smaller than n
    >>> largest_divisor(15)
    5
    """
    for i in range(n // 2, 0, -1):
        if n % i == 0:
            return i
    return 1
```


```python
from typing import List

def factorize(n: int) -> List[int]:
    """ Return list of prime factors of given integer in the order from smallest to largest.
    Each of the factors should be listed number of times corresponding to how many times it appeares in factorization.
    Input number should be equal to the product of all factors
    >>> factorize(8)
    [2, 2, 2]
    >>> factorize(25)
    [5, 5]
    >>> factorize(70)
    [2, 5, 7]
    """
    factors = []
    d = 2
    while d * d <= n:
        while n % d == 0:
            factors.append(d)
            n //= d
        d += 1
    if n > 1:
        factors.append(n)
    return factors
```


```python
from typing import List

def remove_duplicates(numbers: List[int]) -> List[int]:
    """ From a list of integers, remove all elements that occur more than once.
    Keep order of elements left the same as in the input.
    >>> remove_duplicates([1, 2, 3, 2, 4])
    [1, 3, 4]
    """
    # Count occurrences of each number
    counts = {}
    for num in numbers:
        counts[num] = counts.get(num, 0) + 1

    # Keep only numbers that appear exactly once, preserving order
    result = [num for num in numbers if counts[num] == 1]
    return result
```


```python

def flip_case(string: str) -> str:
    """ For a given string, flip lowercase characters to uppercase and uppercase to lowercase.
    >>> flip_case('Hello')
    'hELLO'
    """
    return string.swapcase()

```


```python
from typing import List

def concatenate(strings: List[str]) -> str:
    """ Concatenate list of strings into a single string
    >>> concatenate([])
    ''
    >>> concatenate(['a', 'b', 'c'])
    'abc'
    """
    return ''.join(strings)
```


```python
from typing import List

def filter_by_prefix(strings: List[str], prefix: str) -> List[str]:
    """ Filter an input list of strings only for ones that start with a given prefix.
    >>> filter_by_prefix([], 'a')
    []
    >>> filter_by_prefix(['abc', 'bcd', 'cde', 'array'], 'a')
    ['abc', 'array']
    """
    return [s for s in strings if s.startswith(prefix)]
```


```python

def get_positive(l: list):
    """Return only positive numbers in the list.
    >>> get_positive([-1, 2, -4, 5, 6])
    [2, 5, 6]
    >>> get_positive([5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10])
    [5, 3, 2, 3, 9, 123, 1]
    """
    return [x for x in l if x > 0]

```


```python

def is_prime(n):
    """Return true if a given number is prime, and false otherwise.
    >>> is_prime(6)
    False
    >>> is_prime(101)
    True
    >>> is_prime(11)
    True
    >>> is_prime(13441)
    True
    >>> is_prime(61)
    True
    >>> is_prime(4)
    False
    >>> is_prime(1)
    False
    """
    if n <= 1:
        return False
    if n <= 3:
        return True
    if n % 2 == 0 or n % 3 == 0:
        return False
    i = 5
    while i * i <= n:
        if n % i == 0 or n % (i + 2) == 0:
            return False
        i += 6
    return True

```


Here's the implementation for the `find_zero` function using a binary search approach, assuming the polynomial is continuous and we can find a root by narrowing in on a sign change.

```python
import math

def poly(xs: list, x: float):
    """
    Evaluates polynomial with coefficients xs at point x.
    return xs[0] + xs[1] * x + xs[1] * x^2 + .... xs[n] * x^n
    """
    return sum([coeff * math.pow(x, i) for i, coeff in enumerate(xs)])

def find_zero(xs: list):
    """ xs are coefficients of a polynomial.
    find_zero find x such that poly(x) = 0.
    find_zero returns only only zero point, even if there are many.
    Moreover, find_zero only takes list xs having even number of coefficients
    and largest non zero coefficient as it guarantees
    a solution.
    >>> round(find_zero([1, 2]), 2) # f(x) = 1 + 2x
    -0.5
    >>> round(find_zero([-6, 11, -6, 1]), 2) # (x - 1) * (x - 2) * (x - 3) = -6 + 11x - 6x^2 + x^3
    1.0
    """
    # Find a starting interval where poly changes sign
    # Start with a reasonable range and expand until sign change found
    low = -10.0
    high = 10.0

    f_low = poly(xs, low)
    f_high = poly(xs, high)

    # Expand range if needed
    while f_low * f_high > 0:
        low *= 2
        high *= 2
        f_low = poly(xs, low)
        f_high = poly(xs, high)

    # Binary search for root
    for _ in range(50):  # enough iterations for high precision
        mid = (low + high) / 2
        f_mid = poly(xs, mid)
        if f_mid == 0:
            return mid
        if f_low * f_mid < 0:
            high = mid
            f_high = f_mid
        else:
            low = mid
            f_low = f_mid

    return (low + high) / 2
```


Here's the implementation for the function you described:

```python
def sort_third(l: list):
    """This function takes a list l and returns a list l' such that
    l' is identical to l in the indices that are not divisible by three, while its values at the indices that are divisible by three are equal
    to the values of the corresponding indices of l, but sorted.
    >>> sort_third([1, 2, 3])
    [1, 2, 3]
    >>> sort_third([5, 6, 3, 4, 8, 9, 2])
    [2, 6, 3, 4, 8, 9, 5]
    """
    # Extract values at indices divisible by 3
    values_at_divisible = [l[i] for i in range(len(l)) if i % 3 == 0]
    # Sort them
    values_at_divisible.sort()

    # Build result list
    result = []
    sorted_index = 0
    for i in range(len(l)):
        if i % 3 == 0:
            result.append(values_at_divisible[sorted_index])
            sorted_index += 1
        else:
            result.append(l[i])

    return result
```


```python

def unique(l: list):
    """Return sorted unique elements in a list
    >>> unique([5, 3, 5, 2, 3, 3, 9, 0, 123])
    [0, 2, 3, 5, 9, 123]
    """
    return sorted(set(l))

```


```python

def max_element(l: list):
    """Return maximum element in the list.
    >>> max_element([1, 2, 3])
    3
    >>> max_element([5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10])
    123
    """
    if not l:
        raise ValueError("max_element() arg is an empty list")
    max_val = l[0]
    for x in l[1:]:
        if x > max_val:
            max_val = x
    return max_val

```


```python

def fizz_buzz(n: int):
    """Return the number of times the digit 7 appears in integers less than n which are divisible by 11 or 13.
    >>> fizz_buzz(50)
    0
    >>> fizz_buzz(78)
    2
    >>> fizz_buzz(79)
    3
    """
    count = 0
    for i in range(n):
        if i % 11 == 0 or i % 13 == 0:
            count += str(i).count('7')
    return count

```


```python

def sort_even(l: list):
    """This function takes a list l and returns a list l' such that
    l' is identical to l in the odd indicies, while its values at the even indicies are equal
    to the values of the even indicies of l, but sorted.
    >>> sort_even([1, 2, 3])
    [1, 2, 3]
    >>> sort_even([5, 6, 3, 4])
    [3, 6, 5, 4]
    """
    even_values = sorted([l[i] for i in range(0, len(l), 2)])
    result = []
    even_idx = 0
    for i in range(len(l)):
        if i % 2 == 0:
            result.append(even_values[even_idx])
            even_idx += 1
        else:
            result.append(l[i])
    return result

```


Traceback (most recent call last):
  File "<string>", line 30, in <module>
    check(decode_cyclic)
    ~~~~~^^^^^^^^^^^^^^^
  File "<string>", line 26, in check
    encoded_str = encode_cyclic(str)
                  ^^^^^^^^^^^^^
NameError: name 'encode_cyclic' is not defined. Did you mean: 'decode_cyclic'?

```python

def decode_cyclic(s: str):
    """
    takes as input string encoded with encode_cyclic function. Returns decoded string.
    """
    # split string into groups of three characters
    groups = [s[(3 * i):min((3 * i + 3), len(s))] for i in range((len(s) + 2) // 3)]
    # reverse the cycle: move last character to front for groups of length 3
    groups = [(group[-1:] + group[:-1]) if len(group) == 3 else group for group in groups]
    return "".join(groups)

```


```python

def prime_fib(n: int):
    """
    prime_fib returns n-th number that is a Fibonacci number and it's also prime.
    >>> prime_fib(1)
    2
    >>> prime_fib(2)
    3
    >>> prime_fib(3)
    5
    >>> prime_fib(4)
    13
    >>> prime_fib(5)
    89
    """
    def is_prime(num: int) -> bool:
        if num < 2:
            return False
        if num == 2:
            return True
        if num % 2 == 0:
            return False
        i = 3
        while i * i <= num:
            if num % i == 0:
                return False
            i += 2
        return True

    count = 0
    a, b = 1, 2  # start with Fibonacci numbers 1, 2 (1 is not prime, 2 is prime)
    while True:
        # Check the current Fibonacci number (b)
        if is_prime(b):
            count += 1
            if count == n:
                return b
        # Generate next Fibonacci number
        a, b = b, a + b

```


```python

def triples_sum_to_zero(l: list):
    """
    triples_sum_to_zero takes a list of integers as an input.
    it returns True if there are three distinct elements in the list that
    sum to zero, and False otherwise.
    """
    n = len(l)
    for i in range(n):
        for j in range(i + 1, n):
            for k in range(j + 1, n):
                if l[i] + l[j] + l[k] == 0:
                    return True
    return False

```


```python

def car_race_collision(n: int) -> int:
    """
    Imagine a road that's a perfectly straight infinitely long line.
    n cars are driving left to right;  simultaneously, a different set of n cars
    are driving right to left.   The two sets of cars start out being very far from
    each other.  All cars move in the same speed.  Two cars are said to collide
    when a car that's moving left to right hits a car that's moving right to left.
    However, the cars are infinitely sturdy and strong; as a result, they continue moving
    in their trajectory as if they did not collide.

    This function outputs the number of such collisions.
    """
    # Each left-to-right car will collide with each right-to-left car exactly once.
    # So total collisions = n * n.
    return n * n

```


```python

def incr_list(l: list):
    """Return list with elements incremented by 1.
    >>> incr_list([1, 2, 3])
    [2, 3, 4]
    >>> incr_list([5, 3, 5, 2, 3, 3, 9, 0, 123])
    [6, 4, 6, 3, 4, 4, 10, 1, 124]
    """
    return [x + 1 for x in l]

```


```python

def pairs_sum_to_zero(l):
    """
    pairs_sum_to_zero takes a list of integers as an input.
    it returns True if there are two distinct elements in the list that
    sum to zero, and False otherwise.
    >>> pairs_sum_to_zero([1, 3, 5, 0])
    False
    >>> pairs_sum_to_zero([1, 3, -2, 1])
    False
    >>> pairs_sum_to_zero([1, 2, 3, 7])
    False
    >>> pairs_sum_to_zero([2, 4, -5, 3, 5, 7])
    True
    >>> pairs_sum_to_zero([1])
    False
    """
    seen = set()
    for num in l:
        if -num in seen:
            return True
        seen.add(num)
    return False

```


```python
def change_base(x: int, base: int):
    """Change numerical base of input number x to base.
    return string representation after the conversion.
    base numbers are less than 10.
    >>> change_base(8, 3)
    '22'
    >>> change_base(8, 2)
    '1000'
    >>> change_base(7, 2)
    '111'
    """
    if x == 0:
        return '0'

    digits = []
    while x > 0:
        digits.append(str(x % base))
        x //= base

    return ''.join(reversed(digits))
```


```python

def triangle_area(a, h):
    """Given length of a side and high return area for a triangle.
    >>> triangle_area(5, 3)
    7.5
    """
    return a * h / 2

```


Here's the efficient, iterative implementation for the fib4 sequence:

```python
def fib4(n: int):
    """The Fib4 number sequence is a sequence similar to the Fibbonacci sequnece that's defined as follows:
    fib4(0) -> 0
    fib4(1) -> 0
    fib4(2) -> 2
    fib4(3) -> 0
    fib4(n) -> fib4(n-1) + fib4(n-2) + fib4(n-3) + fib4(n-4).
    Please write a function to efficiently compute the n-th element of the fib4 number sequence.  Do not use recursion.
    >>> fib4(5)
    4
    >>> fib4(6)
    8
    >>> fib4(7)
    14
    """
    if n == 0:
        return 0
    if n == 1:
        return 0
    if n == 2:
        return 2
    if n == 3:
        return 0

    # Initial values for n=0,1,2,3
    a, b, c, d = 0, 0, 2, 0

    for _ in range(4, n + 1):
        next_val = a + b + c + d
        a, b, c, d = b, c, d, next_val

    return d
```


```python

def median(l: list):
    """Return median of elements in the list l.
    >>> median([3, 1, 2, 4, 5])
    3
    >>> median([-10, 4, 6, 1000, 10, 20])
    15.0
    """
    sorted_l = sorted(l)
    n = len(sorted_l)
    if n == 0:
        raise ValueError("Cannot compute median of an empty list")
    if n % 2 == 1:
        return sorted_l[n // 2]
    else:
        mid1 = sorted_l[n // 2 - 1]
        mid2 = sorted_l[n // 2]
        return (mid1 + mid2) / 2.0

```


```python
def is_palindrome(text: str):
    """
    Checks if given string is a palindrome
    >>> is_palindrome('')
    True
    >>> is_palindrome('aba')
    True
    >>> is_palindrome('aaaaa')
    True
    >>> is_palindrome('zbcd')
    False
    """
    return text == text[::-1]
```


```python
def modp(n: int, p: int):
    """Return 2^n modulo p (be aware of numerics).
    >>> modp(3, 5)
    3
    >>> modp(1101, 101)
    2
    >>> modp(0, 101)
    1
    >>> modp(3, 11)
    8
    >>> modp(100, 101)
    1
    """
    if n == 0:
        return 1 % p
    result = 1
    base = 2 % p
    while n > 0:
        if n & 1:
            result = (result * base) % p
        base = (base * base) % p
        n >>= 1
    return result
```


```python

def encode_shift(s: str):
    """
    returns encoded string by shifting every character by 5 in the alphabet.
    """
    return "".join([chr(((ord(ch) + 5 - ord("a")) % 26) + ord("a")) for ch in s])

def decode_shift(s: str):
    """
    takes as input string encoded with encode_shift function. Returns decoded string.
    """
    return "".join([chr(((ord(ch) - 5 - ord("a")) % 26) + ord("a")) for ch in s])

```


```python

def remove_vowels(text):
    """
    remove_vowels is a function that takes string and returns string without vowels.
    >>> remove_vowels('')
    ''
    >>> remove_vowels("abcdef\nghijklm")
    'bcdf\nghjklm'
    >>> remove_vowels('abcdef')
    'bcdf'
    >>> remove_vowels('aaaaa')
    ''
    >>> remove_vowels('aaBAA')
    'B'
    >>> remove_vowels('zbcd')
    'zbcd'
    """
    vowels = set('aeiouAEIOU')
    return ''.join(ch for ch in text if ch not in vowels)

```


```python
def below_threshold(l: list, t: int):
    """Return True if all numbers in the list l are below threshold t.
    >>> below_threshold([1, 2, 4, 10], 100)
    True
    >>> below_threshold([1, 20, 4, 10], 5)
    False
    """
    for num in l:
        if num >= t:
            return False
    return True
```


```python
def add(x: int, y: int):
    """Add two numbers x and y
    >>> add(2, 3)
    5
    >>> add(5, 7)
    12
    """
    return x + y
```


Traceback (most recent call last):
  File "<string>", line 38, in <module>
    check(same_chars)
    ~~~~~^^^^^^^^^^^^
  File "<string>", line 29, in check
    assert candidate('eabcdzzzz', 'dddzzzzzzzddeddabc') == True
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AssertionError

```python

def same_chars(s0: str, s1: str):
    """
    Check if two words have the same characters.
    >>> same_chars('eabcdzzzz', 'dddzzzzzzzddeddabc')
    True
    >>> same_chars('abcd', 'dddddddabc')
    True
    >>> same_chars('dddddddabc', 'abcd')
    True
    >>> same_chars('eabcd', 'dddddddabc')
    False
    >>> same_chars('abcd', 'dddddddabce')
    False
    >>> same_chars('eabcdzzzz', 'dddzzzzzzzddddabc')
    False
    """
    from collections import Counter
    return Counter(s0) == Counter(s1)

```


```python

def fib(n: int):
    """Return n-th Fibonacci number.
    >>> fib(10)
    55
    >>> fib(1)
    1
    >>> fib(8)
    21
    """
    if n <= 0:
        return 0
    a, b = 0, 1
    for _ in range(n):
        a, b = b, a + b
    return a

```


```python
def correct_bracketing(brackets: str):
    """ brackets is a string of "<" and ">".
    return True if every opening bracket has a corresponding closing bracket.

    >>> correct_bracketing("<")
    False
    >>> correct_bracketing("<>")
    True
    >>> correct_bracketing("<<><>>")
    True
    >>> correct_bracketing("><<>")
    False
    """
    count = 0
    for b in brackets:
        if b == "<":
            count += 1
        elif b == ">":
            if count == 0:
                return False
            count -= 1
    return count == 0
```


```python

def monotonic(l: list):
    """Return True if list elements are monotonically increasing or decreasing.
    >>> monotonic([1, 2, 4, 20])
    True
    >>> monotonic([1, 20, 4, 10])
    False
    >>> monotonic([4, 1, 0, -10])
    True
    """
    if len(l) <= 1:
        return True
    # Determine direction from first non-equal pair
    increasing = None
    for i in range(1, len(l)):
        if l[i] > l[i-1]:
            if increasing is None:
                increasing = True
            elif not increasing:
                return False
        elif l[i] < l[i-1]:
            if increasing is None:
                increasing = False
            elif increasing:
                return False
        # if equal, direction unchanged
    return True

```


```python

def common(l1: list, l2: list):
    """Return sorted unique common elements for two lists.
    >>> common([1, 4, 3, 34, 653, 2, 5], [5, 7, 1, 5, 9, 653, 121])
    [1, 5, 653]
    >>> common([5, 3, 2, 8], [3, 2])
    [2, 3]

    """
    # Convert both lists to sets to get unique elements
    set1 = set(l1)
    set2 = set(l2)

    # Find intersection of the two sets
    common_elements = set1 & set2

    # Return sorted list of the common elements
    return sorted(common_elements)

```


```python

def largest_prime_factor(n: int):
    """Return the largest prime factor of n. Assume n > 1 and is not a prime.
    >>> largest_prime_factor(13195)
    29
    >>> largest_prime_factor(2048)
    2
    """
    factor = 2
    while factor * factor <= n:
        if n % factor == 0:
            n //= factor
        else:
            factor += 1 if factor == 2 else 2  # after 2, check only odd numbers
    return n

```


```python
def sum_to_n(n: int):
    """sum_to_n is a function that sums numbers from 1 to n.
    >>> sum_to_n(30)
    465
    >>> sum_to_n(100)
    5050
    >>> sum_to_n(5)
    15
    >>> sum_to_n(10)
    55
    >>> sum_to_n(1)
    1
    """
    return n * (n + 1) // 2
```


```python
def correct_bracketing(brackets: str):
    """ brackets is a string of "(" and ")".
    return True if every opening bracket has a corresponding closing bracket.

    >>> correct_bracketing("(")
    False
    >>> correct_bracketing("()")
    True
    >>> correct_bracketing("(()())")
    True
    >>> correct_bracketing(")(()")
    False
    """
    balance = 0
    for b in brackets:
        if b == '(':
            balance += 1
        elif b == ')':
            balance -= 1
        if balance < 0:
            return False
    return balance == 0
```


```python

def derivative(xs: list):
    """ xs represent coefficients of a polynomial.
    xs[0] + xs[1] * x + xs[2] * x^2 + ....
     Return derivative of this polynomial in the same form.
    >>> derivative([3, 1, 2, 4, 5])
    [1, 4, 12, 20]
    >>> derivative([1, 2, 3])
    [2, 6]
    """
    if len(xs) <= 1:
        return []
    result = []
    for i in range(1, len(xs)):
        result.append(i * xs[i])
    return result

```


Here's the efficient implementation using an iterative approach:

```python
def fibfib(n: int):
    """The FibFib number sequence is a sequence similar to the Fibbonacci sequnece that's defined as follows:
    fibfib(0) == 0
    fibfib(1) == 0
    fibfib(2) == 1
    fibfib(n) == fibfib(n-1) + fibfib(n-2) + fibfib(n-3).
    Please write a function to efficiently compute the n-th element of the fibfib number sequence.
    >>> fibfib(1)
    0
    >>> fibfib(5)
    4
    >>> fibfib(8)
    24
    """
    if n < 0:
        raise ValueError("n must be non-negative")
    if n == 0 or n == 1:
        return 0
    if n == 2:
        return 1

    a, b, c = 0, 0, 1  # representing fibfib(0), fibfib(1), fibfib(2)

    for _ in range(3, n + 1):
        next_val = a + b + c
        a, b, c = b, c, next_val

    return c
```


Here's the implementation of the `vowels_count` function:

```python
def vowels_count(s: str) -> int:
    """Write a function vowels_count which takes a string representing
    a word as input and returns the number of vowels in the string.
    Vowels in this case are 'a', 'e', 'i', 'o', 'u'. Here, 'y' is also a
    vowel, but only when it is at the end of the given word.

    Example:
    >>> vowels_count("abcde")
    2
    >>> vowels_count("ACEDY")
    3
    """
    vowels = set('aeiou')
    count = 0
    s_lower = s.lower()

    for i, ch in enumerate(s_lower):
        if ch in vowels:
            count += 1
        elif ch == 'y' and i == len(s) - 1:
            count += 1

    return count
```


Here's the implementation for the function:

```python
def circular_shift(x, shift):
    """Circular shift the digits of the integer x, shift the digits right by shift
    and return the result as a string.
    If shift > number of digits, return digits reversed.
    >>> circular_shift(12, 1)
    "21"
    >>> circular_shift(12, 2)
    "12"
    """
    digits = str(x)
    if shift > len(digits):
        return digits[::-1]
    return digits[-shift:] + digits[:-shift]
```


```python

def digitSum(s):
    """Task
    Write a function that takes a string as input and returns the sum of the upper characters only'
    ASCII codes.

    Examples:
        digitSum("") => 0
        digitSum("abAB") => 131
        digitSum("abcCd") => 67
        digitSum("helloE") => 69
        digitSum("woArBld") => 131
        digitSum("aAaaaXa") => 153
    """
    total = 0
    for ch in s:
        if 'A' <= ch <= 'Z':
            total += ord(ch)
    return total

```


Here's the implementation for the function you described:

```python
import re

def fruit_distribution(s: str, n: int) -> int:
    """
    Given a string that represents a number of apples and oranges
    and an integer representing the total number of fruits in the basket,
    return the number of mango fruits in the basket.
    """
    # Extract numbers for apples and oranges from the string
    numbers = list(map(int, re.findall(r'\d+', s)))

    # The string should contain exactly two numbers: apples and oranges
    apples, oranges = numbers[0], numbers[1]

    # Calculate mango count
    mangoes = n - apples - oranges

    return mangoes
```


```python
def pluck(arr):
    """
    Given an array representing a branch of a tree that has non-negative integer nodes
    your task is to pluck one of the nodes and return it.
    The plucked node should be the node with the smallest even value.
    If multiple nodes with the same smallest even value are found return the node that has smallest index.

    The plucked node should be returned in a list, [ smallest_value, its index ],
    If there are no even values or the given array is empty, return [].
    """
    if not arr:
        return []

    smallest_even = None
    smallest_index = None

    for i, val in enumerate(arr):
        if val % 2 == 0:  # even value
            if smallest_even is None or val < smallest_even:
                smallest_even = val
                smallest_index = i
            elif val == smallest_even and i < smallest_index:
                smallest_index = i

    if smallest_even is None:
        return []
    return [smallest_even, smallest_index]
```


```python
def search(lst):
    """
    Returns the greatest integer that is greater than zero and has a frequency
    greater than or equal to the integer itself. If no such value exists, returns -1.
    """
    freq = {}
    for num in lst:
        freq[num] = freq.get(num, 0) + 1

    result = -1
    for num, count in freq.items():
        if num > 0 and count >= num:
            if result < num:
                result = num
    return result
```


Here's the implementation for the `strange_sort_list` function:

```python
def strange_sort_list(lst):
    """
    Given list of integers, return list in strange order.
    Strange sorting, is when you start with the minimum value,
    then maximum of the remaining integers, then minimum and so on.

    Examples:
    strange_sort_list([1, 2, 3, 4]) == [1, 4, 2, 3]
    strange_sort_list([5, 5, 5, 5]) == [5, 5, 5, 5]
    strange_sort_list([]) == []
    """
    if not lst:
        return []

    result = []
    remaining = sorted(lst)

    # We alternate between taking from the front (min) and back (max)
    # of the sorted list
    i, j = 0, len(remaining) - 1
    take_min = True

    while i <= j:
        if take_min:
            result.append(remaining[i])
            i += 1
        else:
            result.append(remaining[j])
            j -= 1
        take_min = not take_min

    return result
```


Here's the implementation using Heron's formula:

```python
import math

def triangle_area(a, b, c):
    '''
    Given the lengths of the three sides of a triangle. Return the area of
    the triangle rounded to 2 decimal points if the three sides form a valid triangle.
    Otherwise return -1
    Three sides make a valid triangle when the sum of any two sides is greater
    than the third side.
    Example:
    triangle_area(3, 4, 5) == 6.00
    triangle_area(1, 2, 10) == -1
    '''
    # Check if the sides form a valid triangle
    if a + b > c and a + c > b and b + c > a:
        # Calculate semi-perimeter
        s = (a + b + c) / 2
        # Calculate area using Heron's formula
        area = math.sqrt(s * (s - a) * (s - b) * (s - c))
        # Round to 2 decimal places
        return round(area, 2)
    else:
        return -1
```


Here's the implementation for the function you described:

```python
def will_it_fly(q, w):
    # Check if the list is a palindrome (balanced)
    if q != q[::-1]:
        return False
    # Check if the sum of elements is less than or equal to w
    if sum(q) > w:
        return False
    return True
```


```python
def smallest_change(arr):
    """
    Given an array arr of integers, find the minimum number of elements that
    need to be changed to make the array palindromic. A palindromic array is an array that
    is read the same backwards and forwards. In one change, you can change one element to any other element.

    For example:
    smallest_change([1,2,3,5,4,7,9,6]) == 4
    smallest_change([1, 2, 3, 4, 3, 2, 2]) == 1
    smallest_change([1, 2, 3, 2, 1]) == 0
    """
    n = len(arr)
    changes = 0
    for i in range(n // 2):
        if arr[i] != arr[n - 1 - i]:
            changes += 1
    return changes
```


Here's the implementation for the function you described:

```python
def total_match(lst1, lst2):
    '''
    Write a function that accepts two lists of strings and returns the list that has
    total number of chars in the all strings of the list less than the other list.

    if the two lists have the same number of chars, return the first list.

    Examples
    total_match([], []) ➞ []
    total_match(['hi', 'admin'], ['hI', 'Hi']) ➞ ['hI', 'Hi']
    total_match(['hi', 'admin'], ['hi', 'hi', 'admin', 'project']) ➞ ['hi', 'admin']
    total_match(['hi', 'admin'], ['hI', 'hi', 'hi']) ➞ ['hI', 'hi', 'hi']
    total_match(['4'], ['1', '2', '3', '4', '5']) ➞ ['4']
    '''
    total1 = sum(len(s) for s in lst1)
    total2 = sum(len(s) for s in lst2)

    if total1 <= total2:
        return lst1
    else:
        return lst2
```


```python

def is_multiply_prime(a):
    """Write a function that returns true if the given number is the multiplication of 3 prime numbers
    and false otherwise.
    Knowing that (a) is less then 100.
    Example:
    is_multiply_prime(30) == True
    30 = 2 * 3 * 5
    """
    if a < 2:
        return False

    # Find prime factors
    factors = []
    temp = a
    for p in range(2, int(a**0.5) + 1):
        while temp % p == 0:
            factors.append(p)
            temp //= p
    if temp > 1:
        factors.append(temp)

    # Check if exactly three prime factors (allowing repeats? The problem implies distinct primes)
    # The example 30 = 2*3*5 uses three distinct primes.
    # We'll require exactly three prime factors (allowing repeats? The problem implies distinct primes)
    # For safety, we check if there are exactly three factors and they are all prime.
    if len(factors) != 3:
        return False
    # All factors are already primes from the loop, but ensure no composite remains
    for f in factors:
        if f < 2:
            return False
        # Check primality (redundant but safe)
        for i in range(2, int(f**0.5) + 1):
            if f % i == 0:
                return False
    return True

```


```python

def is_simple_power(x, n):
    """Returns True if x is a simple power of n, i.e., n**int == x, else False."""
    if n == 0 or n == 1:
        # 0**positive = 0, 0**0 = 1, 1**anything = 1
        return x == n or x == 1
    if x < 1:
        return False
    # Repeatedly divide x by n
    while x >= n:
        if x % n != 0:
            return False
        x //= n
    return x == 1

```


```python
def iscube(a):
    '''
    Write a function that takes an integer a and returns True
    if this integer is a cube of some integer number.
    Note: you may assume the input is always valid.
    Examples:
    iscube(1) ==> True
    iscube(2) ==> False
    iscube(-1) ==> True
    iscube(64) ==> True
    iscube(0) ==> True
    iscube(180) ==> False
    '''
    if a < 0:
        # Handle negative numbers by working with absolute value
        a = -a
        # Check if the cube root of the absolute value is an integer
        root = round(a ** (1/3))
        return root ** 3 == a
    else:
        # For non-negative numbers
        root = round(a ** (1/3))
        return root ** 3 == a
```


```python

def hex_key(num):
    """You have been tasked to write a function that receives
    a hexadecimal number as a string and counts the number of hexadecimal
    digits that are primes (prime number, or a prime, is a natural number
    greater than 1 that is not a product of two smaller natural numbers).
    Hexadecimal digits are 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F.
    Prime numbers are 2, 3, 5, 7, 11, 13, 17,...
    So you have to determine a number of the following digits: 2, 3, 5, 7,
    B (=decimal 11), D (=decimal 13).
    Note: you may assume the input is always correct or empty string,
    and symbols A,B,C,D,E,F are always uppercase.
    Examples:
    For num = "AB" the output should be 1.
    For num = "1077E" the output should be 2.
    For num = "ABED1A33" the output should be 4.
    For num = "123456789ABCDEF0" the output should be 6.
    For num = "2020" the output should be 2.
    """
    prime_digits = {'2', '3', '5', '7', 'B', 'D'}
    count = 0
    for digit in num:
        if digit in prime_digits:
            count += 1
    return count

```


```python

def decimal_to_binary(decimal):
    """You will be given a number in decimal form and your task is to convert it to
    binary format. The function should return a string, with each character representing a binary
    number. Each character in the string will be '0' or '1'.

    There will be an extra couple of characters 'db' at the beginning and at the end of the string.
    The extra characters are there to help with the format.

    Examples:
    decimal_to_binary(15)   # returns "db1111db"
    decimal_to_binary(32)   # returns "db100000db"
    """
    if decimal == 0:
        return "db0db"
    binary_str = ""
    num = decimal
    while num > 0:
        binary_str = str(num % 2) + binary_str
        num //= 2
    return "db" + binary_str + "db"

```


```python

def is_happy(s):
    """You are given a string s.
    Your task is to check if the string is happy or not.
    A string is happy if its length is at least 3 and every 3 consecutive letters are distinct
    For example:
    is_happy(a) => False
    is_happy(aa) => False
    is_happy(abcd) => True
    is_happy(aabb) => False
    is_happy(adb) => True
    is_happy(xyy) => False
    """
    if len(s) < 3:
        return False
    for i in range(len(s) - 2):
        if s[i] == s[i+1] or s[i] == s[i+2] or s[i+1] == s[i+2]:
            return False
    return True

```


Here's the implementation of the function based on the grading table you provided:

```python
def numerical_letter_grade(grades):
    """It is the last week of the semester and the teacher has to give the grades
    to students. The teacher has been making her own algorithm for grading.
    The only problem is, she has lost the code she used for grading.
    She has given you a list of GPAs for some students and you have to write
    a function that can output a list of letter grades using the following table:
             GPA       |    Letter grade
              4.0                A+
            > 3.7                A
            > 3.3                A-
            > 3.0                B+
            > 2.7                B
            > 2.3                B-
            > 2.0                C+
            > 1.7                C
            > 1.3                C-
            > 1.0                D+
            > 0.7                D
            > 0.0                D-
              0.0                E

    Example:
    grade_equation([4.0, 3, 1.7, 2, 3.5]) ==> ['A+', 'B', 'C-', 'C', 'A-']
    """
    result = []
    for gpa in grades:
        if gpa == 4.0:
            result.append('A+')
        elif gpa > 3.7:
            result.append('A')
        elif gpa > 3.3:
            result.append('A-')
        elif gpa > 3.0:
            result.append('B+')
        elif gpa > 2.7:
            result.append('B')
        elif gpa > 2.3:
            result.append('B-')
        elif gpa > 2.0:
            result.append('C+')
        elif gpa > 1.7:
            result.append('C')
        elif gpa > 1.3:
            result.append('C-')
        elif gpa > 1.0:
            result.append('D+')
        elif gpa > 0.7:
            result.append('D')
        elif gpa > 0.0:
            result.append('D-')
        else:
            result.append('E')
    return result
```


Here's the implementation:

```python
def prime_length(string):
    """Write a function that takes a string and returns True if the string
    length is a prime number or False otherwise
    Examples
    prime_length('Hello') == True
    prime_length('abcdcba') == True
    prime_length('kittens') == True
    prime_length('orange') == False
    """
    length = len(string)
    if length < 2:
        return False
    for i in range(2, int(length ** 0.5) + 1):
        if length % i == 0:
            return False
    return True
```


```python

def starts_one_ends(n):
    """
    Given a positive integer n, return the count of the numbers of n-digit
    positive integers that start or end with 1.
    """
    if n == 1:
        # For 1-digit numbers: 1 through 9, only 1 starts or ends with 1
        return 1

    # Total n-digit numbers: 9 * 10^(n-1)
    # Numbers that start with 1: 10^(n-1)
    # Numbers that end with 1: 9 * 10^(n-2) (first digit 1-9, last digit fixed to 1)
    # Numbers that both start and end with 1: 10^(n-2) (first digit 1, last digit 1, middle free)
    # Use inclusion-exclusion:
    # count = start_with_1 + end_with_1 - both_start_and_end_1
    start_with_1 = 10 ** (n - 1)
    end_with_1 = 9 * 10 ** (n - 2)
    both = 10 ** (n - 2)
    return start_with_1 + end_with_1 - both

```


```python

def solve(N):
    """Given a positive integer N, return the total sum of its digits in binary.

    Example
        For N = 1000, the sum of digits will be 1 the output should be "1".
        For N = 150, the sum of digits will be 6 the output should be "110".
        For N = 147, the sum of digits will be 12 the output should be "1100".

    Variables:
        @N integer
             Constraints: 0 ≤ N ≤ 10000.
    Output:
         a string of binary number
    """
    digit_sum = sum(int(d) for d in str(N))
    return bin(digit_sum)[2:]

```


```python

from typing import List

def add(lst: List[int]) -> int:
    """
    Given a non-empty list of integers lst, add the even elements that are at odd indices.

    Examples:
        add([4, 2, 6, 7]) ==> 2
    """
    total = 0
    for i in range(1, len(lst), 2):  # odd indices only
        if lst[i] % 2 == 0:
            total += lst[i]
    return total

```


Here's the implementation for the `anti_shuffle` function:

```python
def anti_shuffle(s):
    """
    Write a function that takes a string and returns an ordered version of it.
    Ordered version of string, is a string where all words (separated by space)
    are replaced by a new word where all the characters arranged in
    ascending order based on ascii value.
    Note: You should keep the order of words and blank spaces in the sentence.

    For example:
    anti_shuffle('Hi') returns 'Hi'
    anti_shuffle('hello') returns 'ehllo'
    anti_shuffle('Hello World!!!') returns 'Hello !!!Wdlor'
    """
    words = s.split(' ')
    ordered_words = []
    for word in words:
        sorted_chars = sorted(word)
        ordered_words.append(''.join(sorted_chars))
    return ' '.join(ordered_words)
```


Here's the implementation for the function you described:

```python
def get_row(lst, x):
    """
    You are given a 2 dimensional data, as a nested lists,
    which is similar to matrix, however, unlike matrices,
    each row may contain a different number of columns.
    Given lst, and integer x, find integers x in the list,
    and return list of tuples, [(x1, y1), (x2, y2) ...] such that
    each tuple is a coordinate - (row, columns), starting with 0.
    Sort coordinates initially by rows in ascending order.
    Also, sort coordinates of the row by columns in descending order.

    Examples:
    get_row([
      [1,2,3,4,5,6],
      [1,2,3,4,1,6],
      [1,2,3,4,5,1]
    ], 1) == [(0, 0), (1, 4), (1, 0), (2, 5), (2, 0)]
    get_row([], 1) == []
    get_row([[], [1], [1, 2, 3]], 3) == [(2, 2)]
    """
    result = []
    for row_idx, row in enumerate(lst):
        for col_idx, value in enumerate(row):
            if value == x:
                result.append((row_idx, col_idx))

    # Sort by row ascending, then by column descending
    result.sort(key=lambda coord: (coord[0], -coord[1]))
    return result
```


```python

def sort_array(array):
    """
    Given an array of non-negative integers, return a copy of the given array after sorting,
    you will sort the given array in ascending order if the sum( first index value, last index value) is odd,
    or sort it in descending order if the sum( first index value, last index value) is even.

    Note:
    * don't change the given array.

    Examples:
    * sort_array([]) => []
    * sort_array([5]) => [5]
    * sort_array([2, 4, 3, 0, 1, 5]) => [0, 1, 2, 3, 4, 5]
    * sort_array([2, 4, 3, 0, 1, 5, 6]) => [6, 5, 4, 3, 2, 1, 0]
    """
    if len(array) == 0:
        return []

    first = array[0]
    last = array[-1]

    if (first + last) % 2 == 1:
        # sum is odd -> ascending order
        return sorted(array)
    else:
        # sum is even -> descending order
        return sorted(array, reverse=True)

```


```python

def encrypt(s):
    """Create a function encrypt that takes a string as an argument and
    returns a string encrypted with the alphabet being rotated.
    The alphabet should be rotated in a manner such that the letters
    shift down by two multiplied to two places.
    For example:
    encrypt('hi') returns 'lm'
    encrypt('asdfghjkl') returns 'ewhjklnop'
    encrypt('gf') returns 'kj'
    encrypt('et') returns 'ix'
    """
    result = []
    for ch in s:
        if 'a' <= ch <= 'z':
            # shift by 4 positions (2 * 2)
            shifted = chr((ord(ch) - ord('a') + 4) % 26 + ord('a'))
            result.append(shifted)
        elif 'A' <= ch <= 'Z':
            shifted = chr((ord(ch) - ord('A') + 4) % 26 + ord('A'))
            result.append(shifted)
        else:
            result.append(ch)
    return ''.join(result)

```


```python

def next_smallest(lst):
    """
    You are given a list of integers.
    Write a function next_smallest() that returns the 2nd smallest element of the list.
    Return None if there is no such element.

    next_smallest([1, 2, 3, 4, 5]) == 2
    next_smallest([5, 1, 4, 3, 2]) == 2
    next_smallest([]) == None
    next_smallest([1, 1]) == None
    """
    if len(lst) < 2:
        return None

    # Find the smallest and second smallest in one pass
    smallest = float('inf')
    second_smallest = float('inf')

    for num in lst:
        if num < smallest:
            second_smallest = smallest
            smallest = num
        elif num < second_smallest and num != smallest:
            second_smallest = num

    # If second_smallest was never updated, return None
    if second_smallest == float('inf'):
        return None

    return second_smallest

```


```python

def is_bored(S):
    """
    You'll be given a string of words, and your task is to count the number
    of boredoms. A boredom is a sentence that starts with the word "I".
    Sentences are delimited by '.', '?' or '!'.

    For example:
    >>> is_bored("Hello world")
    0
    >>> is_bored("The sky is blue. The sun is shining. I love this weather")
    1
    """
    import re
    # Split the string into sentences based on '.', '?', or '!'
    sentences = re.split(r'[.?!]', S)
    count = 0
    for sentence in sentences:
        # Remove leading/trailing whitespace
        stripped = sentence.strip()
        if stripped:
            # Check if the first word is "I"
            first_word = stripped.split()[0] if stripped.split() else ''
            if first_word == "I":
                count += 1
    return count

```


Here's the implementation for the function you described:

```python
def any_int(x, y, z):
    '''
    Create a function that takes 3 numbers.
    Returns true if one of the numbers is equal to the sum of the other two, and all numbers are integers.
    Returns false in any other cases.

    Examples
    any_int(5, 2, 7) ➞ True

    any_int(3, 2, 2) ➞ False

    any_int(3, -2, 1) ➞ True

    any_int(3.6, -2.2, 2) ➞ False
    '''
    # Check if all numbers are integers
    if not all(isinstance(n, int) for n in (x, y, z)):
        return False

    # Check if one number equals the sum of the other two
    return (x == y + z) or (y == x + z) or (z == x + y)
```


Here's the implementation for the `encode` function:

```python
def encode(message):
    """
    Write a function that takes a message, and encodes in such a
    way that it swaps case of all letters, replaces all vowels in
    the message with the letter that appears 2 places ahead of that
    vowel in the english alphabet.
    Assume only letters.

    Examples:
    >>> encode('test')
    'TGST'
    >>> encode('This is a message')
    'tHKS KS C MGSSCGG'
    """
    vowels = 'aeiouAEIOU'
    result = []

    for char in message:
        if char in vowels:
            # Find the vowel and shift it by 2 in the alphabet
            if char.islower():
                shifted = chr((ord(char) - ord('a') + 2) % 26 + ord('a'))
            else:
                shifted = chr((ord(char) - ord('A') + 2) % 26 + ord('A'))
            # Swap case after shifting
            result.append(shifted.swapcase())
        else:
            # For non-vowels, just swap case
            result.append(char.swapcase())

    return ''.join(result)
```


```python

def skjkasdkd(lst):
    def is_prime(n):
        if n < 2:
            return False
        if n == 2:
            return True
        if n % 2 == 0:
            return False
        i = 3
        while i * i <= n:
            if n % i == 0:
                return False
            i += 2
        return True

    largest_prime = None
    for num in lst:
        if is_prime(num):
            if largest_prime is None or num > largest_prime:
                largest_prime = num

    if largest_prime is None:
        return 0

    return sum(int(d) for d in str(largest_prime))

```


```python

def check_dict_case(dict):
    """
    Given a dictionary, return True if all keys are strings in lower
    case or all keys are strings in upper case, else return False.
    The function should return False is the given dictionary is empty.
    Examples:
    check_dict_case({"a":"apple", "b":"banana"}) should return True.
    check_dict_case({"a":"apple", "A":"banana", "B":"banana"}) should return False.
    check_dict_case({"a":"apple", 8:"banana", "a":"apple"}) should return False.
    check_dict_case({"Name":"John", "Age":"36", "City":"Houston"}) should return False.
    check_dict_case({"STATE":"NC", "ZIP":"12345" }) should return True.
    """
    if not dict:
        return False

    lower_case = True
    upper_case = True

    for key in dict:
        if not isinstance(key, str):
            lower_case = False
            upper_case = False
            break
        if not key.islower():
            lower_case = False
        if not key.isupper():
            upper_case = False
        # If both are false, we can break early
        if not lower_case and not upper_case:
            break

    return lower_case or upper_case

```


```python

def count_up_to(n):
    """Implement a function that takes an non-negative integer and returns an array of the first n
    integers that are prime numbers and less than n.
    for example:
    count_up_to(5) => [2,3]
    count_up_to(11) => [2,3,5,7]
    count_up_to(0) => []
    count_up_to(20) => [2,3,5,7,11,13,17,19]
    count_up_to(1) => []
    count_up_to(18) => [2,3,5,7,11,13,17]
    """
    def is_prime(num):
        if num < 2:
            return False
        for i in range(2, int(num**0.5) + 1):
            if num % i == 0:
                return False
        return True

    result = []
    for candidate in range(2, n):
        if is_prime(candidate):
            result.append(candidate)
    return result

```


```python
def multiply(a, b):
    """Complete the function that takes two integers and returns
    the product of their unit digits.
    Assume the input is always valid.
    Examples:
    multiply(148, 412) should return 16.
    multiply(19, 28) should return 72.
    multiply(2020, 1851) should return 0.
    multiply(14,-15) should return 20.
    """
    unit_a = abs(a) % 10
    unit_b = abs(b) % 10
    return unit_a * unit_b
```


```python

def count_upper(s):
    """
    Given a string s, count the number of uppercase vowels in even indices.

    For example:
    count_upper('aBCdEf') returns 1
    count_upper('abcdefg') returns 0
    count_upper('dBBE') returns 0
    """
    vowels = set('AEIOU')
    count = 0
    for i, ch in enumerate(s):
        if i % 2 == 0 and ch in vowels:
            count += 1
    return count

```


Here's the implementation for the function you described:

```python
def closest_integer(value):
    '''
    Create a function that takes a value (string) representing a number
    and returns the closest integer to it. If the number is equidistant
    from two integers, round it away from zero.

    Examples
    >>> closest_integer("10")
    10
    >>> closest_integer("15.3")
    15

    Note:
    Rounding away from zero means that if the given number is equidistant
    from two integers, the one you should return is the one that is the
    farthest from zero. For example closest_integer("14.5") should
    return 15 and closest_integer("-14.5") should return -15.
    '''
    from decimal import Decimal, ROUND_HALF_UP

    num = Decimal(value)
    rounded = num.to_integral_value(rounding=ROUND_HALF_UP)
    return int(rounded)
```


```python

def make_a_pile(n):
    """
    Given a positive integer n, you have to make a pile of n levels of stones.
    The first level has n stones.
    The number of stones in the next level is:
        - the next odd number if n is odd.
        - the next even number if n is even.
    Return the number of stones in each level in a list, where element at index
    i represents the number of stones in the level (i+1).

    Examples:
    >>> make_a_pile(3)
    [3, 5, 7]
    """
    result = []
    current = n
    for _ in range(n):
        result.append(current)
        if n % 2 == 1:
            current += 2
        else:
            current += 2
    return result

```


Here's the implementation for the function:

```python
def words_string(s):
    """
    You will be given a string of words separated by commas or spaces. Your task is
    to split the string into words and return an array of the words.

    For example:
    words_string("Hi, my name is John") == ["Hi", "my", "name", "is", "John"]
    words_string("One, two, three, four, five, six") == ["One", "two", "three", "four", "five", "six"]
    """
    import re
    return re.split(r'[,\s]+', s.strip())
```


```python

def choose_num(x, y):
    """This function takes two positive numbers x and y and returns the
    biggest even integer number that is in the range [x, y] inclusive. If
    there's no such number, then the function should return -1.

    For example:
    choose_num(12, 15) = 14
    choose_num(13, 12) = -1
    """
    if x > y:
        return -1
    # Start from the largest number in range and go downwards
    for num in range(y, x - 1, -1):
        if num % 2 == 0:
            return num
    return -1

```


```python

def rounded_avg(n, m):
    if n > m:
        return -1
    total = 0
    count = 0
    for i in range(n, m + 1):
        total += i
        count += 1
    avg = total / count
    rounded = round(avg)
    return bin(rounded)

```


```python
def unique_digits(x):
    """Given a list of positive integers x. return a sorted list of all
    elements that hasn't any even digit.

    Note: Returned list should be sorted in increasing order.

    For example:
    >>> unique_digits([15, 33, 1422, 1])
    [1, 15, 33]
    >>> unique_digits([152, 323, 1422, 10])
    []
    """
    result = []
    for num in x:
        if all(int(d) % 2 != 0 for d in str(num)):
            result.append(num)
    return sorted(result)
```


Here's the implementation for the function you described:

```python
def by_length(arr):
    """
    Given an array of integers, sort the integers that are between 1 and 9 inclusive,
    reverse the resulting array, and then replace each digit by its corresponding name from
    "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine".
    """
    # Filter numbers between 1 and 9 inclusive
    filtered = [x for x in arr if 1 <= x <= 9]

    # Sort the filtered list
    filtered.sort()

    # Reverse the sorted list
    filtered.reverse()

    # Map numbers to their word names
    num_to_word = {
        1: "One",
        2: "Two",
        3: "Three",
        4: "Four",
        5: "Five",
        6: "Six",
        7: "Seven",
        8: "Eight",
        9: "Nine"
    }

    # Convert each number to its word representation
    result = [num_to_word[num] for num in filtered]

    return result
```


```python

def f(n):
    result = []
    for i in range(1, n + 1):
        if i % 2 == 0:
            # factorial of i
            fact = 1
            for j in range(1, i + 1):
                fact *= j
            result.append(fact)
        else:
            # sum of numbers from 1 to i
            total = 0
            for j in range(1, i + 1):
                total += j
            result.append(total)
    return result

```


```python

def even_odd_palindrome(n):
    """
    Given a positive integer n, return a tuple that has the number of even and odd
    integer palindromes that fall within the range(1, n), inclusive.
    """
    even_count = 0
    odd_count = 0
    for num in range(1, n + 1):
        s = str(num)
        if s == s[::-1]:
            if num % 2 == 0:
                even_count += 1
            else:
                odd_count += 1
    return (even_count, odd_count)

```


Traceback (most recent call last):
  File "<string>", line 48, in <module>
    check(count_nums)
    ~~~~~^^^^^^^^^^^^
  File "<string>", line 40, in check
    assert candidate([12, 23, 34, -45, -56, 0]) == 5
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AssertionError

```python

def count_nums(arr):
    """
    Returns the number of elements in the array whose sum of signed digits > 0.
    For negative numbers, the first digit is treated as negative.
    """
    def sum_signed_digits(n):
        if n == 0:
            return 0
        sign = 1 if n >= 0 else -1
        n = abs(n)
        total = 0
        first = True
        while n > 0:
            digit = n % 10
            if first:
                total += sign * digit
                first = False
            else:
                total += digit
            n //= 10
        return total

    count = 0
    for num in arr:
        if sum_signed_digits(num) > 0:
            count += 1
    return count

```


```python

def move_one_ball(arr):
    """
    Determines if the array can be sorted in non-decreasing order by performing
    any number of right shift operations.
    """
    if not arr:
        return True

    n = len(arr)
    # Find the smallest element and its index
    min_val = min(arr)
    min_index = arr.index(min_val)

    # Check if the array can be rotated to become sorted
    # Starting from min_index, the array should be non-decreasing
    # and wrap around to the beginning without breaking order

    # Check the segment from min_index to end
    for i in range(min_index, n - 1):
        if arr[i] > arr[i + 1]:
            return False

    # Check the segment from start to min_index (wrap-around)
    # The last element before wrap must be <= first element after wrap
    if arr[-1] > arr[0]:
        return False

    # Check the segment from start to min_index - 1
    for i in range(0, min_index - 1):
        if arr[i] > arr[i + 1]:
            return False

    return True

```


```python
def exchange(lst1, lst2):
    """In this problem, you will implement a function that takes two lists of numbers,
    and determines whether it is possible to perform an exchange of elements
    between them to make lst1 a list of only even numbers.
    There is no limit on the number of exchanged elements between lst1 and lst2.
    If it is possible to exchange elements between the lst1 and lst2 to make
    all the elements of lst1 to be even, return "YES".
    Otherwise, return "NO".
    For example:
    exchange([1, 2, 3, 4], [1, 2, 3, 4]) => "YES"
    exchange([1, 2, 3, 4], [1, 5, 3, 4]) => "NO"
    It is assumed that the input lists will be non-empty.
    """
    odd_in_lst1 = [x for x in lst1 if x % 2 != 0]
    even_in_lst2 = [x for x in lst2 if x % 2 == 0]

    if len(odd_in_lst1) <= len(even_in_lst2):
        return "YES"
    else:
        return "NO"
```


Here's the implementation for the `histogram` function:

```python
def histogram(test):
    """Given a string representing a space separated lowercase letters, return a dictionary
    of the letter with the most repetition and containing the corresponding count.
    If several letters have the same occurrence, return all of them.

    Example:
    histogram('a b c') == {'a': 1, 'b': 1, 'c': 1}
    histogram('a b b a') == {'a': 2, 'b': 2}
    histogram('a b c a b') == {'a': 2, 'b': 2}
    histogram('b b b b a') == {'b': 4}
    histogram('') == {}

    """
    if not test.strip():
        return {}

    words = test.split()
    freq = {}
    for w in words:
        freq[w] = freq.get(w, 0) + 1

    max_count = max(freq.values())
    result = {k: v for k, v in freq.items() if v == max_count}
    return result
```


Here's the implementation for the function:

```python
def reverse_delete(s, c):
    # Remove characters from s that are present in c
    result = ''.join(ch for ch in s if ch not in c)
    # Check if the result string is a palindrome
    is_palindrome = result == result[::-1]
    return (result, is_palindrome)
```


Here's the implementation for the function you described:

```python
def odd_count(lst):
    """Given a list of strings, where each string consists of only digits, return a list.
    Each element i of the output should be "the number of odd elements in the
    string i of the input." where all the i's should be replaced by the number
    of odd digits in the i'th string of the input.

    >>> odd_count(['1234567'])
    ["the number of odd elements 4n the str4ng 4 of the 4nput."]
    >>> odd_count(['3',"11111111"])
    ["the number of odd elements 1n the str1ng 1 of the 1nput.",
     "the number of odd elements 8n the str8ng 8 of the 8nput."]
    """
    result = []
    for s in lst:
        count = sum(1 for ch in s if int(ch) % 2 != 0)
        result.append(
            f"the number of odd elements {count}n the str{count}ng {count} of the {count}nput."
        )
    return result
```


```python

def minSubArraySum(nums):
    """
    Given an array of integers nums, find the minimum sum of any non-empty sub-array
    of nums.
    Example
    minSubArraySum([2, 3, 4, 1, 2, 4]) == 1
    minSubArraySum([-1, -2, -3]) == -6
    """
    min_ending_here = nums[0]
    min_so_far = nums[0]
    for i in range(1, len(nums)):
        min_ending_here = min(nums[i], min_ending_here + nums[i])
        min_so_far = min(min_so_far, min_ending_here)
    return min_so_far

```


Traceback (most recent call last):
  File "<string>", line 63, in <module>
    check(max_fill)
    ~~~~~^^^^^^^^^^
  File "<string>", line 60, in check
    assert candidate([[1,1,1,1], [1,1,1,1]], 9) == 2, "Error"
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AssertionError: Error

```python

def max_fill(grid, capacity):
    import math
    """
    You are given a rectangular grid of wells. Each row represents a single well,
    and each 1 in a row represents a single unit of water.
    Each well has a corresponding bucket that can be used to extract water from it,
    and all buckets have the same capacity.
    Your task is to use the buckets to empty the wells.
    Output the number of times you need to lower the buckets.

    Example 1:
        Input:
            grid : [[0,0,1,0], [0,1,0,0], [1,1,1,1]]
            bucket_capacity : 1
        Output: 6

    Example 2:
        Input:
            grid : [[0,0,1,1], [0,0,0,0], [1,1,1,1], [0,1,1,1]]
            bucket_capacity : 2
        Output: 5

    Example 3:
        Input:
            grid : [[0,0,0], [0,0,0]]
            bucket_capacity : 5
        Output: 0

    Constraints:
        * all wells have the same length
        * 1 <= grid.length <= 10^2
        * 1 <= grid[:,1].length <= 10^2
        * grid[i][j] -> 0 | 1
        * 1 <= capacity <= 10
    """
    total_water = 0
    for row in grid:
        total_water += sum(row)
    if total_water == 0:
        return 0
    # Each bucket can hold 'capacity' units, and each lowering extracts one bucketful.
    # Number of bucket lowerings = ceil(total_water / capacity)
    return math.ceil(total_water / capacity)

```


```python

def sort_array(arr):
    """
    Sorts an array of integers (including negative) by the number of 1s in their
    binary representation (ascending), and then by decimal value (ascending).
    """
    def count_bits(n):
        # Count ones in binary representation for both positive and negative numbers
        # For negative numbers, we consider the two's complement representation
        # using a fixed-width 32-bit interpretation.
        if n >= 0:
            return bin(n).count('1')
        else:
            # For negative numbers, treat as unsigned 32-bit
            return bin(n & 0xFFFFFFFF).count('1')

    return sorted(arr, key=lambda x: (count_bits(x), x))

```


Here's the implementation for the function you described:

```python
def select_words(s, n):
    """Given a string s and a natural number n, you have been tasked to implement
    a function that returns a list of all words from string s that contain exactly
    n consonants, in order these words appear in the string s.
    If the string s is empty then the function should return an empty list.
    Note: you may assume the input string contains only letters and spaces.
    Examples:
    select_words("Mary had a little lamb", 4) ==> ["little"]
    select_words("Mary had a little lamb", 3) ==> ["Mary", "lamb"]
    select_words("simple white space", 2) ==> []
    select_words("Hello world", 4) ==> ["world"]
    select_words("Uncle sam", 3) ==> ["Uncle"]
    """
    vowels = set("aeiouAEIOU")
    result = []
    words = s.split()
    for word in words:
        consonant_count = sum(1 for ch in word if ch.isalpha() and ch not in vowels)
        if consonant_count == n:
            result.append(word)
    return result
```


Here's the implementation for the function you described:

```python
def get_closest_vowel(word):
    vowels = set("aeiouAEIOU")

    # Find the rightmost vowel that is between two consonants
    for i in range(len(word) - 2, 0, -1):
        if word[i] in vowels:
            if word[i-1].isalpha() and word[i-1] not in vowels and word[i+1].isalpha() and word[i+1] not in vowels:
                return word[i]

    return ""
```


Here's the implementation for the function you described:

```python
def match_parens(lst):
    '''
    You are given a list of two strings, both strings consist of open
    parentheses '(' or close parentheses ')' only.
    Your job is to check if it is possible to concatenate the two strings in
    some order, that the resulting string will be good.
    A string S is considered to be good if and only if all parentheses in S
    are balanced. For example: the string '(())()' is good, while the string
    '())' is not.
    Return 'Yes' if there's a way to make a good string, and return 'No' otherwise.

    Examples:
    match_parens(['()(', ')']) == 'Yes'
    match_parens([')', ')']) == 'No'
    '''
    def is_balanced(s):
        balance = 0
        for ch in s:
            if ch == '(':
                balance += 1
            else:
                balance -= 1
            if balance < 0:
                return False
        return balance == 0

    # Try both possible concatenations
    if is_balanced(lst[0] + lst[1]) or is_balanced(lst[1] + lst[0]):
        return 'Yes'
    return 'No'
```


```python

import heapq

def maximum(arr, k):
    """
    Given an array arr of integers and a positive integer k, return a sorted list
    of length k with the maximum k numbers in arr.
    """
    if k == 0:
        return []
    # Use a min-heap of size k to keep the k largest elements
    heap = arr[:k]
    heapq.heapify(heap)
    for num in arr[k:]:
        if num > heap[0]:
            heapq.heapreplace(heap, num)
    # Return the heap sorted in ascending order (which matches the required output)
    return sorted(heap)

```


```python
def solution(lst):
    """
    Given a non-empty list of integers, return the sum of all of the odd elements
    that are in even positions.

    Positions are 0-indexed, so even positions are indices 0, 2, 4, ...

    Examples:
    solution([5, 8, 7, 1]) ==> 12
    solution([3, 3, 3, 3, 3]) ==> 9
    solution([30, 13, 24, 321]) ==> 0
    """
    total = 0
    for i in range(len(lst)):
        if i % 2 == 0 and lst[i] % 2 != 0:
            total += lst[i]
    return total
```


```python

def add_elements(arr, k):
    """
    Given a non-empty array of integers arr and an integer k, return
    the sum of the elements with at most two digits from the first k elements of arr.
    """
    total = 0
    for i in range(k):
        if 0 <= arr[i] < 100 or (-100 < arr[i] < 0 and arr[i] != -100):
            # Check if the number has at most two digits (including negative numbers)
            # Positive: 0 to 99 inclusive (1 or 2 digits)
            # Negative: -1 to -99 inclusive (1 or 2 digits, excluding -100 which has 3 digits)
            total += arr[i]
    return total

```


Here's the implementation of the function:

```python
def get_odd_collatz(n):
    """
    Given a positive integer n, return a sorted list that has the odd numbers in collatz sequence.
    """
    sequence = []
    while n != 1:
        if n % 2 == 1:
            sequence.append(n)
        if n % 2 == 0:
            n //= 2
        else:
            n = 3 * n + 1
    sequence.append(1)  # include the final 1
    return sorted(sequence)
```


Here's the complete implementation for the `valid_date` function:

```python
import re

def valid_date(date):
    """You have to write a function which validates a given date string and
    returns True if the date is valid otherwise False.
    The date is valid if all of the following rules are satisfied:
    1. The date string is not empty.
    2. The number of days is not less than 1 or higher than 31 days for months 1,3,5,7,8,10,12. And the number of days is not less than 1 or higher than 30 days for months 4,6,9,11. And, the number of days is not less than 1 or higher than 29 for the month 2.
    3. The months should not be less than 1 or higher than 12.
    4. The date should be in the format: mm-dd-yyyy

    for example:
    valid_date('03-11-2000') => True

    valid_date('15-01-2012') => False

    valid_date('04-0-2040') => False

    valid_date('06-04-2020') => True

    valid_date('06/04/2020') => False
    """
    if not date:
        return False

    # Check format: mm-dd-yyyy
    if not re.match(r'^\d{2}-\d{2}-\d{4}$', date):
        return False

    parts = date.split('-')
    month = int(parts[0])
    day = int(parts[1])
    year = int(parts[2])

    # Month validation
    if month < 1 or month > 12:
        return False

    # Day validation based on month
    days_in_month = {
        1: 31, 2: 29, 3: 31, 4: 30, 5: 31, 6: 30,
        7: 31, 8: 31, 9: 30, 10: 31, 11: 30, 12: 31
    }

    if day < 1 or day > days_in_month[month]:
        return False

    return True
```


Here's the implementation for the function you described:

```python
def split_words(txt):
    """
    Given a string of words, return a list of words split on whitespace, if no whitespaces exists in the text you
    should split on commas ',' if no commas exists you should return the number of lower-case letters with odd order in the
    alphabet, ord('a') = 0, ord('b') = 1, ... ord('z') = 25
    Examples
    split_words("Hello world!") ➞ ["Hello", "world!"]
    split_words("Hello,world!") ➞ ["Hello", "world!"]
    split_words("abcdef") == 3
    """
    if ' ' in txt:
        return txt.split()
    if ',' in txt:
        return txt.split(',')

    count = 0
    for ch in txt:
        if ch.islower():
            if (ord(ch) - ord('a')) % 2 != 0:
                count += 1
    return count
```


Traceback (most recent call last):
  File "<string>", line 46, in <module>
    check(is_sorted)
    ~~~~~^^^^^^^^^^^
  File "<string>", line 42, in check
    assert candidate([1, 2, 2, 3, 3, 4]) == True, "This prints if this assert fails 7 (good for debugging!)"
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AssertionError: This prints if this assert fails 7 (good for debugging!)

Here's the implementation for the function you described:

```python
def is_sorted(lst):
    """
    Given a list of numbers, return whether or not they are sorted
    in ascending order. If list has more than 1 duplicate of the same
    number, return False. Assume no negative numbers and only integers.
    """
    if len(lst) <= 1:
        return True

    for i in range(1, len(lst)):
        if lst[i] < lst[i - 1]:
            return False

    # Check for more than one duplicate of any number
    seen = set()
    for num in lst:
        if num in seen:
            return False
        seen.add(num)

    return True
```


Traceback (most recent call last):
  File "<string>", line 41, in <module>
    check(intersection)
    ~~~~~^^^^^^^^^^^^^^
  File "<string>", line 30, in check
    assert candidate((-1, 1), (0, 4)) == "NO"
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AssertionError

Here's the implementation:

```python
def intersection(interval1, interval2):
    # Determine the intersection range
    start = max(interval1[0], interval2[0])
    end = min(interval1[1], interval2[1])

    # If no intersection
    if start > end:
        return "NO"

    # Length of intersection
    length = end - start + 1

    # Check if length is prime
    if length < 2:
        return "NO"

    for i in range(2, int(length ** 0.5) + 1):
        if length % i == 0:
            return "NO"

    return "YES"
```


```python
def prod_signs(arr):
    """
    You are given an array arr of integers and you need to return
    sum of magnitudes of integers multiplied by product of all signs
    of each number in the array, represented by 1, -1 or 0.
    Note: return None for empty arr.

    Example:
    >>> prod_signs([1, 2, 2, -4]) == -9
    >>> prod_signs([0, 1]) == 0
    >>> prod_signs([]) == None
    """
    if not arr:
        return None

    sum_magnitudes = 0
    sign_product = 1

    for num in arr:
        sum_magnitudes += abs(num)
        if num > 0:
            sign_product *= 1
        elif num < 0:
            sign_product *= -1
        else:
            sign_product *= 0

    return sum_magnitudes * sign_product
```


```python

import heapq

def minPath(grid, k):
    n = len(grid)
    # Map each value to its coordinates for quick lookup
    value_to_pos = {}
    for i in range(n):
        for j in range(n):
            value_to_pos[grid[i][j]] = (i, j)

    # Directions: up, down, left, right
    dirs = [(-1,0), (1,0), (0,-1), (0,1)]

    # Priority queue: (path_tuple, current_cell_value, row, col, length)
    # We use path tuple for lexicographic ordering
    start = (1,)
    pq = []
    # Start from the smallest value cell
    smallest_val = 1
    r, c = value_to_pos[smallest_val]
    heapq.heappush(pq, (start, smallest_val, r, c, 1))

    while pq:
        path, last_val, r, c, length = heapq.heappop(pq)
        if length == k:
            return list(path)
        # Extend path
        for dr, dc in dirs:
            nr, nc = r + dr, c + dc
            if 0 <= nr < n and 0 <= nc < n:
                next_val = grid[nr][nc]
                new_path = path + (next_val,)
                heapq.heappush(pq, (new_path, next_val, nr, nc, length + 1))
    # Should never reach here because answer is guaranteed
    return []

```


Here's the implementation of the `tri` function based on the given recurrence:

```python
def tri(n):
    if n < 0:
        raise ValueError("n must be non-negative")

    # Base cases
    if n == 0:
        return [1]

    result = [1]  # tri(0) is defined as 1 for the list start
    # We'll compute up to index n
    # tri(1) = 3
    if n >= 1:
        result.append(3)

    for i in range(2, n + 1):
        if i % 2 == 0:  # even
            val = 1 + i // 2
        else:  # odd
            # tri(i) = tri(i-1) + tri(i-2) + tri(i+1)
            # But tri(i+1) might not be computed yet, so we need to compute it first
            # Actually, for odd i, tri(i+1) is even, so we can compute it directly
            # tri(i+1) = 1 + (i+1) // 2
            val = result[i - 1] + result[i - 2] + (1 + (i + 1) // 2)
        result.append(val)

    return result
```


```python

def digits(n):
    """Given a positive integer n, return the product of the odd digits.
    Return 0 if all digits are even.
    For example:
    digits(1)  == 1
    digits(4)  == 0
    digits(235) == 15
    """
    product = 1
    found_odd = False
    while n > 0:
        digit = n % 10
        if digit % 2 == 1:
            product *= digit
            found_odd = True
        n //= 10
    return product if found_odd else 0

```


Traceback (most recent call last):
  File "<string>", line 53, in <module>
    check(is_nested)
    ~~~~~^^^^^^^^^^^
  File "<string>", line 36, in check
    assert candidate('[]]]]]]][[[[[]') == False
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AssertionError

Here's the implementation for the function you described:

```python

def is_nested(string):
    '''
    Create a function that takes a string as input which contains only square brackets.
    The function should return True if and only if there is a valid subsequence of brackets
    where at least one bracket in the subsequence is nested.

    is_nested('[[]]') ➞ True
    is_nested('[]]]]]]][[[[[]') ➞ False
    is_nested('[][]') ➞ False
    is_nested('[]') ➞ False
    is_nested('[[][]]') ➞ True
    is_nested('[[]][[') ➞ True
    '''
    # Track the depth of valid bracket subsequences
    depth = 0
    max_depth = 0

    for char in string:
        if char == '[':
            depth += 1
            max_depth = max(max_depth, depth)
        elif char == ']':
            if depth > 0:
                depth -= 1

    # A valid subsequence with nesting means we had at least depth 2 at some point
    return max_depth >= 2

```


```python

import math

def sum_squares(lst):
    """
    Returns the sum of squared numbers in the given list,
    after rounding each element to the upper int (ceiling).
    """
    total = 0
    for x in lst:
        ceil_val = math.ceil(x)
        total += ceil_val * ceil_val
    return total

```


Here’s the implementation for the function you described:

```python
def check_if_last_char_is_a_letter(txt):
    if not txt or txt[-1] == ' ':
        return False
    last_char = txt[-1]
    if not last_char.isalpha():
        return False
    # Check if the last character is part of a word by ensuring
    # it is not preceded by a non-space character that would make it part of a word.
    # Actually, we need to check if it's the last character of a word,
    # meaning it should be preceded by a space or be the start of the string.
    # But also it must not be followed by any non-space (which is impossible since it's last).
    # So we check that the character before it (if exists) is a space.
    if len(txt) > 1 and txt[-2] != ' ':
        return False
    return True
```


```python
def can_arrange(arr):
    """Create a function which returns the largest index of an element which
    is not greater than or equal to the element immediately preceding it. If
    no such element exists then return -1. The given array will not contain
    duplicate values.

    Examples:
    can_arrange([1,2,4,3,5]) = 3
    can_arrange([1,2,3]) = -1
    """
    if len(arr) <= 1:
        return -1

    result = -1
    for i in range(1, len(arr)):
        if arr[i] < arr[i-1]:
            result = i
    return result
```


```python

def largest_smallest_integers(lst):
    '''
    Create a function that returns a tuple (a, b), where 'a' is
    the largest of negative integers, and 'b' is the smallest
    of positive integers in a list.
    If there is no negative or positive integers, return them as None.

    Examples:
    largest_smallest_integers([2, 4, 1, 3, 5, 7]) == (None, 1)
    largest_smallest_integers([]) == (None, None)
    largest_smallest_integers([0]) == (None, None)
    '''
    largest_negative = None
    smallest_positive = None

    for num in lst:
        if num < 0:
            if largest_negative is None or num > largest_negative:
                largest_negative = num
        elif num > 0:
            if smallest_positive is None or num < smallest_positive:
                smallest_positive = num

    return (largest_negative, smallest_positive)

```


Here's the implementation for the function you described:

```python
def compare_one(a, b):
    """
    Create a function that takes integers, floats, or strings representing
    real numbers, and returns the larger variable in its given variable type.
    Return None if the values are equal.
    Note: If a real number is represented as a string, the floating point might be . or ,

    compare_one(1, 2.5) ➞ 2.5
    compare_one(1, "2,3") ➞ "2,3"
    compare_one("5,1", "6") ➞ "6"
    compare_one("1", 1) ➞ None
    """
    def to_number(val):
        if isinstance(val, (int, float)):
            return float(val)
        if isinstance(val, str):
            # Replace comma with dot for parsing
            normalized = val.replace(',', '.')
            return float(normalized)
        return None

    num_a = to_number(a)
    num_b = to_number(b)

    if num_a is None or num_b is None:
        return None

    if abs(num_a - num_b) < 1e-12:
        return None

    if num_a > num_b:
        return a
    else:
        return b
```


Here's the implementation:

```python
def is_equal_to_sum_even(n):
    """Evaluate whether the given number n can be written as the sum of exactly 4 positive even numbers
    Example
    is_equal_to_sum_even(4) == False
    is_equal_to_sum_even(6) == False
    is_equal_to_sum_even(8) == True
    """
    # The smallest sum of 4 positive even numbers is 2+2+2+2 = 8
    # Any number >= 8 that is even can be written as such a sum
    # because we can adjust the four even numbers (2,2,2, n-6) if n-6 is even and >= 2
    # More generally: n must be >= 8 and even
    return n >= 8 and n % 2 == 0
```


```python
def special_factorial(n):
    """The Brazilian factorial is defined as:
    brazilian_factorial(n) = n! * (n-1)! * (n-2)! * ... * 1!
    where n > 0

    For example:
    >>> special_factorial(4)
    288

    The function will receive an integer as input and should return the special
    factorial of this integer.
    """
    # Compute factorials iteratively and multiply them
    result = 1
    current_factorial = 1
    for i in range(1, n + 1):
        current_factorial *= i  # i! = (i-1)! * i
        result *= current_factorial
    return result
```


Here's the implementation for the `fix_spaces` function:

```python
def fix_spaces(text):
    """
    Given a string text, replace all spaces in it with underscores,
    and if a string has more than 2 consecutive spaces,
    then replace all consecutive spaces with -

    fix_spaces("Example") == "Example"
    fix_spaces("Example 1") == "Example_1"
    fix_spaces(" Example 2") == "_Example_2"
    fix_spaces(" Example   3") == "_Example-3"
    """
    result = []
    i = 0
    while i < len(text):
        if text[i] == ' ':
            # Count consecutive spaces
            count = 0
            while i < len(text) and text[i] == ' ':
                count += 1
                i += 1
            if count > 2:
                result.append('-')
            else:
                for _ in range(count):
                    result.append('_')
        else:
            result.append(text[i])
            i += 1
    return ''.join(result)
```


```python

import re

def file_name_check(file_name):
    """Create a function which takes a string representing a file's name, and returns
    'Yes' if the the file's name is valid, and returns 'No' otherwise.
    A file's name is considered to be valid if and only if all the following conditions
    are met:
    - There should not be more than three digits ('0'-'9') in the file's name.
    - The file's name contains exactly one dot '.'
    - The substring before the dot should not be empty, and it starts with a letter from
    the latin alphapet ('a'-'z' and 'A'-'Z').
    - The substring after the dot should be one of these: ['txt', 'exe', 'dll']
    Examples:
    file_name_check("example.txt") # => 'Yes'
    file_name_check("1example.dll") # => 'No' (the name should start with a latin alphapet letter)
    """
    if file_name.count('.') != 1:
        return 'No'

    parts = file_name.split('.')
    before_dot = parts[0]
    after_dot = parts[1]

    if not before_dot:
        return 'No'

    if not before_dot[0].isalpha():
        return 'No'

    if after_dot not in ['txt', 'exe', 'dll']:
        return 'No'

    digit_count = sum(1 for ch in file_name if ch.isdigit())
    if digit_count > 3:
        return 'No'

    return 'Yes'

```


Here's the implementation of the function based on your specification:

```python
def sum_squares(lst):
    """
    This function will take a list of integers. For all entries in the list, the function shall square the integer entry if its index is a
    multiple of 3 and will cube the integer entry if its index is a multiple of 4 and not a multiple of 3. The function will not
    change the entries in the list whose indexes are not a multiple of 3 or 4. The function shall then return the sum of all entries.

    Examples:
    For lst = [1,2,3] the output should be 6
    For lst = []  the output should be 0
    For lst = [-1,-5,2,-1,-5]  the output should be -126
    """
    total = 0
    for i, val in enumerate(lst):
        if i % 3 == 0:
            total += val * val
        elif i % 4 == 0:
            total += val * val * val
        else:
            total += val
    return total
```


```python

def words_in_sentence(sentence):
    def is_prime(n):
        if n <= 1:
            return False
        if n <= 3:
            return True
        if n % 2 == 0 or n % 3 == 0:
            return False
        i = 5
        while i * i <= n:
            if n % i == 0 or n % (i + 2) == 0:
                return False
            i += 6
        return True

    words = sentence.split()
    result_words = [word for word in words if is_prime(len(word))]
    return " ".join(result_words)

```


Here's the implementation for the `simplify` function:

```python
from fractions import Fraction

def simplify(x, n):
    """Your task is to implement a function that will simplify the expression
    x * n. The function returns True if x * n evaluates to a whole number and False
    otherwise. Both x and n, are string representation of a fraction, and have the following format,
    <numerator>/<denominator> where both numerator and denominator are positive whole numbers.

    You can assume that x, and n are valid fractions, and do not have zero as denominator.

    simplify("1/5", "5/1") = True
    simplify("1/6", "2/1") = False
    simplify("7/10", "10/2") = False
    """
    frac_x = Fraction(x)
    frac_n = Fraction(n)
    product = frac_x * frac_n
    return product.denominator == 1
```


```python
def order_by_points(nums):
    """
    Write a function which sorts the given list of integers
    in ascending order according to the sum of their digits.
    Note: if there are several items with similar sum of their digits,
    order them based on their index in original list.

    For example:
    >>> order_by_points([1, 11, -1, -11, -12]) == [-1, -11, 1, -12, 11]
    >>> order_by_points([]) == []
    """
    def digit_sum(n):
        # Compute sum of digits, ignoring sign
        total = 0
        n = abs(n)
        while n > 0:
            total += n % 10
            n //= 10
        return total

    # Create list of (digit_sum, original_index, value) tuples
    decorated = [(digit_sum(nums[i]), i, nums[i]) for i in range(len(nums))]

    # Sort by digit_sum first, then by original index
    decorated.sort(key=lambda x: (x[0], x[1]))

    # Extract values in sorted order
    return [x[2] for x in decorated]
```


```python

def specialFilter(nums):
    """
    Returns the count of numbers in the list that are greater than 10 and
    have both the first and last digits odd.
    """
    count = 0
    for num in nums:
        if num > 10:
            # Convert to positive string to handle negative numbers
            s = str(abs(num))
            first_digit = int(s[0])
            last_digit = int(s[-1])
            if first_digit % 2 == 1 and last_digit % 2 == 1:
                count += 1
    return count

```


```python

def get_max_triples(n):
    """
    You are given a positive integer n. You have to create an integer array a of length n.
        For each i (1 ≤ i ≤ n), the value of a[i] = i * i - i + 1.
        Return the number of triples (a[i], a[j], a[k]) of a where i < j < k,
    and a[i] + a[j] + a[k] is a multiple of 3.

    Example :
        Input: n = 5
        Output: 1
        Explanation:
        a = [1, 3, 7, 13, 21]
        The only valid triple is (1, 7, 13).
    """
    # Compute a[i] mod 3 for i from 1 to n
    # a[i] = i*i - i + 1
    # mod 3: i*i mod 3 = (i mod 3)^2 mod 3, -i mod 3 = -(i mod 3) mod 3
    # So a[i] mod 3 = ( (i%3)^2 - (i%3) + 1 ) % 3
    # For i%3 = 0: 0 - 0 + 1 = 1 mod 3
    # For i%3 = 1: 1 - 1 + 1 = 1 mod 3
    # For i%3 = 2: 4 - 2 + 1 = 3 mod 3 = 0
    # So pattern: i%3=0 -> 1, i%3=1 -> 1, i%3=2 -> 0

    count_mod = [0, 0, 0]  # count of residues 0,1,2
    for i in range(1, n + 1):
        if i % 3 == 2:
            count_mod[0] += 1
        else:
            count_mod[1] += 1

    c0, c1, c2 = count_mod  # c2 is always 0 because only residues 0 and 1 appear
    # Actually c2 = 0, so we only have residues 0 and 1.
    # For sum of three numbers to be divisible by 3, the residues must sum to 0 mod 3.
    # Possible combinations from {0,1}:
    # (0,0,0) -> sum 0 mod 3
    # (1,1,1) -> sum 3 mod 3 = 0
    # (0,0,1) -> sum 1 mod 3 -> not valid
    # (0,1,1) -> sum 2 mod 3 -> not valid
    # So only all same residue.

    # Number of triples with all residues 0: choose(c0, 3)
    # Number of triples with all residues 1: choose(c1, 3)
    from math import comb
    return comb(c0, 3) + comb(c1, 3)

```


```python

def bf(planet1, planet2):
    '''
    There are eight planets in our solar system: the closerst to the Sun
    is Mercury, the next one is Venus, then Earth, Mars, Jupiter, Saturn,
    Uranus, Neptune.
    Write a function that takes two planet names as strings planet1 and planet2.
    The function should return a tuple containing all planets whose orbits are
    located between the orbit of planet1 and the orbit of planet2, sorted by
    the proximity to the sun.
    The function should return an empty tuple if planet1 or planet2
    are not correct planet names.
    Examples
    bf("Jupiter", "Neptune") ==> ("Saturn", "Uranus")
    bf("Earth", "Mercury") ==> ("Venus")
    bf("Mercury", "Uranus") ==> ("Venus", "Earth", "Mars", "Jupiter", "Saturn")
    '''
    planets = ["Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune"]

    if planet1 not in planets or planet2 not in planets:
        return ()

    idx1 = planets.index(planet1)
    idx2 = planets.index(planet2)

    if idx1 < idx2:
        start = idx1 + 1
        end = idx2
    else:
        start = idx2 + 1
        end = idx1

    return tuple(planets[start:end])

```