def sum_of_digits_of_largest_prime_substring(integer: str) -> int:
    """
    Given a string representing non-negative integers,
    return the sum of digits of the largest prime number among all the contiguous substrings of length 3.
    Examples:
    >>> sum_of_digits_of_largest_prime_substring('1019')
    2
    >>> sum_of_digits_of_largest_prime_substring('10199')
    19
    """
    return skjkasdkd([int(integer[i:i + 3]) for i in range(len(integer) - 2)])

def check(candidate):
    assert candidate('1232131') == 5
    assert candidate('99773') == 25
    assert candidate('20230711') == 10

def test_check():
    check(sum_of_digits_of_largest_prime_substring)

test_check()

    def isPrime(n):
        for i in range(2, int(n ** 0.5) + 1):
            if n % i == 0:
                return False
        return True
    maxx = 0
    i = 0
    while i < len(lst):
        if lst[i] > maxx and isPrime(lst[i]):
            maxx = lst[i]
        i += 1
    result = sum((int(digit) for digit in str(maxx)))
    return result


def check_dict_case(dict: Dict[str, str]) -> bool:
    """
    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' })
    True
    >>> check_dict_case({ 'a': 'apple', 'A': 'banana', 'B': 'banana' })
    False
    >>> check_dict_case({ 'a': 'apple', 8: 'banana', 'a': 'apple' })
    False
    >>> check_dict_case({ 'Name': 'John', 'Age': '36', 'City': 'Houston' })
    False
    >>> check_dict_case({ 'STATE': 'NC', 'ZIP': '12345' })
    True
    """
    if len(dict.keys()) == 0:
        return False
    else:
        state = 'start'
        for key in dict.keys():
            if not isinstance(key, str):
                state = 'mixed'
                break
            if state == 'start':
                if key.isupper():
                    state = 'upper'
                elif key.islower():
                    state = 'lower'
                else:
                    break
            elif state == 'upper' and (not key.isupper()) or (state == 'lower' and (not key.islower())):
                state = 'mixed'
                break
            else:
                break
        return state == 'upper' or state == 'lower'

def check_case_consistency(lst: List[str]) -> bool:
    """
    Implement a function that returns true if all the strings in the given list
    are either all lowercase or all uppercase, and false otherwise.
    Examples:
    >>> check_case_consistency(['Name', 'Age', 'City'])
    False
    >>> check_case_consistency(['STATE', 'ZIP'])
    True
    """
    return check_dict_case({string: None for string in lst})

def check(candidate):
    assert candidate(['aa', 'bb', 'cc', 'abc', 'abcd']) is True
    assert candidate(['AAA', 'ABCD', 'ABCDE']) is True
    assert candidate(['Check', 'case', 'consistency']) is False

def test_check():
    check(check_case_consistency)

test_check()


def count_up_to(n: int) -> List[int]:
    """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]
    """
    primes = []
    for i in range(2, n):
        is_prime = True
        for j in range(2, i):
            if i % j == 0:
                is_prime = False
                break
        if is_prime:
            primes.append(i)
    return primes

def sum_of_primes_smaller_than(number: int) -> int:
    """
    Calculate the sum of all prime numbers smaller than the given number.
    Examples:
    >>> sum_of_primes_smaller_than(5)
    5
    >>> sum_of_primes_smaller_than(11)
    17
    """
    return sum(count_up_to(number))

def check(candidate):
    assert candidate(2) == 0
    assert candidate(20) == 77
    assert candidate(100) == 1060

def test_check():
    check(sum_of_primes_smaller_than)

test_check()


def multiply(a: int, b: int) -> int:
    """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)
    16
    >>> multiply(19, 28)
    72
    >>> multiply(2020, 1851)
    0
    >>> multiply(14, -15)
    20
    """
    return abs(a % 10) * abs(b % 10)

def calculate_sum_or_difference_based_on_product(a: int, b: int) -> int:
    """
    Implement an efficient function that returns the sum of the two numbers
    if their product is even, and the difference of the two numbers if their product is odd.
    Examples:
    >>> calculate_sum_or_difference_based_on_product(3, 4)
    7
    >>> calculate_sum_or_difference_based_on_product(3, 5)
    -2
    """
    return a + b if multiply(a, b) % 2 == 0 else a - b

def check(candidate):
    assert candidate(11, 33) == -22
    assert candidate(22, 44) == 66
    assert candidate(-111, 333) == -444

def test_check():
    check(calculate_sum_or_difference_based_on_product)

test_check()


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

    For example:
    >>> count_upper('aBCdEf')
    1
    >>> count_upper('abcdefg')
    0
    >>> count_upper('dBBE')
    0
    """
    count = 0
    for i in range(0, len(s), 2):
        if s[i] in 'AEIOU':
            count += 1
    return count

def find_string_with_highest_uppercase_vowel_count_at_even_indices(strings: List[str]) -> str:
    """
    Return the string from the given list of strings
    that has the highest count of uppercase vowels at even indices.
    In the case of having the same count, return the string that is located at the frontmost position.
    Examples:
    >>> find_string_with_highest_uppercase_vowel_count_at_even_indices(['aBCdEf', 'abcdefg', 'dBBE'])
    'aBCdEf'
    >>> find_string_with_highest_uppercase_vowel_count_at_even_indices(['b', 'Eb', 'Ab'])
    'Eb'
    """
    return max(strings, key=count_upper)

def check(candidate):
    assert candidate(['ABBBBBBB', 'ABABABAB', 'AAAAAA', 'BBBBBBBBBB']) == 'ABABABAB'
    assert candidate(['BABEBIBOBU', 'acecicocuc', 'bbccAdd']) == 'bbccAdd'
    assert candidate(['ABEC', 'EBIC', 'IBOC', 'OBUC']) == 'ABEC'

def test_check():
    check(find_string_with_highest_uppercase_vowel_count_at_even_indices)

test_check()


def closest_integer(value: str) -> int:
    """
    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 math import ceil, floor
    if value.count('.') == 1:
        while value[-1] == '0':
            value = value[:-1]
    num = float(value)
    if value[-2:] == '.5':
        if num > 0:
            res = ceil(num)
        else:
            res = floor(num)
    elif len(value) > 0:
        res = int(round(num))
    else:
        res = 0
    return res

def find_largest_rearranged_decimal_number(number: str) -> int:
    """
    Given a positive decimal number represented as a string,
    return the rounded value of the largest decimal number that can be obtained
    by rearranging the order of digits, excluding the decimal point (.).
    Examples:
    >>> find_largest_rearranged_decimal_number('13.24')
    43
    """
    index = number.index('.')
    digits = number[:index] + number[index + 1:]
    digits = ''.join(sorted(digits, reverse=True))
    number = digits[:index] + '.' + digits[index:]
    return closest_integer(number)

def check(candidate):
    assert candidate('1234.5678') == 8765
    assert candidate('567.567') == 777
    assert candidate('2023.0712') == 7322

def test_check():
    check(find_largest_rearranged_decimal_number)

test_check()


def make_a_pile(n: int) -> List[int]:
    """
    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]
    """
    return [n + 2 * i for i in range(n)]

def get_last_elements_of_piles(numbers: List[int]) -> List[int]:
    """
    Given a list of positive integers,
    return a list of the last elements of the piles corresponding to each integer.
    Examples:
    >>> get_last_elements_of_piles([2, 3])
    [4, 7]
    """
    return [make_a_pile(number)[-1] for number in numbers]

def check(candidate):
    assert candidate([1, 2, 3, 4, 5]) == [1, 4, 7, 10, 13]
    assert candidate([5, 3, 1, 5, 3, 1]) == [13, 7, 1, 13, 7, 1]
    assert candidate([7, 10]) == [19, 28]

def test_check():
    check(get_last_elements_of_piles)

test_check()


def words_string(s: str) -> List[str]:
    """
    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']
    """
    if not s:
        return []
    s_list = []
    for letter in s:
        if letter == ',':
            s_list.append(' ')
        else:
            s_list.append(letter)
    s_list = ''.join(s_list)
    return s_list.split()

def words_string_lower(s: str) -> List[str]:
    """
    You will be given a string of words separated by commas or spaces. Your task is
    to split the lowercased version of the string into words and return an array of the words.

    For example:
    >>> words_string_lower('Hi, my name is John')
    ['hi', 'my', 'name', 'is', 'john']
    >>> words_string_lower('One, two, three, four, five, six')
    ['one', 'two', 'three', 'four', 'five', 'six']
    """
    return words_string(s.lower())

def check(candidate):
    assert candidate('') == []
    assert candidate(' ') == []
    assert candidate('Hi, my name is John') == ['hi', 'my', 'name', 'is', 'john']
    assert candidate('One, two, three, Four, five') == ['one', 'two', 'three', 'four', 'five']
    assert candidate(' , APPLE BANANA,, CANDY') == ['apple', 'banana', 'candy']

def test_check():
    check(words_string_lower)

test_check()


def choose_num(x: int, y: int) -> int:
    """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
    if y % 2 == 0:
        return y
    if x == y:
        return -1
    return y - 1

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

    For example:
    >>> choose_num_two_intervals(12, 15, 18, 20)
    20
    >>> choose_num_two_intervals(13, 12, 0, 10)
    -1
    """
    a = choose_num(x, y)
    b = choose_num(z, w)
    if a == -1 or b == -1:
        return -1
    else:
        return max(a, b)

def check(candidate):
    assert candidate(12, 15, 18, 20) == 20
    assert candidate(13, 12, 1, 10) == -1
    assert candidate(1, 5, 2, 3) == 4
    assert candidate(10, 20, 13, 10) == -1
    assert candidate(8, 6, 4, 2) == -1
    assert candidate(2, 5, 5, 9) == 8

def test_check():
    check(choose_num_two_intervals)

test_check()


def rounded_avg(n: int, m: int) -> Union[str, int]:
    """You are given two positive integers n and m, and your task is to compute the
    average of the integers from n through m (including n and m).
    Round the answer to the nearest integer and convert that to binary.
    If n is greater than m, return -1.
    Example:
    >>> rounded_avg(1, 5)
    '0b11'
    >>> rounded_avg(7, 5)
    -1
    >>> rounded_avg(10, 20)
    '0b1111'
    >>> rounded_avg(20, 33)
    '0b11010'
    """
    if m < n:
        return -1
    summation = 0
    for i in range(n, m + 1):
        summation += i
    return bin(round(summation / (m - n + 1)))

def biggest_multiplier_of_two(n: int, m: int) -> int:
    """You are given two positive integers n and m, and your task is to compute the
    the biggest multiplier of 2 among the numbers that are smaller than
    the average of [n, m] rounded to the nearest integer.
    If n is greater than m, return -1.
    Example:
    >>> biggest_multiplier_of_two(1, 5)
    2
    >>> biggest_multiplier_of_two(7, 5)
    -1
    >>> biggest_multiplier_of_two(10, 20)
    8
    >>> biggest_multiplier_of_two(20, 33)
    16
    """
    if m < n:
        return -1
    return 2 ** (len(rounded_avg(n, m)) - 3)

def check(candidate):
    assert candidate(1, 5) == 2
    assert candidate(7, 5) == -1
    assert candidate(10, 20) == 8
    assert candidate(20, 33) == 16
    assert candidate(1, 10) == 4
    assert candidate(16, 64) == 32

def test_check():
    check(biggest_multiplier_of_two)

test_check()


def unique_digits(x: List[int]) -> List[int]:
    """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])
    []
    """
    odd_digit_elements = []
    for i in x:
        if all((int(c) % 2 == 1 for c in str(i))):
            odd_digit_elements.append(i)
    return sorted(odd_digit_elements)

def unique_sum_of_digits(x: List[int]) -> List[int]:
    """Given a list of positive integers x. Compute a sorted list of all
    elements that hasn't any even digit, and convert each element into the
    sum of digits of the number.

    For example:
    >>> unique_sum_of_digits([15, 33, 1422, 1])
    [1, 6, 6]
    >>> unique_sum_of_digits([152, 323, 1422, 10])
    []
    """
    return [sum((int(digit) for digit in str(elem))) for elem in unique_digits(x)]


def by_length(arr: List[int]) -> List[str]:
    """
    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".

    For example:
    >>> by_length([2, 1, 1, 4, 5, 8, 2, 3])
    ['Eight', 'Five', 'Four', 'Three', 'Two', 'Two', 'One', 'One']

      If the array is empty, return an empty array:
    >>> by_length([])
    []

      If the array has any strange number ignore it:
    >>> by_length([1, -1, 55])
    ['One']
    """
    dic = {1: 'One', 2: 'Two', 3: 'Three', 4: 'Four', 5: 'Five', 6: 'Six', 7: 'Seven', 8: 'Eight', 9: 'Nine'}
    sorted_arr = sorted(arr, reverse=True)
    new_arr = []
    for var in sorted_arr:
        try:
            new_arr.append(dic[var])
        except:
            pass
    return new_arr

def by_length_csv(arr: List[int]) -> str:
    """
    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".
    Convert the list of digit names into a comma-separated string.

    For example:
    >>> by_length_csv([2, 1, 1, 4, 5, 8, 2, 3])
    'Eight,Five,Four,Three,Two,Two,One,One'

      If the array is empty, return an empty string:
    >>> by_length_csv([])
    ''

      If the array has any strange number ignore it:
    >>> by_length_csv([1, -1, 55])
    'One'
    """
    return ','.join(by_length(arr))

def check(candidate):
    assert candidate([2, 1, 1, 4, 5, 8, 2, 3]) == 'Eight,Five,Four,Three,Two,Two,One,One'
    assert candidate([]) == ''
    assert candidate([1, -1, 55]) == 'One'
    assert candidate([1, 3, 5, 7]) == 'Seven,Five,Three,One'
    assert candidate([0, 0, 0, 0]) == ''
    assert candidate([99, 0, 1, 4, 4, 1]) == 'Four,Four,One,One'

def test_check():
    check(by_length_csv)

test_check()


def f(n: int) -> List[int]:
    """Implement the function f that takes n as a parameter,
    and returns a list of size n, such that the value of the element at index i is the factorial of i if i is even
    or the sum of numbers from 1 to i otherwise.
    i starts from 1.
    the factorial of i is the multiplication of the numbers from 1 to i (1 * 2 * ... * i).
    Example:
    >>> f(5)
    [1, 2, 6, 24, 15]
    """
    ret = []
    for i in range(1, n + 1):
        if i % 2 == 0:
            x = 1
            for j in range(1, i + 1):
                x *= j
            ret += [x]
        else:
            x = 0
            for j in range(1, i + 1):
                x += j
            ret += [x]
    return ret

def sorted_f(n: int) -> List[int]:
    """Implement the function f that takes n as a parameter,
    and compute a list of size n, such that the value of the element at index i is the factorial of i if i is even
    or the sum of numbers from 1 to i otherwise.
    i starts from 1.
    Sort the integer values in a descending order.
    the factorial of i is the multiplication of the numbers from 1 to i (1 * 2 * ... * i).
    Example:
    >>> sorted_f(5)
    [24, 15, 6, 2, 1]
    """
    return sorted(f(n), reverse=True)

def check(candidate):
    assert candidate(1) == [1]
    assert candidate(5) == [24, 15, 6, 2, 1]
    assert candidate(10) == [3628800, 40320, 720, 45, 28, 24, 15, 6, 2, 1]

def test_check():
    check(sorted_f)

test_check()


def even_odd_palindrome(n: int) -> Tuple[int, int]:
    """
    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.

    Example 1:

    >>> even_odd_palindrome(3)
    (1, 2)
        Explanation:
        Integer palindrome are 1, 2, 3. one of them is even, and two of them are odd.

    Example 2:

    >>> even_odd_palindrome(12)
    (4, 6)
        Explanation:
        Integer palindrome are 1, 2, 3, 4, 5, 6, 7, 8, 9, 11. four of them are even, and 6 of them are odd.

    Note:
        1. 1 <= n <= 10^3
        2. returned tuple has the number of even and odd integer palindromes respectively.
    """

    def is_palindrome(n):
        return str(n) == str(n)[::-1]
    even_palindrome_count = 0
    odd_palindrome_count = 0
    for i in range(1, n + 1):
        if i % 2 == 1 and is_palindrome(i):
            odd_palindrome_count += 1
        elif i % 2 == 0 and is_palindrome(i):
            even_palindrome_count += 1
    return (even_palindrome_count, odd_palindrome_count)

def even_odd_palindrome_interval(m: int, n: int) -> Tuple[int, int]:
    """
    Given two positive integers m and n, return a tuple that has the number of even and odd
    integer palindromes that fall within the range(m+1, n), inclusive.
    If m is greater than n, return (0, 0).

    Example 1:

    >>> even_odd_palindrome_interval(3, 12)
    (3, 4)
        Explanation:
        Integer palindrome within the range(3+1, 12) are 4, 5, 6, 7, 8, 9, 11. three of them are even, and four of them are odd.

    Note:
        1. 1 <= m, n <= 10^3
        2. returned tuple has the number of even and odd integer palindromes respectively.
    """
    if m > n:
        return (0, 0)
    return tuple((en - em for (em, en) in zip(even_odd_palindrome(m), even_odd_palindrome(n))))

def check(candidate):
    assert candidate(3, 12) == (3, 4)
    assert candidate(5, 3) == (0, 0)
    assert candidate(4, 4) == (0, 0)
    assert candidate(4, 5) == (0, 1)
    assert candidate(10, 20) == (0, 1)
    assert candidate(11, 21) == (0, 0)

def test_check():
    check(even_odd_palindrome_interval)

test_check()


def count_nums(arr: List[int]) -> int:
    """
    Write a function count_nums which takes an array of integers and returns
    the number of elements which has a sum of digits > 0.
    If a number is negative, then its first signed digit will be negative:
    e.g. -123 has signed digits -1, 2, and 3.
    >>> count_nums([])
    0
    >>> count_nums([-1, 11, -11])
    1
    >>> count_nums([1, 1, 2])
    3
    """

    def digits_sum(n):
        neg = 1
        if n < 0:
            (n, neg) = (-1 * n, -1)
        n = [int(i) for i in str(n)]
        n[0] = n[0] * neg
        return sum(n)
    return len(list(filter(lambda x: x > 0, [digits_sum(i) for i in arr])))

def count_nums_union(arr1: List[int], arr2: List[int]) -> int:
    """
    Write a function count_nums_union which takes two arrays of integers and returns
    the number of elements which has a sum of digits > 0 from union of the arrays (without repetition of elements).
    If a number is negative, then its first signed digit will be negative:
    e.g. -123 has signed digits -1, 2, and 3.
    >>> count_nums_union([], [])
    0
    >>> count_nums_union([-1, 11, -11], [1, 1, 2])
    3
    """
    return count_nums(list(set(arr1) | set(arr2)))


def move_one_ball(arr: List[int]) -> bool:
    """We have an array 'arr' of N integers arr[1], arr[2], ..., arr[N].The
    numbers in the array will be randomly ordered. Your task is to determine if
    it is possible to get an array sorted in non-decreasing order by performing
    the following operation on the given array:
        You are allowed to perform right shift operation any number of times.

    One right shift operation means shifting all elements of the array by one
    position in the right direction. The last element of the array will be moved to
    the starting position in the array i.e. 0th index.

    If it is possible to obtain the sorted array by performing the above operation
    then return True else return False.
    If the given array is empty then return True.

    Note: The given list is guaranteed to have unique elements.

    For Example:

    >>> move_one_ball([3, 4, 5, 1, 2])
    True
    Explanation: By performin 2 right shift operations, non-decreasing order can
                 be achieved for the given array.
    >>> move_one_ball([3, 5, 4, 1, 2])
    False
    Explanation:It is not possible to get non-decreasing order for the given
                array by performing any number of right shift operations.

    """
    if len(arr) == 0:
        return True
    sorted_array = sorted(arr)
    my_arr = []
    min_value = min(arr)
    min_index = arr.index(min_value)
    my_arr = arr[min_index:] + arr[0:min_index]
    for i in range(len(arr)):
        if my_arr[i] != sorted_array[i]:
            return False
    return True

def move_one_ball_any_order(arr: List[int]) -> bool:
    """We have an array 'arr' of N integers arr[1], arr[2], ..., arr[N].The
    numbers in the array will be randomly ordered. Your task is to determine if
    it is possible to get an array sorted in non-decreasing or non-increasing order
    by performing the following operation on the given array:
        You are allowed to perform right shift operation any number of times.

    One right shift operation means shifting all elements of the array by one
    position in the right direction. The last element of the array will be moved to
    the starting position in the array i.e. 0th index.

    If it is possible to obtain the sorted array by performing the above operation
    then return True else return False.
    If the given array is empty then return True.

    Note: The given list is guaranteed to have unique elements.

    For Example:

    >>> move_one_ball_any_order([3, 4, 5, 1, 2])
    True
    Explanation: By performing 2 right shift operations, non-decreasing order can
                 be achieved for the given array.
    >>> move_one_ball_any_order([2, 1, 5, 4, 3])
    True
    Explanation: By performing 3 right shift operations, non-increasing order can
                 be achieved for the given array.
    >>> move_one_ball_any_order([3, 5, 4, 1, 2])
    False
    Explanation:It is not possible to get non-decreasing or non-increasing order
                for the given array by performing any number of right shift operations.

    """
    return move_one_ball(arr) or move_one_ball([-e for e in arr])

def check(candidate):
    assert candidate([3, 4, 5, 1, 2]) is True
    assert candidate([2, 1, 5, 4, 3]) is True
    assert candidate([3, 5, 4, 1, 2]) is False
    assert candidate([3, 5, 4, 2, 1]) is False
    assert candidate([5, 6, 7, 1, 2, 3, 4]) is True
    assert candidate([3, 2, 1, 7, 6, 5, 4]) is True

def test_check():
    check(move_one_ball_any_order)

test_check()


def exchange(lst1: List[int], lst2: List[int]) -> str:
    """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 = 0
    even = 0
    for i in lst1:
        if i % 2 == 1:
            odd += 1
    for i in lst2:
        if i % 2 == 0:
            even += 1
    if even >= odd:
        return 'YES'
    return 'NO'

def exchange_from_repetition(lst1: List[int], lst2: List[int], n: int) -> List[str]:
    """In this problem, you will implement a function that takes two lists of numbers (lst1 and lst2) and a number (n),
    and determines whether it is possible to perform an exchange of elements
    between "lst1" and "k-times repeated lst2" (k <= n) to make lst1 a list of only even numbers.
    There is no limit on the number of exchanged elements between "lst1" and "k-times repeated lst2".
    Return the array of length n whose k-th element is "YES" if it is possible to exchange elements between the "lst1"
    and "k-times repeated lst2" to make all the elements of lst1 to be even.
    Otherwise, k-th element is "NO".
    For example:
    >>> exchange_from_repetition([1, 2, 3, 4], [1, 5, 3, 4], 1)
    ['NO']
    >>> exchange_from_repetition([1, 2, 3, 4], [1, 5, 3, 4], 3)
    ['NO', 'YES', 'YES']
    It is assumed that the input lists will be non-empty.
    """
    return [exchange(lst1, lst2 * k) for k in range(1, n + 1)]


def histogram(test: str) -> Dict[str, int]:
    """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('')
    {  }

    """
    dict1 = {}
    list1 = test.split(' ')
    t = 0
    for i in list1:
        if list1.count(i) > t and i != '':
            t = list1.count(i)
    if t > 0:
        for i in list1:
            if list1.count(i) == t:
                dict1[i] = t
    return dict1

def most_frequent_letter(test: str) -> Tuple[str, int]:
    """Given a string representing a space separated lowercase letters, return a tuple
    of the letter with the most repetition and containing the corresponding count.
    If several letters have the same occurrence, return the largest one in an alphabetical order.

    Example:
    >>> most_frequent_letter('a b c')
    ('c', 1)
    >>> most_frequent_letter('a b b a')
    ('b', 2)
    >>> most_frequent_letter('a b c a b')
    ('b', 2)
    """
    return max([e for e in histogram(test).items()], key=lambda x: x[0])

def check(candidate):
    assert candidate('a b c') == ('c', 1)
    assert candidate('a b b a') == ('b', 2)
    assert candidate('a b c a b') == ('b', 2)
    assert candidate('a b a a b') == ('a', 3)
    assert candidate('b b b b a') == ('b', 4)
    assert candidate('a b c d e e e f f f') == ('f', 3)

def test_check():
    check(most_frequent_letter)

test_check()


def reverse_delete(s: str, c: str) -> Tuple[str, bool]:
    """Task
    We are given two strings s and c, you have to deleted all the characters in s that are equal to any character in c
    then check if the result string is palindrome.
    A string is called palindrome if it reads the same backward as forward.
    You should return a tuple containing the result string and True/False for the check.
    Example
    >>> reverse_delete('abcde', 'ae')
    ('bcd', False)
    >>> reverse_delete('abcdef', 'b')
    ('acdef', False)
    >>> reverse_delete('abcdedcba', 'ab')
    ('cdedc', True)
    """
    s = ''.join([char for char in s if char not in c])
    return (s, s[::-1] == s)

def reverse_delete_list(s: str, c: str) -> List[Tuple[str, bool]]:
    """Task
    We are given two strings s and c, you have to deleted all the characters in s that are equal to each of the characters in c
    then check if each result string is palindrome.
    A string is called palindrome if it reads the same backward as forward.
    You should return a list of the tuples containing result string and True/False for the check.
    Example
    >>> reverse_delete_list('abcde', 'ae')
    [('bcde', False), ('abcd', 'False')]
    >>> reverse_delete_list('abcdef', 'b')
    [('acdef', False)]
    >>> reverse_delete_list('abcdedcba', 'ab')
    [('bcdedcb', True), ('acdedca', True)]
    """
    return [reverse_delete(s, e) for e in c]

def check(candidate):
    assert candidate('abcde', 'ae') == [('bcde', False), ('abcd', False)]
    assert candidate('abcdef', 'b') == [('acdef', False)]
    assert candidate('aabaa', 'b') == [('aaaa', True)]
    assert candidate('abcdedcba', 'ab') == [('bcdedcb', True), ('acdedca', True)]
    assert candidate('abcdedcba', 'abc') == [('bcdedcb', True), ('acdedca', True), ('abdedba', True)]
    assert candidate('eabcdefdcba', 'ef') == [('abcdfdcba', True), ('eabcdedcba', False)]

def test_check():
    check(reverse_delete_list)

test_check()


def odd_count(lst: List[str]) -> List[str]:
    """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.']
    """
    res = []
    for arr in lst:
        n = sum((int(d) % 2 == 1 for d in arr))
        res.append('the number of odd elements ' + str(n) + 'n the str' + str(n) + 'ng ' + str(n) + ' of the ' + str(n) + 'nput.')
    return res

def split_odd_count(lst: List[str], strsize: int) -> List[str]:
    """Given a list of strings, where each string consists of only digits,
    first split each string into shorter ones with the length strsize and 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.

    >>> split_odd_count(['1234567'], 7)
    ['the number of odd elements 4n the str4ng 4 of the 4nput.']
    >>> split_odd_count(['3', '11111111'], 4)
    ['the number of odd elements 1n the str1ng 1 of the 1nput.',
    'the number of odd elements 4n the str4ng 4 of the 4nput.',
    'the number of odd elements 4n the str4ng 4 of the 4nput.']
    """
    split_lst = [s[i:i + strsize] for s in lst for i in range(0, len(s), strsize)]
    return odd_count(split_lst)

def check(candidate):
    assert candidate(['1234567'], 7) == ['the number of odd elements 4n the str4ng 4 of the 4nput.']
    assert candidate(['3', '11111111'], 4) == ['the number of odd elements 1n the str1ng 1 of the 1nput.', 'the number of odd elements 4n the str4ng 4 of the 4nput.', 'the number of odd elements 4n the str4ng 4 of the 4nput.']
    assert candidate(['1', '2'], 2) == ['the number of odd elements 1n the str1ng 1 of the 1nput.', 'the number of odd elements 0n the str0ng 0 of the 0nput.']
    assert candidate(['987234826349'], 6) == ['the number of odd elements 3n the str3ng 3 of the 3nput.', 'the number of odd elements 2n the str2ng 2 of the 2nput.']
    assert candidate(['987234826349'], 8) == ['the number of odd elements 3n the str3ng 3 of the 3nput.', 'the number of odd elements 2n the str2ng 2 of the 2nput.']
    assert candidate(['987234826349'], 10) == ['the number of odd elements 4n the str4ng 4 of the 4nput.', 'the number of odd elements 1n the str1ng 1 of the 1nput.']

def test_check():
    check(split_odd_count)

test_check()


def minSubArraySum(nums: List[int]) -> int:
    """
    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
    """
    max_sum = 0
    s = 0
    for num in nums:
        s += -num
        if s < 0:
            s = 0
        max_sum = max(s, max_sum)
    if max_sum == 0:
        max_sum = max((-i for i in nums))
    min_sum = -max_sum
    return min_sum

def minSubArraySumNonNegative(nums: List[int]) -> int:
    """
    Given an array of integers nums, find the minimum sum of any non-empty sub-array
    of nums. Consider all negative integers as 0.
    Example
    >>> minSubArraySumNonNegative([2, 3, 4, 1, 2, 4])
    1
    >>> minSubArraySumNonNegative([-1, -2, -3])
    0
    """
    return minSubArraySum([max(e, 0) for e in nums])

def check(candidate):
    assert candidate([2, 3, 4, 1, 2, 4]) == 1
    assert candidate([-1, -2, -3]) == 0
    assert candidate([1, 2, 3, 4, 1, 2, 3, 4]) == 1
    assert candidate([1, 2, -1, -3, -4, -5, 6, 1]) == 0
    assert candidate([0, 0, 0]) == 0
    assert candidate([1, 0, -1]) == 0

def test_check():
    check(minSubArraySumNonNegative)

test_check()


def max_fill(grid: List[List[int]], capacity: int) -> int:
    """
    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:
    >>> max_fill([[0, 0, 1, 0], [0, 1, 0, 0], [1, 1, 1, 1]], 1)
    6

    Example 2:
    >>> max_fill([[0, 0, 1, 1], [0, 0, 0, 0], [1, 1, 1, 1], [0, 1, 1, 1]], 2)
    5

    Example 3:
    >>> max_fill([[0, 0, 0], [0, 0, 0]], 5)
    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
    """
    return sum([math.ceil(sum(arr) / capacity) for arr in grid])

def max_fill_buckets(grid: List[List[int]], capacities: List[int]) -> List[int]:
    """
    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 corresponding buckets that can be used to extract water from it,
    and all buckets have the same capacity.
    Your task is to use the buckets with different capacities to empty the wells.
    Output the list of the number of times you need to lower the buckets for each capacity.

    Example 1:
    >>> max_fill_buckets([[0, 0, 1, 0], [0, 1, 0, 0], [1, 1, 1, 1]], [1, 2])
    [6, 4]

    Example 2:
    >>> max_fill_buckets([[0, 0, 1, 1], [0, 0, 0, 0], [1, 1, 1, 1], [0, 1, 1, 1]], [1, 2])
    [9, 5]

    Example 3:
    >>> max_fill_buckets([[0, 0, 0], [0, 0, 0]], [5])
    [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
    """
    return [max_fill(grid, capacity) for capacity in capacities]


def sort_array(arr: List[int]) -> List[int]:
    """
    In this Kata, you have to sort an array of non-negative integers according to
    number of ones in their binary representation in ascending order.
    For similar number of ones, sort based on decimal value.

    It must be implemented like this:
    >>> sort_array([1, 5, 2, 3, 4])
    [1, 2, 4, 3, 5]
    >>> sort_array([-2, -3, -4, -5, -6])
    [-4, -2, -6, -5, -3]
    >>> sort_array([1, 0, 2, 3, 4])
    [0, 1, 2, 4, 3]
    """
    return sorted(sorted(arr), key=lambda x: bin(x)[2:].count('1'))

def check_moving_sort_array(arr: List[int]) -> List[bool]:
    """
    In this Kata, you have to sort an array of non-negative integers according to
    number of ones in their binary representation in ascending order.
    For similar number of ones, sort based on decimal value.
    Compare the original array and its sorted array, and then return the list of whether each
    element is moved or not from its original position. (True if it is moved, False otherwise.)

    It must be implemented like this:
    >>> check_moving_sort_array([1, 5, 2, 3, 4])
    [False, True, True, False, True]
    >>> check_moving_sort_array([-2, -3, -4, -5, -6])
    [True, True, True, False, True]
    >>> check_moving_sort_array([1, 0, 2, 3, 4])
    [True, True, False, True, True]
    """
    sorted_arr = sort_array(arr)
    return [True if a != b else False for (a, b) in zip(arr, sorted_arr)]

def check(candidate):
    assert candidate([1, 5, 2, 3, 4]) == [False, True, True, False, True]
    assert candidate([-2, -3, -4, -5, -6]) == [True, True, True, False, True]
    assert candidate([1, 0, 2, 3, 4]) == [True, True, False, True, True]
    assert candidate([1, 2, 3, 4, 5, 6, 7, 8]) == [False, False, True, True, True, True, True, True]
    assert candidate([-4, -1, 9, 0, -9, 1, 4]) == [True, True, True, True, True, True, True]
    assert candidate([11, 14]) == [False, False]

def test_check():
    check(check_moving_sort_array)

test_check()


def select_words(s: str, n: int) -> List[str]:
    """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']
    """
    result = []
    for word in s.split():
        n_consonants = 0
        for i in range(0, len(word)):
            if word[i].lower() not in ['a', 'e', 'i', 'o', 'u']:
                n_consonants += 1
        if n_consonants == n:
            result.append(word)
    return result

def select_largest_word(s: str, n: int) -> str:
    """Given a string s and a natural number n, you have been tasked to implement
    a function that returns the word from string s that contain exactly n consonants.
    If there exist multiple words satisfying the condition, return the largest one in an alphabetical order.
    If the string s is empty then the function should return an empty string.
    Note: you may assume the input string contains only letters and spaces.
    Examples:
    >>> select_largest_word('Mary had a little lamb', 4)
    'little'
    >>> select_largest_word('Mary had a little lamb', 3)
    'lamb'
    >>> select_largest_word('simple white space', 2)
    ''
    >>> select_largest_word('Hello world', 4)
    'world'
    >>> select_largest_word('Uncle sam', 3)
    'Uncle'
    """
    return max(select_words(s, n) + [''])

def check(candidate):
    assert candidate('Mary had a little lamb', 4) == 'little'
    assert candidate('Mary had a little lamb', 3) == 'lamb'
    assert candidate('simple white space', 2) == ''
    assert candidate('Hello world', 4) == 'world'
    assert candidate('Uncle sam', 3) == 'Uncle'
    assert candidate('baeiou aeiouz', 1) == 'baeiou'

def test_check():
    check(select_largest_word)

test_check()


def get_closest_vowel(word: str) -> str:
    """You are given a word. Your task is to find the closest vowel that stands between
    two consonants from the right side of the word (case sensitive).

    Vowels in the beginning and ending doesn't count. Return empty string if you didn't
    find any vowel met the above condition.

    You may assume that the given string contains English letter only.

    Example:
    >>> get_closest_vowel('yogurt')
    'u'
    >>> get_closest_vowel('FULL')
    'U'
    >>> get_closest_vowel('quick')
    ''
    >>> get_closest_vowel('ab')
    ''
    """
    if len(word) < 3:
        return ''
    vowels = {'a', 'e', 'i', 'o', 'u', 'A', 'E', 'O', 'U', 'I'}
    for i in range(len(word) - 2, 0, -1):
        if word[i] in vowels:
            if word[i + 1] not in vowels and word[i - 1] not in vowels:
                return word[i]
    return ''

def transform_closest_vowel(s: str) -> str:
    """You are given a string containing multiple words. Your task is to make a new string by changing each word
    to its closest vowel that stands between two consonants from the right side of the word (case sensitive).
    You need to concatenate all the closest vowels that are obtained from each word.

    Vowels in the beginning and ending doesn't count. Ignore the word if you didn't
    find any vowel met the above condition.

    You may assume that the given string contains English letter only.

    Example:
    >>> transform_closest_vowel('yogurt FULL')
    'uU'
    >>> transform_closest_vowel('quick ab')
    ''
    """
    return ''.join([get_closest_vowel(word) for word in s.split()])

def check(candidate):
    assert candidate('yogurt FULL') == 'uU'
    assert candidate('quick ab') == ''
    assert candidate('Alice loves Bob') == 'ieo'
    assert candidate('happy sunny day ever') == 'auae'
    assert candidate('aaa bbb ccc ddd') == ''
    assert candidate('fox and dog') == 'oo'

def test_check():
    check(transform_closest_vowel)

test_check()


def match_parens(lst: List[str]) -> str:
    """
    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 check(s):
        val = 0
        for i in s:
            if i == '(':
                val = val + 1
            else:
                val = val - 1
            if val < 0:
                return False
        return True if val == 0 else False
    S1 = lst[0] + lst[1]
    S2 = lst[1] + lst[0]
    return 'Yes' if check(S1) or check(S2) else 'No'

def match_parens_from_list(str1: str, lst2: List[str]) -> str:
    """
    You are given a string (str1) and a list of strings (lst2), where every string consists of open
    parentheses '(' or close parentheses ')' only.
    Your job is to check if it is possible to concatenate a string (selected from the list lst2)
    and the first string str1 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_from_list('()(' [')', '(((())(()())))'])
    'Yes'
    >>> match_parens_from_list(')', [')'])
    'No'
    """
    for str2 in lst2:
        if match_parens([str1, str2]) == 'Yes':
            return 'Yes'
    return 'No'


def maximum(arr: List[int], k: int) -> List[int]:
    """
    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.

    Example 1:

    >>> maximum([-3, -4, 5], 3)
    [-4, -3, 5]

    Example 2:

    >>> maximum([4, -4, 4], 2)
    [4, 4]

    Example 3:

    >>> maximum([-3, 2, 1, 2, -1, -2, 1], 1)
    [2]

    Note:
        1. The length of the array will be in the range of [1, 1000].
        2. The elements in the array will be in the range of [-1000, 1000].
        3. 0 <= k <= len(arr)
    """
    if k == 0:
        return []
    arr.sort()
    ans = arr[-k:]
    return ans

def minimum_of_maximum_subarrays(arrays: List[List[int]], k: int) -> int:
    """
    Given a list of arrays and a positive integer k, return the minimal integer among the arrays.

    Example 1:

    >>> minimum_of_maximum_subarrays([[-3, -4, 5], [4, -4, 4], [-3, 2, 1, 2, -1, -2, 1]], 2)
    -3

    Example 2:

    >>> minimum_of_maximum_subarrays([[1, 2, 3], [4, 5, 6], [7, 8, 9]], 1)
    3

    Note:
        1. Each array in the list will have length in the range of [1, 1000].
        2. The elements in each array will be in the range of [-1000, 1000].
        3. 1 <= k <= min([len(arr) for arr in arrays])
    """
    mins = [maximum(arr, k)[0] for arr in arrays]
    return min(mins)


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

    Examples
    >>> solution([5, 8, 7, 1])
    12
    >>> solution([3, 3, 3, 3, 3])
    9
    >>> solution([30, 13, 24, 321])
    0
    """
    return sum([x for (idx, x) in enumerate(lst) if idx % 2 == 0 and x % 2 == 1])

def alternate_sum(arrays: List[List[int]]) -> int:
    """Given a list of arrays, return the sum of all of the odd elements that are in even positions
    of all arrays in even positions minus the sum of all of the odd elements that are in odd positions.

    Examples
    >>> alternate_sum([[5, 8, 7, 1], [3, 3, 3, 3, 3]])
    3
    >>> alternate_sum([[30, 13, 24, 321], [3, 3, 3, 3, 3]])
    -9
    """
    return sum([solution(x) for (idx, x) in enumerate(arrays) if idx % 2 == 0]) - sum([solution(x) for (idx, x) in enumerate(arrays) if idx % 2 == 1])


def add_elements(arr: List[int], k: int) -> int:
    """
    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.

    Example:

    >>> add_elements([111, 21, 3, 4000, 5, 6, 7, 8, 9], 4)
    24

    Constraints:
        1. 1 <= len(arr) <= 100
        2. 1 <= k <= len(arr)
    """
    return sum((elem for elem in arr[:k] if len(str(elem)) <= 2))

def max_num_passengers(arr: List[int]) -> int:
    """
    Given an array of integers arr where each element represents the weight of
    passengers, return the maximum number of passengers that can be carried on
    a single elevator given that the sum of all the weights must be less than 100.

    Examples:

    >>> max_num_passengers([111, 21, 3, 4000, 5, 6, 7, 8, 9])
    7
    >>> max_num_passengers([215, 327, 102])
    0

    Constraints:
        1. 1 <= len(arr) <= 100
        2. arr[i] > 0
    """
    arr.sort()
    for k in range(1, len(arr) + 1):
        if add_elements(arr, k) >= 100:
            return k - 1
    return len(arr)

def check(candidate):
    assert candidate([70, 13, 25, 10, 10, 45]) == 4
    assert candidate([60, 55, 42, 37, 97]) == 2
    assert candidate([1, 2, 3, 4, 5, 6, 7, 8, 9]) == 9

def test_check():
    check(max_num_passengers)

test_check()


def get_odd_collatz(n: int) -> List[int]:
    """
    Given a positive integer n, return a sorted list that has the odd numbers in collatz sequence.

    The Collatz conjecture is a conjecture in mathematics that concerns a sequence defined
    as follows: start with any positive integer n. Then each term is obtained from the
    previous term as follows: if the previous term is even, the next term is one half of
    the previous term. If the previous term is odd, the next term is 3 times the previous
    term plus 1. The conjecture is that no matter what value of n, the sequence will always reach 1.

    Note:
        1. Collatz(1) is [1].
        2. returned list sorted in increasing order.

    For example:
    get_odd_collatz(5) returns [1, 5] # The collatz sequence for 5 is [5, 16, 8, 4, 2, 1], so the odd numbers are only 1, and 5.
    >>> get_odd_collatz(5)
    [1, 5]
    """
    if n % 2 == 0:
        odd_collatz = []
    else:
        odd_collatz = [n]
    while n > 1:
        if n % 2 == 0:
            n = n / 2
        else:
            n = n * 3 + 1
        if n % 2 == 1:
            odd_collatz.append(int(n))
    return sorted(odd_collatz)

def sum_odd_collatz(n: int) -> int:
    """
    Given a positive integer n, return the sum of odd numbers in collatz sequence.

    Examples:

    >>> sum_odd_collatz(5)
    6
    >>> sum_odd_collatz(10)
    6
    """
    return sum(get_odd_collatz(n))

def check(candidate):
    assert candidate(11) == 47
    assert candidate(7) == 54
    assert candidate(100) == 19

def test_check():
    check(sum_odd_collatz)

test_check()


def valid_date(date: str) -> bool:
    """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

    >>> 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
    """
    try:
        date = date.strip()
        (month, day, year) = date.split('-')
        (month, day, year) = (int(month), int(day), int(year))
        if month < 1 or month > 12:
            return False
        if month in [1, 3, 5, 7, 8, 10, 12] and day < 1 or day > 31:
            return False
        if month in [4, 6, 9, 11] and day < 1 or day > 30:
            return False
        if month == 2 and day < 1 or day > 29:
            return False
    except:
        return False
    return True

def num_valid_birthdays(dates: List[str]) -> int:
    """Given a list of birthdays with valid dates, return the number of people
    who can be given some birthday gifts.

    >>> num_valid_birthdays(['03-11-2000', '15-01-2012', '04-0-2040', '06-04-2020'])
    2
    """
    return sum([valid_date(date) for date in dates])


def split_words(txt: str) -> Union[List[str], int]:
    """
    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()
    elif ',' in txt:
        return txt.replace(',', ' ').split()
    else:
        return len([i for i in txt if i.islower() and ord(i) % 2 == 0])

def num_words(txt: str) -> int:
    """
    Given one sentence of words, return the number of words in it.
    >>> num_words('Hello world!')
    2
    >>> num_words('Hello,world!')
    2
    >>> num_words('abcdef')
    1
    """
    result = split_words(txt)
    if isinstance(result, list):
        return len(result)
    else:
        return 1

def check(candidate):
    assert candidate('The fox jumped over the fence.') == 6
    assert candidate('The,fox,jumped,over,the,fence.') == 6
    assert candidate('I, as a human, love to sleep.') == 7

def test_check():
    check(num_words)

test_check()


def is_sorted(lst: List[int]) -> bool:
    """
    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.

    Examples
    >>> is_sorted([5])
    True
    >>> is_sorted([1, 2, 3, 4, 5])
    True
    >>> is_sorted([1, 3, 2, 4, 5])
    False
    >>> is_sorted([1, 2, 3, 4, 5, 6])
    True
    >>> is_sorted([1, 2, 3, 4, 5, 6, 7])
    True
    >>> is_sorted([1, 3, 2, 4, 5, 6, 7])
    False
    >>> is_sorted([1, 2, 2, 3, 3, 4])
    True
    >>> is_sorted([1, 2, 2, 2, 3, 4])
    False
    """
    count_digit = dict([(i, 0) for i in lst])
    for i in lst:
        count_digit[i] += 1
    if any((count_digit[i] > 2 for i in lst)):
        return False
    if all((lst[i - 1] <= lst[i] for i in range(1, len(lst)))):
        return True
    else:
        return False

def all_sorted(lst: List[List[int]]) -> bool:
    """
    Given a non-empty list of lists of integers, return a boolean values indicating
    whether each sublist is sorted in ascending order without more than one duplicate of the same number.

    Examples
    >>> all_sorted([[5], [1, 2, 3, 4, 5], [1, 3, 2, 4, 5], [1, 2, 3, 4, 5, 6], [1, 2, 2, 2, 3, 4]])
    False
    >>> all_sorted([1, 2, 3, 4, 5, 6, 7], [1, 2, 2, 3, 3, 4], [3, 5, 7, 8])
    True
    """
    return all([is_sorted(sublist) for sublist in lst])

def check(candidate):
    assert candidate([1, 1, 1, 2], [2, 3, 5], [4, 4, 5]) is False
    assert candidate([1, 2, 3, 4, 5], [5, 7, 10, 13]) is True
    assert candidate([3, 3, 4], [1, 2, 3], [7, 6, 7]) is False

def test_check():
    check(all_sorted)

test_check()


from itertools import combinations
from typing import List, Tuple

def intersection(interval1: Tuple[int, int], interval2: Tuple[int, int]) -> str:
    """You are given two intervals,
    where each interval is a pair of integers. For example, interval = (start, end) = (1, 2).
    The given intervals are closed which means that the interval (start, end)
    includes both start and end.
    For each given interval, it is assumed that its start is less or equal its end.
    Your task is to determine whether the length of intersection of these two
    intervals is a prime number.
    Example, the intersection of the intervals (1, 3), (2, 4) is (2, 3)
    which its length is 1, which not a prime number.
    If the length of the intersection is a prime number, return "YES",
    otherwise, return "NO".
    If the two intervals don't intersect, return "NO".

    [input/output] samples:
    >>> intersection((1, 2), (2, 3))
    'NO'
    >>> intersection((-1, 1), (0, 4))
    'NO'
    >>> intersection((-3, -1), (-5, 5))
    'YES'
    """

    def is_prime(num):
        if num == 1 or num == 0:
            return False
        if num == 2:
            return True
        for i in range(2, num):
            if num % i == 0:
                return False
        return True
    l = max(interval1[0], interval2[0])
    r = min(interval1[1], interval2[1])
    length = r - l
    if length > 0 and is_prime(length):
        return 'YES'
    return 'NO'

def all_prime_intersection(intervals: List[Tuple[int, int]]) -> bool:
    """Check if all intersections of given intervals are prime numbers.

    [inpt/output] samples:
    >>> all_prime_intersection([(1, 2), (2, 3), (3, 4)])
    False
    >>> all_prime_intersection([(-3, 4), (-5, 5), (1, 4)])
    True
    """
    comb = combinations(intervals, 2)
    for (interval1, interval2) in comb:
        if intersection(interval1, interval2) == 'NO':
            return False
    return True

def check(candidate):
    assert candidate([(-3, -1), (-5, 5), (3, 4)]) is False
    assert candidate([(-1, 7), (-5, 4), (1, 4)]) is True
    assert candidate([(1, 8), (3, 8), (-2, 6)]) is True

def test_check():
    check(all_prime_intersection)

test_check()


def prod_signs(arr: List[int]) -> Optional[int]:
    """
    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
    prod = 0 if 0 in arr else (-1) ** len(list(filter(lambda x: x < 0, arr)))
    return prod * sum([abs(i) for i in arr])

def prod_signs_within_threshold(arr: List[int], threshold: int) -> Optional[int]:
    """
    You are given an array arr of integers and you need to return
    sum of magnitudes of integers within the threshold value,
    multiplied by product of all signs of each number in the array.
    Note: return None for empty arr.

    Example:
    >>> prod_signs_within_threshold([1, 2, 2, -4], 3)
    5
    >>> prod_signs_within_threshold([0, 1], 1)
    0
    >>> prod_signs_within_threshold([], 1)
    None
    """
    return prod_signs(list(filter(lambda x: abs(x) <= threshold, arr)))

def check(candidate):
    assert candidate([-1, -3, -5, -7, -9], 5) == 4
    assert candidate([-10, -20, 30, -40, 50, -60], 45) == -100
    assert candidate([-3, -2, -1, 0, 1, 2, 3], 2) == 0

def test_check():
    check(prod_signs_within_threshold)

test_check()


def tri(n: int) -> list[int]:
    """Everyone knows Fibonacci sequence, it was studied deeply by mathematicians in
    the last couple centuries. However, what people don't know is Tribonacci sequence.
    Tribonacci sequence is defined by the recurrence:
    tri(1) = 3
    tri(n) = 1 + n / 2, if n is even.
    tri(n) =  tri(n - 1) + tri(n - 2) + tri(n + 1), if n is odd.
    For example:
    tri(2) = 1 + (2 / 2) = 2
    tri(4) = 3
    tri(3) = tri(2) + tri(1) + tri(4)
           = 2 + 3 + 3 = 8
    You are given a non-negative integer number n, you have to a return a list of the
    first n + 1 numbers of the Tribonacci sequence.
    Examples:
    >>> tri(3)
    [1, 3, 2, 8]
    """
    if n == 0:
        return [1]
    my_tri = [1, 3]
    for i in range(2, n + 1):
        if i % 2 == 0:
            my_tri.append(i / 2 + 1)
        else:
            my_tri.append(my_tri[i - 1] + my_tri[i - 2] + (i + 3) / 2)
    return my_tri

def beautiful_tri(start: int, end: int) -> list[int]:
    """Everyone knows Fibonacci sequence, it was studied deeply by mathematicians in
    the last couple centuries. However, what people don't know is Tribonacci sequence.
    Tribonacci sequence is defined by the recurrence:
    tri(1) = 3
    tri(n) = 1 + n / 2, if n is even.
    tri(n) =  tri(n - 1) + tri(n - 2) + tri(n + 1), if n is odd.
    For example:
    tri(2) = 1 + (2 / 2) = 2
    tri(4) = 3
    tri(3) = tri(2) + tri(1) + tri(4)
           = 2 + 3 + 3 = 8
    You are given a non-negative integer number n, you have to a return a list of the
    start-th number and end-th number of the Tribonacci sequence that the number is
    a multiple of 3.
    Examples:
    >>> tri(5, 10)
    [3]
    """
    return [int(i) for i in tri(end)[start:] if i % 3 == 0]


def digits(n: int) -> int:
    """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
    odd_count = 0
    for digit in str(n):
        int_digit = int(digit)
        if int_digit % 2 == 1:
            product = product * int_digit
            odd_count += 1
    if odd_count == 0:
        return 0
    else:
        return product

def unique_odd_digits(lst: List[int]) -> int:
    """Given a list of positive integers, return the product of unique odd digits.
    For example:
    >>> unique_odd_digits([1, 4, 235])
    15
    >>> unique_odd_digits([123, 456, 789])
    945
    >>> unique_odd_digits([2, 4, 6, 8, 99])
    9
    """
    concat = ''
    for num in lst:
        concat += str(num)
    unique = set(concat)
    return digits(int(''.join(unique)))

def check(candidate):
    assert candidate([0, 1, 2, 3, 4, 5]) == 15
    assert candidate([22, 44, 66, 88]) == 0
    assert candidate([1325, 540, 938]) == 135

def test_check():
    check(unique_odd_digits)

test_check()


def sum_squares(lst: List[float]) -> int:
    """You are given a list of numbers.
    You need to return the sum of squared numbers in the given list,
    round each element in the list to the upper int(Ceiling) first.
    Examples:
    >>> lst([1.0, 2.0, 3.0])
    14
    >>> lst([1.0, 4.0, 9.0])
    98
    >>> lst([1.0, 3.0, 5.0, 7.0])
    84
    >>> lst([1.4, 4.2, 0.0])
    29
    >>> lst([-2.4, 1.0, 1.0])
    6

    """
    import math
    squared = 0
    for i in lst:
        squared += math.ceil(i) ** 2
    return squared

def diff_ceil_floor_sum_squares(lst: List[float]) -> int:
    """You are given a list of numbers.
    You need to return the absolute difference between the sum of squared numbers in the given list,
    round each element in the list to the upper int(Ceiling) first,
    and the sum of squared numbers in the given list,
    round each element in the list to the lower int(Floor) first.
    Examples:
    >>> lst([1.0, 2.0, 3.0])
    0
    >>> lst([1.4, 4.2, 0.0])
    12
    >>> lst([-2.4, 1.0, 1.0])
    5

    """
    return abs(sum_squares(lst) - sum_squares([-i for i in lst]))

def check(candidate):
    assert candidate([-3.1, 2.5, 7.9]) == 13
    assert candidate([0.5, -0.5, 3.0, -2.0]) == 0
    assert candidate([-3.2, -2.8, -1.6, 0.7, 1.5, 2.8]) == 6

def test_check():
    check(diff_ceil_floor_sum_squares)

test_check()


def check_if_last_char_is_a_letter(txt: str) -> bool:
    """
    Create a function that returns True if the last character
    of a given string is an alphabetical character and is not
    a part of a word, and False otherwise.
    Note: "word" is a group of characters separated by space.

    Examples:
    >>> check_if_last_char_is_a_letter('apple pie')
    False
    >>> check_if_last_char_is_a_letter('apple pi e')
    True
    >>> check_if_last_char_is_a_letter('apple pi e ')
    False
    >>> check_if_last_char_is_a_letter('')
    False
    """
    check = txt.split(' ')[-1]
    return True if len(check) == 1 and 97 <= ord(check.lower()) <= 122 else False

def check_if_first_char_is_a_letter(txt: str) -> bool:
    """
    Create a function that returns True if the first character
    of a given string is an alphabetical character and is not
    a part of a word, and False otherwise.
    Note: "word" is a group of characters separated by space.

    Examples:
    >>> check_if_first_char_is_a_letter('apple pie')
    False
    >>> check_if_first_char_is_a_letter('a pple pie')
    True
    >>> check_if_first_char_is_a_letter(' a pple pie')
    False
    >>> check_if_first_char_is_a_letter('')
    False
    """
    return check_if_last_char_is_a_letter(txt[::-1])

def check(candidate):
    assert candidate('a boat is on the river') is True
    assert candidate(' over the rainbow') is False
    assert candidate('life is good') is False

def test_check():
    check(check_if_first_char_is_a_letter)

test_check()


def can_arrange(arr: List[int]) -> int:
    """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
    """
    ind = -1
    i = 1
    while i < len(arr):
        if arr[i] < arr[i - 1]:
            ind = i
        i += 1
    return ind

def is_ordered(arr: List[int]) -> bool:
    """Create a function which returns True if the given array is sorted in
    either ascending or descending order, otherwise return False.

    Examples:
    >>> is_ordered([1, 2, 4, 3, 5])
    False
    >>> is_ordered([1, 2, 3])
    True
    >>> is_ordered([3, 2, 1])
    True
    """
    return can_arrange(arr) == -1 or can_arrange(arr[::-1]) == -1

def check(candidate):
    assert candidate([6, 5, 4, 3, 2, 1]) is True
    assert candidate([3, 5, 4, 2, 7, 9]) is False
    assert candidate([-1, -2, -3, -5]) is True

def test_check():
    check(is_ordered)

test_check()


from typing import List, Optional, Tuple

def largest_smallest_integers(lst: List[int]) -> Tuple[Optional[int], Optional[int]]:
    """
    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)
    """
    smallest = list(filter(lambda x: x < 0, lst))
    largest = list(filter(lambda x: x > 0, lst))
    return (max(smallest) if smallest else None, min(largest) if largest else None)

def smallest_interval_including_zero(lst: List[int]) -> int:
    """
    Create a function that returns the length of the smallest interval that includes zero.
    If there is no such interval, return 0.

    Examples:
    >>> smallest_interval_including_zero([2, 4, 1, 3, 5, 7])
    0
    >>> smallest_interval_including_zero([0])
    0
    >>> smallest_interval_including_zero([-5, -3, 1, 2, 4])
    4
    """
    (start, end) = largest_smallest_integers(lst)
    if start is None or end is None:
        return 0
    return end - start

def check(candidate):
    assert candidate([-2, 0, 1, 2, 3]) == 3
    assert candidate([0, 1, 2, 3]) == 0
    assert candidate([-5, -4, -3, -2, -1]) == 0

def test_check():
    check(smallest_interval_including_zero)

test_check()


from itertools import combinations
from typing import List, Union

def compare_one(a: Union[int, float, str], b: Union[int, float, str]) -> Union[int, float, str, None]:
    """
    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
    """
    (temp_a, temp_b) = (a, b)
    if isinstance(temp_a, str):
        temp_a = temp_a.replace(',', '.')
    if isinstance(temp_b, str):
        temp_b = temp_b.replace(',', '.')
    if float(temp_a) == float(temp_b):
        return None
    return a if float(temp_a) > float(temp_b) else b

def biggest(lst: List[Union[int, float, str]]) -> Union[int, float, str, None]:
    """
    Create a function that takes a list of integers, floats, or strings representing
    real numbers, and returns the non-duplicate largest variable in its given variable type.
    Return None if the largest value is duplicated.
    Note: If a real number is represented as a string, the floating point might be . or ,

    >>> biggest([1, 2.5, '2,3'])
    2.5
    >>> biggest(['1', 1])
    None
    >>> biggest(['5,1', '-6'])
    '5,1'
    """
    bigger = [compare_one(a, b) for (a, b) in combinations(lst, 2)]
    bigger = [elem for elem in bigger if elem is not None]
    if not bigger:
        return None
    return max(bigger)

def check(candidate):
    assert candidate([1, 1, 1, 1, 1]) is None
    assert candidate(['8,4', 8.1, '-8,3', 8.2]) == '8,4'
    assert candidate([10, 10, 8, 9, 6]) == 10

def test_check():
    check(biggest)

test_check()


def is_equal_to_sum_even(n: int) -> bool:
    """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
    """
    return n % 2 == 0 and n >= 8

def num_test_subjects(lst: List[int]) -> int:
    """In your country, people are obligated to take a inspection test every 2 years
    after they turn 8.
    You are given a list of ages of people in your country. Return the number of
    people who are required to take the test in the next year.
    Example
    >>> num_test_subjects([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
    2
    >>> num_test_subjects([30, 42, 27, 21, 8, 1])
    2
    >>> num_test_subjects([7, 3, 5, 6, 8, 9])
    2
    """
    return sum([is_equal_to_sum_even(x + 1) for x in lst])

def check(candidate):
    assert candidate([27, 28, 29, 30, 31, 32]) == 3
    assert candidate([7, 6, 8, 9, 11, 13, 100]) == 4
    assert candidate([37, 31, 30, 29, 8, 13, 14, 49, 57]) == 6

def test_check():
    check(num_test_subjects)

test_check()


def special_factorial(n: int) -> int:
    """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.
    """
    fact_i = 1
    special_fact = 1
    for i in range(1, n + 1):
        fact_i *= i
        special_fact *= fact_i
    return special_fact

def factorial(n: int) -> int:
    """The factorial of a positive integer n, denoted by n!, is the product of all
    positive integers less than or equal to n.

    For example:
    >>> factorial(4)
    24
    >>> factorial(1)
    1
    >>> factorial(5)
    120

    The function will receive an integer as input and should return the factorial
    of this integer.
    """
    fact = special_factorial(n)
    for i in range(1, n):
        fact //= special_factorial(i)
    return fact

def check(candidate):
    assert candidate(7) == 5040
    assert candidate(6) == 720
    assert candidate(10) == 3628800

def test_check():
    check(factorial)

test_check()


def fix_spaces(text: str) -> str:
    """
    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'
    """
    new_text = ''
    i = 0
    (start, end) = (0, 0)
    while i < len(text):
        if text[i] == ' ':
            end += 1
        else:
            if end - start > 2:
                new_text += '-' + text[i]
            elif end - start > 0:
                new_text += '_' * (end - start) + text[i]
            else:
                new_text += text[i]
            (start, end) = (i + 1, i + 1)
        i += 1
    if end - start > 2:
        new_text += '-'
    elif end - start > 0:
        new_text += '_'
    return new_text

def extended_fix_spaces(text: str) -> str:
    """
    Given a string text, replace all spaces and tab in it with underscores.
    Consider a tab as 4 spaces, and if a string has more than 2 consecutive spaces,
    then replace all consecutive spaces with -

    >>> extended_fix_spaces('Example')
    'Example'
    >>> extended_fix_spaces('Example	1')
    'Example-1'
    >>> extended_fix_spaces('	Example 2')
    '-Example_2'
    >>> extended_fix_spaces(' Example 3')
    '_Example-3'
    >>> extended_fix_spaces(' Example	4_')
    '_Example-4_'
    """
    return fix_spaces(text.replace('\t', '    '))

def check(candidate):
    assert candidate('\tcandidate([9, 2, 4, 3, 8, 9])') == '-candidate([9,_2,_4,_3,_8,_9])'
    assert candidate('cool\tand aweesome function!') == 'cool-and_aweesome_function!'
    assert candidate('\t\t\t\t') == '-'

def test_check():
    check(extended_fix_spaces)

test_check()


def file_name_check(file_name: str) -> str:
    """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'
    """
    suf = ['txt', 'exe', 'dll']
    lst = file_name.split(sep='.')
    if len(lst) != 2:
        return 'No'
    if not lst[1] in suf:
        return 'No'
    if len(lst[0]) == 0:
        return 'No'
    if not lst[0][0].isalpha():
        return 'No'
    t = len([x for x in lst[0] if x.isdigit()])
    if t > 3:
        return 'No'
    return 'Yes'

def download_link_check(link: str) -> str:
    """Create a function which takes a string representing a link address, and returns
    'Yes' if the the link is valid, and returns 'No' otherwise.
    A link 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']
    - The link should start with 'https://'
    Examples:
    >>> download_link_check('https://example.txt')
    'Yes'
    >>> file_name_check('https://1example.dll')
    'No'
    >>> file_name_check('example.txt')
    'No'
    """
    if not link.startswith('https://'):
        return 'No'
    return file_name_check(link[8:])

def check(candidate):
    assert candidate('https://hello-world.dll') == 'Yes'
    assert candidate('file://cool010.exe') == 'No'
    assert candidate('https://0010110.txt') == 'No'

def test_check():
    check(download_link_check)

test_check()


def sum_squares(lst: list[int]) -> int:
    """ "
    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:
    >>> sum_squares([1, 2, 3])
    6
    >>> sum_squares([])
    0
    >>> sum_squares([-1, -5, 2, -1, -5])
    -126
    """
    result = []
    for i in range(len(lst)):
        if i % 3 == 0:
            result.append(lst[i] ** 2)
        elif i % 4 == 0 and i % 3 != 0:
            result.append(lst[i] ** 3)
        else:
            result.append(lst[i])
    return sum(result)

def extended_sum_squares(lst: list[int]) -> int:
    """
    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 and negate the integer entry if its index is a multiple of 5
    and not a multiple of 3 and 4. The function will not change the entries in
    the list whose indexes are not a multiple of 3 or 4 or 5. The function shall
    then return the sum of all entries.

    Examples:
    >>> sum_squares([1, 2, 3])
    6
    >>> sum_squares([])
    0
    >>> sum_squares([-1, -5, 2, -1, -5, -6])
    -120
    """
    return sum_squares([-x if idx % 5 == 0 and idx % 4 != 0 and (idx % 3 != 0) else x for (idx, x) in enumerate(lst)])

def check(candidate):
    assert candidate([4, 7, 5, 3, 1, 1, 4, 6, 8, 9, 100]) == 552
    assert candidate([3, 4, 1, 5, 0, 8, 8, 5]) == 100
    assert candidate([2, 3, 5, 7, 11, 13, 17, 19]) == 1687

def test_check():
    check(extended_sum_squares)

test_check()


def words_in_sentence(sentence: str) -> str:
    """
    You are given a string representing a sentence,
    the sentence contains some words separated by a space,
    and you have to return a string that contains the words from the original sentence,
    whose lengths are prime numbers,
    the order of the words in the new string should be the same as the original one.

    Example 1:
    >>> words_in_sentence('This is a test')
    'is'

    Example 2:
    >>> words_in_sentence('lets go for swimming')
    'go for'

    Constraints:
        * 1 <= len(sentence) <= 100
        * sentence contains only letters
    """
    new_lst = []
    for word in sentence.split():
        flg = 0
        if len(word) == 1:
            flg = 1
        for i in range(2, len(word)):
            if len(word) % i == 0:
                flg = 1
        if flg == 0 or len(word) == 2:
            new_lst.append(word)
    return ' '.join(new_lst)

def extended_words_in_sentence(sentence: str, sep: str) -> str:
    """
    You are given a string representing a sentence,
    the sentence contains some words separated by `sep`,
    and you have to return a string that contains the words from the original sentence,
    whose lengths are prime numbers,
    the order of the words in the new string should be the same as the original one.

    Example 1:
    >>> extended_words_in_sentence('This is a test', ' ')
    'is'

    Example 2:
    >>> extended_words_in_sentence('lets,go,for,swimming', ',')
    'go,for'

    Constraints:
        * 1 <= len(sentence) <= 100
        * sentence contains only letters
    """
    return words_in_sentence(sentence.replace(sep, ' ')).replace(' ', sep)

def check(candidate):
    assert candidate('apple|delta|for|much|quantity', '|') == 'apple|delta|for'
    assert candidate('what-is-your-hobby', '-') == 'is-hobby'
    assert candidate('your,task,is,to,support,your,colleague', ',') == 'is,to,support'

def test_check():
    check(extended_words_in_sentence)

test_check()


def simplify(x: str, n: str) -> bool:
    """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
    """
    (a, b) = x.split('/')
    (c, d) = n.split('/')
    numerator = int(a) * int(c)
    denom = int(b) * int(d)
    if numerator / denom == int(numerator / denom):
        return True
    return False

def get_simplified_pair(l: list[str]) -> Optional[tuple[str, str]]:
    """Find a pair (a, b) which can be simplified in the given list of fractions.
    Simplified means that a * b is a whole number. Both a and b are string representation
    of a fraction, and have the following format, <numerator>/<denominator> where both
    numerator and denominator are positive whole numbers.

    If there is no such pair, return None.
    If there is multiple such pair, return the first one.

    Example:
    >>> get_simplified_pair(['1/5', '5/1', '1/6', '2/1', '7/10', '10/2'])
    ('1/5', '5/1')
    >>> get_simplified_pair(['1/6', '2/1', '7/10', '10/2'])
    ('2/1', '10/2')
    """
    for i in range(len(l)):
        for j in range(i + 1, len(l)):
            if simplify(l[i], l[j]):
                return (l[i], l[j])
    return None


def order_by_points(nums: list[int]) -> list[int]:
    """
    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 digits_sum(n):
        neg = 1
        if n < 0:
            (n, neg) = (-1 * n, -1)
        n = [int(i) for i in str(n)]
        n[0] = n[0] * neg
        return sum(n)
    return sorted(nums, key=digits_sum)

def positive_order_by_points(nums: list[int]) -> list[int]:
    """Write a function which sorts the integers in the given list
    that is greater than zero.
    Note: if there are several items with similar sum of their digits,
    order them based on their index in original list.

    For example:
    >>> positive_order_by_points([1, 11, -1, -11, -12])
    [1, 11]
    >>> positive_order_by_points([])
    []
    """
    return order_by_points([num for num in nums if num > 0])


def specialFilter(nums: list[int]) -> int:
    """Write a function that takes an array of numbers as input and returns
    the number of elements in the array that are greater than 10 and both
    first and last digits of a number are odd (1, 3, 5, 7, 9).
    For example:
    >>> specialFilter([15, -73, 14, -15])
    1
    >>> specialFilter([33, -2, -3, 45, 21, 109])
    2
    """
    count = 0
    for num in nums:
        if num > 10:
            odd_digits = (1, 3, 5, 7, 9)
            number_as_string = str(num)
            if int(number_as_string[0]) in odd_digits and int(number_as_string[-1]) in odd_digits:
                count += 1
    return count

def extended_special_filter(nums: list[int]) -> int:
    """Write a function that takes an array of numbers as input and returns
    the number of elements in the array that are greater than 10 and both
    first digits of a number are odd (1, 3, 5, 7, 9) and last digits of a number is even.
    For example:
    >>> specialFilter([15, -73, 14, -15])
    1
    >>> specialFilter([33, -2, -3, 45, 21, 109])
    0
    """
    count = 0
    for num in nums:
        if num > 10:
            odd_digits = (1, 3, 5, 7, 9)
            even_digits = (2, 4, 6, 8, 0)
            number_as_string = str(num)
            if int(number_as_string[0]) in odd_digits and int(number_as_string[-1]) in even_digits:
                count += 1
    return count

def check(candidate):
    assert candidate([302, 444, 97, 92, 114]) == 3
    assert candidate([4932, 30585, 392828, 1128]) == 2
    assert candidate([66485, 9327, 88757, 344]) == 1

def test_check():
    check(extended_special_filter)

test_check()


def get_max_triples(n: int) -> int:
    """
    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 :
    >>> get_max_triples(5)
    1
        Explanation:
        a = [1, 3, 7, 13, 21]
        The only valid triple is (1, 7, 13).
    """
    A = [i * i - i + 1 for i in range(1, n + 1)]
    ans = []
    for i in range(n):
        for j in range(i + 1, n):
            for k in range(j + 1, n):
                if (A[i] + A[j] + A[k]) % 3 == 0:
                    ans += [(A[i], A[j], A[k])]
    return len(ans)

def get_not_max_triple(n: int) -> int:
    """
    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 not a multiple of 3.
    Assume that n >= 3.

    Example :
    >>> get_not_max_triples(5)
    9
    """
    return n * (n - 1) * (n - 2) // 6 - get_max_triples(n)

def check(candidate):
    assert candidate(8) == 45
    assert candidate(13) == 198
    assert candidate(16) == 385

def test_check():
    check(get_not_max_triple)

test_check()


def bf(planet1: str, planet2: str) -> Tuple[str, ...]:
    """
    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')
    """
    planet_names = ('Mercury', 'Venus', 'Earth', 'Mars', 'Jupiter', 'Saturn', 'Uranus', 'Neptune')
    if planet1 not in planet_names or planet2 not in planet_names or planet1 == planet2:
        return ()
    planet1_index = planet_names.index(planet1)
    planet2_index = planet_names.index(planet2)
    if planet1_index < planet2_index:
        return planet_names[planet1_index + 1:planet2_index]
    else:
        return planet_names[planet2_index + 1:planet1_index]

def living_area(planet1: str, planet2: str) -> bool:
    """
    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.
    Among this planets, Earth is the only planet that can live human.
    Your task is to check whether there is a planet that can live human
    between planet1 and planet2 exclusively.
    Return true if there is a planet that can live human between planet1 and planet2.
    Examples:
    >>> living_area('Jupiter', 'Neptune')
    False
    >>> living_area('Earth', 'Mercury')
    False
    >>> living_area('Mercury', 'Uranus')
    True
    """
    return 'Earth' in bf(planet1, planet2)

def check(candidate):
    assert candidate('Venus', 'Jupiter') is True
    assert candidate('Uranus', 'Mars') is False
    assert candidate('Mars', 'Mercury') is True

def test_check():
    check(living_area)

test_check()


def sorted_list_sum(lst: List[str]) -> List[str]:
    """Write a function that accepts a list of strings as a parameter,
    deletes the strings that have odd lengths from it,
    and returns the resulted list with a sorted order,
    The list is always a list of strings and never an array of numbers,
    and it may contain duplicates.
    The order of the list should be ascending by length of each word, and you
    should return the list sorted by that rule.
    If two words have the same length, sort the list alphabetically.
    The function should return a list of strings in sorted order.
    You may assume that all words will have the same length.
    For example:
    >>> list_sort(['aa', 'a', 'aaa'])
    ['aa']
    >>> list_sort(['ab', 'a', 'aaa', 'cd'])
    ['ab', 'cd']
    """
    lst.sort()
    new_lst = []
    for i in lst:
        if len(i) % 2 == 0:
            new_lst.append(i)
    return sorted(new_lst, key=len)

def extract_even_words(text: str) -> str:
    """Write a function that accepts a string as a parameter, and a string
    is consisted of words separated by spaces, deletes the words that have
    odd lengths from it, and returns the resulted string with a sorted order,
    The order of the words should be ascending by length of each word, and you
    should return the string sorted by that rule.
    IF two words have the same length, sort the string alphabetically.
    For example:
    >>> extract_odd_words('aa a aaa')
    'aa'
    >>> extract_odd_words('ab a aaa cd')
    'ab cd'
    """
    return ' '.join(sorted_list_sum(text.split()))

def check(candidate):
    assert candidate('apple sand pear black cheeze') == 'pear sand cheeze'
    assert candidate('answer python analysis task mirror') == 'task answer mirror python analysis'
    assert candidate('hand monitor cream tissue water') == 'hand tissue'

def test_check():
    check(extract_even_words)

test_check()


def x_or_y(n: int, x: int, y: int) -> int:
    """A simple program which should return the value of x if n is
    a prime number and should return the value of y otherwise.

    Examples:
    >>> x_or_y(7, 34, 12)
    34
    >>> x_or_y(15, 8, 5)
    5

    """
    if n == 1:
        return y
    for i in range(2, n):
        if n % i == 0:
            return y
    else:
        return x

def list_x_or_y(ns: list[int], xs: list[int], ys: list[int]) -> list[int]:
    """A simple program which should return a list of values of x if the
    corresponding value in ns is a prime number and should return the value of y
    otherwise.

    Examples:
    >>> list_x_or_by([7, 15, 21], [34, 8, 3], [12, 5, 7])
    [34, 5, 7]
    >>> list_x_or_by([1, 2, 3], [34, 8, 3], [12, 5, 7])
    [12, 8, 3]
    """
    return [x_or_y(n, x, y) for (n, x, y) in zip(ns, xs, ys)]


def double_the_difference(lst: list[float]) -> int:
    """
    Given a list of numbers, return the sum of squares of the numbers
    in the list that are odd. Ignore numbers that are negative or not integers.

    >>> double_the_difference([1, 3, 2, 0])
    10
    >>> double_the_difference([-1, -2, 0])
    0
    >>> double_the_difference([9, -2])
    81
    >>> double_the_difference([0])
    0

    If the input list is empty, return 0.
    """
    return sum([i ** 2 for i in lst if i > 0 and i % 2 != 0 and ('.' not in str(i))])

def extended_double_the_difference(lst: list[float]) -> int:
    """
    Given a list of numbers, return the sum of squares of the numbers
    in the list that are odd and the cubic of the number in the list that
    are even. Ignore numbers that are negative or not integers.

    >>> double_the_difference([1, 3, 2, 0])
    18
    >>> double_the_difference([-1, -2, 0])
    0
    >>> double_the_difference([9, -2])
    81
    >>> double_the_difference([0])
    0

    If the input list is empty, return 0.
    """
    x = double_the_difference(lst)
    x += sum((i ** 3 for i in lst if i > 0 and i % 2 == 0 and ('.' not in str(i))))
    return x

def check(candidate):
    assert candidate([-1, 9, -5, 5, 13, 7, 0, 15]) == 549
    assert candidate([-5, -2, 7, 2, 1]) == 58
    assert candidate([3, 4, 5, 6, 7]) == 363

def test_check():
    check(extended_double_the_difference)

test_check()


def compare(game: list[int], guess: list[int]) -> list[int]:
    """I think we all remember that feeling when the result of some long-awaited
    event is finally known. The feelings and thoughts you have at that moment are
    definitely worth noting down and comparing.
    Your task is to determine if a person correctly guessed the results of a number of matches.
    You are given two arrays of scores and guesses of equal length, where each index shows a match.
    Return an array of the same length denoting how far off each guess was. If they have guessed correctly,
    the value is 0, and if not, the value is the absolute difference between the guess and the score.

    example:

    >>> compare([1, 2, 3, 4, 5, 1], [1, 2, 3, 4, 2, -2])
    [0, 0, 0, 0, 3, 3]
    >>> compare([0, 5, 0, 0, 0, 4], [4, 1, 1, 0, 0, -2])
    [4, 4, 1, 0, 0, 6]
    """
    return [abs(x - y) for (x, y) in zip(game, guess)]

def who_is_winner(game: list[int], guesses: list[list[int]]) -> int:
    """Return the index of guesses that is the most closely guess the game.
    If there is a tie, return the index of the first guess that is the most
    closely guess the game.

    Example:
    >>> who_is_winner([1, 2, 3], [[2, 0, 3], [1, 2, 3]])
    1
    >>> who_is_winner([1, 2, 3], [[2, 0, 3], [4, 5, 6]])
    0
    """
    return min(range(len(guesses)), key=lambda i: sum(compare(game, guesses[i])))


def Strongest_Extension(class_name: str, extensions: list[str]) -> str:
    """You will be given the name of a class (a string) and a list of extensions.
    The extensions are to be used to load additional classes to the class. The
    strength of the extension is as follows: Let CAP be the number of the uppercase
    letters in the extension's name, and let SM be the number of lowercase letters
    in the extension's name, the strength is given by the fraction CAP - SM.
    You should find the strongest extension and return a string in this
    format: ClassName.StrongestExtensionName.
    If there are two or more extensions with the same strength, you should
    choose the one that comes first in the list.
    For example, if you are given "Slices" as the class and a list of the
    extensions: ['SErviNGSliCes', 'Cheese', 'StuFfed'] then you should
    return 'Slices.SErviNGSliCes' since 'SErviNGSliCes' is the strongest extension
    (its strength is -1).
    Example:
    >>> Strongest_Extension('my_class', ['AA', 'Be', 'CC'])
    'my_class.AA'
    """
    strong = extensions[0]
    my_val = len([x for x in extensions[0] if x.isalpha() and x.isupper()]) - len([x for x in extensions[0] if x.isalpha() and x.islower()])
    for s in extensions:
        val = len([x for x in s if x.isalpha() and x.isupper()]) - len([x for x in s if x.isalpha() and x.islower()])
        if val > my_val:
            strong = s
            my_val = val
    ans = class_name + '.' + strong
    return ans

def extended_strongest_extension(extensions: list[str]) -> str:
    """You will be given a list of extensions. These extensions consist of package name and
    function name such as `package1.function1`.
    The strength of the extension is as follows: Let CAP be the number of the uppercase
    letters in the function's name, and let SM be the number of lowercase letters
    in the function's name, the strength is given by the fraction CAP - SM.
    You should find the strongest functions and return a dictionary which has package name as key
    and the strongest extension as value in this format: `package1.function1`.
    If there are two or more extensions with the same strength in the same package, you should
    choose the one that comes first in the list.
    Example:
    >>> extended_strongest_extension(['my_class.AA', 'my_class.Be', 'my_class2.Be', 'my_class2.CC'])
    {'my_class': 'my_class.AA', 'my_class2': 'my_class2.CC'}
    """
    result = {}
    for extension in extensions:
        (package, function) = extension.split('.')
        if package not in result:
            result[package] = [function]
        else:
            result[package].append(function)
    for package in result:
        result[package] = Strongest_Extension(package, result[package])
    return result

def check(candidate):
    assert candidate(['pack1.func1', 'pack1.Func1', 'pack1.FunC1']) == {'pack1': 'pack1.FunC1'}
    assert candidate(['math.MIN', 'math.MAX', 'abc.abstractmethod']) == {'math': 'math.MIN', 'abc': 'abc.abstractmethod'}
    assert candidate(['mirror.iSNa', 'category.FUNC', 'mirror.IsnA']) == {'mirror': 'mirror.iSNa', 'category': 'category.FUNC'}

def test_check():
    check(extended_strongest_extension)

test_check()


def cycpattern_check(a: str, b: str) -> bool:
    """You are given 2 words. You need to return True if the second word or any
    of its rotations is a substring in the first word
    >>> cycpattern_check('abcd', 'abd')
    False
    >>> cycpattern_check('hello', 'ell')
    True
    >>> cycpattern_check('whassup', 'psus')
    False
    >>> cycpattern_check('abab', 'baa')
    True
    >>> cycpattern_check('efef', 'eeff')
    False
    >>> cycpattern_check('himenss', 'simen')
    True

    """
    l = len(b)
    pat = b + b
    for i in range(len(a) - l + 1):
        for j in range(l + 1):
            if a[i:i + l] == pat[j:j + l]:
                return True
    return False

def extended_cycpattern_check(a: str, b: str) -> bool:
    """You are given 2 words. You need to return True if the second word or any
    of its rotations is a substring in the first word or any of its rotations
    >>> cycpattern_check('abcd', 'abd')
    True
    >>> cycpattern_check('hello', 'ell')
    True
    >>> cycpattern_check('whassup', 'psus')
    False
    >>> cycpattern_check('abab', 'baa')
    True
    >>> cycpattern_check('efeff', 'eeff')
    True
    >>> cycpattern_check('himenss', 'simen')
    True
    """
    return any((cycpattern_check(a[i:] + a[:i], b) for i in range(len(a))))

def check(candidate):
    assert candidate('oossiie', 'iso') is False
    assert candidate('rikkenwhwiejf', 'friwiej') is True
    assert candidate('whatemfho', 'howhat') is True

def test_check():
    check(extended_cycpattern_check)

test_check()


def even_odd_count(num: int) -> Tuple[int, int]:
    """Given an integer. return a tuple that has the number of even and odd digits respectively.

     Example:
    >>> even_odd_count(-12)
    (1, 1)
    >>> even_odd_count(123)
    (1, 2)
    """
    even_count = 0
    odd_count = 0
    for i in str(abs(num)):
        if int(i) % 2 == 0:
            even_count += 1
        else:
            odd_count += 1
    return (even_count, odd_count)

def balanced_number(num: int) -> bool:
    """Given an integer. return True if the number of even digits and odd digits
    are the same.

    Example:
    >>> balanced_number(1324)
    True
    >>> balanced_number(9119)
    False
    """
    (even_count, odd_count) = even_odd_count(num)
    return even_count == odd_count

def check(candidate):
    assert candidate(1234) is True
    assert candidate(12345) is False
    assert candidate(10) is True

def test_check():
    check(balanced_number)

test_check()