Prompt:
from typing import List

def has_close_elements(numbers: List[float], threshold: float) -> bool:
    """ Check if in given list of numbers, are any two numbers closer to each other than
    given threshold.
    """

Response:
def has_close_elements(numbers: List[float], threshold: float) -> bool:
    for i in range(len(numbers)):
        for j in range(i+1, len(numbers)):
            if abs(numbers[i] - numbers[j]) < threshold:
                return True
    return False


Prompt:
from typing import List

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

Response:
def separate_paren_groups(paren_string: str) -> List[str]:
    stack = []
    result = []
    for i in range(len(paren_string)):
        if paren_string[i] == '(': # push index of opening parenthesis onto stack
            stack.append(i)
        elif paren_string[i] == ')': # pop last index from stack and slice string
            start = stack.pop()
            result.append(paren_string[start:i+1])
    return result


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

    Return the decimal part of the number.
    """

Response:
def truncate_number(number: float) -> float:
    integer_part = number // 1
    decimal_part = number - integer_part
    return decimal_part


Prompt:
from typing import List

def below_zero(operations: List[int]) -> bool:
    """ You're given a list of deposit and withdrawal operations on a bank account that starts with
    zero balance. Your task is to detect if at any point the balance of account fallls below zero, and
    at that point function should return True. Otherwise it should return False.
    """

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


Prompt:
from typing import List

def mean_absolute_deviation(numbers: List[float]) -> float:
    """ For a given list of input numbers, calculate Mean Absolute Deviation
    around the mean of this dataset.
    Mean Absolute Deviation is the average absolute difference between each
    element and a centerpoint (mean in this case):
    MAD = average | x - x_mean |
    """

Response:
def mean_absolute_deviation(numbers: List[float]) -> float:
    mean = sum(numbers) / len(numbers)
    absolute_differences = [abs(num - mean) for num in numbers]
    return sum(absolute_differences) / len(absolute_differences)


Prompt:
from typing import List

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

Response:
def intersperse(numbers: List[int], delimeter: int) -> List[int]:
    new_list = []
    for i in range(len(numbers)):
        new_list.append(numbers[i])
        if i != len(numbers) - 1:
            new_list.append(delimeter)
    new_list.pop()
    return new_list


Prompt:
from typing import List

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

Response:
def parse_nested_parens(paren_string: str) -> List[int]:
    max_nesting = 0
    nesting = 0
    stack = []
    result = []
    for char in paren_string:
        if char == '(':  # opening parenthesis
            stack.append(char)
            nesting += 1
            max_nesting = max(max_nesting, nesting)
        elif char == ')':  # closing parenthesis
            stack.pop()
            nesting -= 1
        elif char == ' ':  # end of group
            result.append(max_nesting)
            max_nesting = 0
            nesting = 0
            stack = []
    result.append(max_nesting)  # last group
    return result


Prompt:
from typing import List

def filter_by_substring(strings: List[str], substring: str) -> List[str]:
    """ Filter an input list of strings only for ones that contain given substring
    """

Response:
def filter_by_substring(strings: List[str], substring: str) -> List[str]:
    return [s for s in strings if substring in s]


Prompt:
from typing import List, Tuple

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

Response:
def sum_product(numbers: List[int]) -> Tuple[int, int]:
    sum = 0
    product = 1
    for num in numbers:
        sum += num
        product *= num
    return (sum, product)


Prompt:
from typing import List, Tuple

def rolling_max(numbers: List[int]) -> List[int]:
    """ From a given list of integers, generate a list of rolling maximum element found until given moment
    in the sequence.
    """

Response:
def rolling_max(numbers: List[int]) -> List[int]:
    max_so_far = float('-inf')
    result = []
    for num in numbers:
        max_so_far = max(max_so_far, num)
        result.append(max_so_far)
    return result


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

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

Response:
def make_palindrome(string: str) -> str:
    for i in range(len(string), -1, -1):
        if is_palindrome(string[:i]):
            return string + string[:i][::-1]


Prompt:
from typing import List

def string_xor(a: str, b: str) -> str:
    """ Input are two strings a and b consisting only of 1s and 0s.
    Perform binary XOR on these inputs and return result also as a string.
    """

Response:
def string_xor(a: str, b: str) -> str:
    result = ''
    for i in range(len(a)):
        if a[i] == b[i]:
            result += '0'
        else:
            result += '1'
    return result


Prompt:
from typing import List, Optional

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

Response:
def longest(strings: List[str]) -> Optional[str]:
    if not strings:
        return None
    longest_str = strings[0]
    for string in strings:
        if len(string) > len(longest_str):
            longest_str = string
    return longest_str


Prompt:
def greatest_common_divisor(a: int, b: int) -> int:
    """ Return a greatest common divisor of two integers a and b
    """

Response:
def greatest_common_divisor(a: int, b: int) -> int:
    if b == 0:
        return a
    else:
        return greatest_common_divisor(b, a % b)


Prompt:
from typing import List

def all_prefixes(string: str) -> List[str]:
    """ Return list of all prefixes from shortest to longest of the input string
    """

Response:
def all_prefixes(string: str) -> List[str]:
    result = []
    for i in range(len(string)):
        result.append(string[:i+1])
    return result


Prompt:
def string_sequence(n: int) -> str:
    """ Return a string containing space-delimited numbers starting from 0 upto n inclusive.
    """

Response:
def string_sequence(n: int) -> str:
    result = ''
    for i in range(n+1):
        result += str(i) + ' '
    return result


Prompt:
def count_distinct_characters(string: str) -> int:
    """ Given a string, find out how many distinct characters (regardless of case) does it consist of
    """

Response:
def count_distinct_characters(string: str) -> int:
    string = string.lower()
    distinct_chars = set(string)
    return len(distinct_chars)


Prompt:
from typing import List

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

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

Response:
def parse_music(music_string: str) -> List[int]:
    result = []
    for note in music_string:
        if note == 'o':
            result.append(4)
        elif note == 'o|':
            result.append(2)
        elif note == '.|':
            result.append(1)
    return result


Prompt:
def how_many_times(string: str, substring: str) -> int:
    """ Find how many times a given substring can be found in the original string. Count overlaping cases.
    """

Response:
def how_many_times(string: str, substring: str) -> int:
    count = 0
    for i in range(len(string) - len(substring) + 1):
        if string[i:i+len(substring)] == substring:
            count += 1
    return count


Prompt:
from typing import List

def sort_numbers(numbers: str) -> str:
    """ Input is a space-delimited string of numberals from 'zero' to 'nine'.
    Valid choices are 'zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight' and 'nine'.
    Return the string with numbers sorted from smallest to largest
    """

Response:
def sort_numbers(numbers: str) -> str:
    num_dict = {'zero': 0, 'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5, 'six': 6, 'seven': 7, 'eight': 8, 'nine': 9}
    num_list = numbers.split()
    num_list = [num_dict[num] for num in num_list]
    num_list.sort()
    num_list = [list(num_dict.keys())[list(num_dict.values()).index(num)] for num in num_list]
    return ' '.join(num_list)


Prompt:
from typing import List, Tuple

def find_closest_elements(numbers: List[float]) -> Tuple[float, float]:
    """ From a supplied list of numbers (of length at least two) select and return two that are the closest to each
    other and return them in order (smaller number, larger number).
    """

Response:
def find_closest_elements(numbers: List[float]) -> Tuple[float, float]:
    numbers.sort()
    min_diff = float('inf')
    result = ()
    for i in range(len(numbers) - 1):
        diff = numbers[i+1] - numbers[i]
        if diff < min_diff:
            min_diff = diff
            result = (numbers[i], numbers[i+1])
    return result


Prompt:
from typing import List

def rescale_to_unit(numbers: List[float]) -> List[float]:
    """ Given list of numbers (of at least two elements), apply a linear transform to that list,
    such that the smallest number will become 0 and the largest will become 1
    """

Response:
def rescale_to_unit(numbers: List[float]) -> List[float]:
    min_num = min(numbers)
    max_num = max(numbers)
    range_num = max_num - min_num
    rescaled_numbers = [(num - min_num) / range_num for num in numbers]
    return rescaled_numbers


Prompt:
from typing import List, Any

def filter_integers(values: List[Any]) -> List[int]:
    """ Filter given list of any python values only for integers
    """

Response:
def filter_integers(values: List[Any]) -> List[int]:
    return [x for x in values if isinstance(x, int)]


Prompt:
def strlen(string: str) -> int:
    """ Return length of given string
    """

Response:
def strlen(string: str) -> int:
    return len(string)


Prompt:
def largest_divisor(n: int) -> int:
    """ For a given number n, find the largest number that divides n evenly, smaller than n
    """

Response:
def largest_divisor(n: int) -> int:
    for i in range(n-1, 0, -1):
        if n % i == 0:
            return i
    return 1


Prompt:
from typing import List

def factorize(n: int) -> List[int]:
    """ Return list of prime factors of given integer in the order from smallest to largest.
    Each of the factors should be listed number of times corresponding to how many times it appeares in factorization.
    Input number should be equal to the product of all factors
    """

Response:
def factorize(n: int) -> List[int]:
    factors = {}
    i = 2
    while n > 1:
        if n % i == 0:
            n //= i
            if i in factors:
                factors[i] += 1
            else:
                factors[i] = 1
        else:
            i += 1
    return [k for k, v in factors.items() for _ in range(v)]


Prompt:
from typing import List

def remove_duplicates(numbers: List[int]) -> List[int]:
    """ From a list of integers, remove all elements that occur more than once.
    Keep order of elements left the same as in the input.
    """

Response:
def remove_duplicates(numbers):
    frequency = {}
    for num in numbers:
        if num in frequency:
            frequency[num] += 1
        else:
            frequency[num] = 1
    result = []
    for num in numbers:
        if frequency[num] == 1:
            result.append(num)
    return result


Prompt:
def flip_case(string: str) -> str:
    """ For a given string, flip lowercase characters to uppercase and uppercase to lowercase.
    """

Response:
def flip_case(string: str) -> str:
    result = ''
    for char in string:
        if char.isupper():
            result += char.lower()
        elif char.islower():
            result += char.upper()
        else:
            result += char
    return result


Prompt:
from typing import List

def concatenate(strings: List[str]) -> str:
    """ Concatenate list of strings into a single string
    """

Response:
def concatenate(strings: List[str]) -> str:
    return ''.join(strings)


Prompt:
from typing import List

def filter_by_prefix(strings: List[str], prefix: str) -> List[str]:
    """ Filter an input list of strings only for ones that start with a given prefix.
    """

Response:
def filter_by_prefix(strings: List[str], prefix: str) -> List[str]:
    filtered_strings = [s for s in strings if s.startswith(prefix)]
    return filtered_strings


Prompt:
def get_positive(l: list):
    """Return only positive numbers in the list.
    """

Response:
def get_positive(l: list):
    return [num for num in l if num > 0]


Prompt:
def is_prime(n):
    """Return true if a given number is prime, and false otherwise.
    """

Response:
def is_prime(n):
    if n <= 1:
        return False
    for i in range(2, int(n**0.5)+1):
        if n % i == 0:
            return False
    return True


Prompt:
import math

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

def find_zero(xs: list):
    """ xs are coefficients of a polynomial.
    find_zero find x such that poly(x) = 0.
    find_zero returns only only zero point, even if there are many.
    Moreover, find_zero only takes list xs having even number of coefficients
    and largest non zero coefficient as it guarantees
    a solution.
    """

Response:
def find_zero(xs: list):
    x = 1.0
    while True:
        f = poly(xs, x)
        df = sum([i * xs[i] * math.pow(x, i-1) for i in range(1, len(xs))])
        x1 = x - f/df
        if abs(x1 - x) < 0.0001:
            return x1
        x = x1


Prompt:
def sort_third(l: list):
    """This function takes a list l and returns a list l' such that
    l' is identical to l in the indicies that are not divisible by three, while its values at the indicies that are divisible by three are equal
    to the values of the corresponding indicies of l, but sorted.
    """

Response:
def sort_third(l: list):
    third_indices = [i for i in range(len(l)) if i % 3 == 0]
    third_values = [l[i] for i in third_indices]
    sorted_third_values = sorted(third_values)
    for i in third_indices:
        l[i] = sorted_third_values[i // 3]
    return l


Prompt:
def unique(l: list):
    """Return sorted unique elements in a list
    """

Response:
def unique(l: list):
    unique_set = set(l)
    unique_list = list(unique_set)
    unique_list.sort()
    return unique_list


Prompt:
def max_element(l: list):
    """Return maximum element in the list.
    """

Response:
def max_element(l: list):
    return max(l)


Prompt:
def fizz_buzz(n: int):
    """Return the number of times the digit 7 appears in integers less than n which are divisible by 11 or 13.
    """

Response:
def fizz_buzz(n: int):
    count = 0
    for i in range(n):
        if i % 11 == 0 or i % 13 == 0:
            if str(i).count('7') > 0:
                count += 1
    return count


Prompt:
def sort_even(l: list):
    """This function takes a list l and returns a list l' such that
    l' is identical to l in the odd indicies, while its values at the even indicies are equal
    to the values of the even indicies of l, but sorted.
    """

Response:
def sort_even(l: list):
    even_list = []
    odd_list = []
    for i in range(len(l)):
        if i % 2 == 0:
            even_list.append(l[i])
        else:
            odd_list.append(l[i])
    even_list.sort()
    sorted_list = []
    for i in range(len(odd_list)):
        sorted_list.append(odd_list[i])
        sorted_list.append(even_list[i])
    if len(even_list) > len(odd_list):
        sorted_list.append(even_list[-1])
    return sorted_list


Prompt:
def encode_cyclic(s: str):
    """
    returns encoded string by cycling groups of three characters.
    """
    # split string to groups. Each of length 3.
    groups = [s[(3 * i):min((3 * i + 3), len(s))] for i in range((len(s) + 2) // 3)]
    # cycle elements in each group. Unless group has fewer elements than 3.
    groups = [(group[1:] + group[0]) if len(group) == 3 else group for group in groups]
    return "".join(groups)

def decode_cyclic(s: str):
    """
    takes as input string encoded with encode_cyclic function. Returns decoded string.
    """

Response:
def decode_cyclic(s: str):
    groups = [s[(3 * i):min((3 * i + 3), len(s))] for i in range((len(s) + 2) // 3)]
    groups = [(group[-1] + group[:2]) if len(group) == 3 else group for group in groups]
    return ''.join(groups)


Prompt:
def prime_fib(n: int):
    """
    prime_fib returns n-th number that is a Fibonacci number and it's also prime.
    """

Response:
def prime_fib(n: int):
    def is_prime(num):
        if num < 2:
            return False
        for i in range(2, int(num**0.5)+1):
            if num % i == 0:
                return False
        return True
    a, b = 0, 1
    count = 0
    while count < n:
        a, b = b, a+b
        if is_prime(a):
            count += 1
    return a


Prompt:
def triples_sum_to_zero(l: list):
    """
    triples_sum_to_zero takes a list of integers as an input.
    it returns True if there are three distinct elements in the list that
    sum to zero, and False otherwise.
    """

Response:
def triples_sum_to_zero(l):
    for i in range(len(l)):
        for j in range(i+1, len(l)):
            for k in range(j+1, len(l)):
                if l[i] + l[j] + l[k] == 0:
                    return True
    return False


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

    This function outputs the number of such collisions.
    """

Response:
def car_race_collision(n: int):
    return sum(n-i for i in range(n))


Prompt:
def incr_list(l: list):
    """Return list with elements incremented by 1.
    """

Response:
def incr_list(l: list):
    return [x+1 for x in l]


Prompt:
def pairs_sum_to_zero(l):
    """
    pairs_sum_to_zero takes a list of integers as an input.
    it returns True if there are two distinct elements in the list that
    sum to zero, and False otherwise.
    """

Response:
def pairs_sum_to_zero(l):
    seen = set()
    for num in l:
        if -num in seen:
            return True
        seen.add(num)
    return False


Prompt:
def change_base(x: int, base: int):
    """Change numerical base of input number x to base.
    return string representation after the conversion.
    base numbers are less than 10.
    """

Response:
def change_base(x: int, base: int):
    result = ''
    while x > 0:
        remainder = x % base
        result = str(remainder) + result
        x = x // base
    return result


Prompt:
def triangle_area(a, h):
    """Given length of a side and high return area for a triangle.
    """

Response:
def triangle_area(a, h):
    area = 0.5 * a * h
    return area


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

Response:
def fib4(n: int):
    if n < 4:
        return [0, 0, 2, 0][n]
    prev = [0, 0, 2, 0]
    for i in range(4, n+1):
        curr = prev[0] + prev[1] + prev[2] + prev[3]
        prev = prev[1:] + [curr]
    return prev[-1]


Prompt:
def median(l: list):
    """Return median of elements in the list l.
    """

Response:
def median(l: list):
    l.sort()
    n = len(l)
    if n % 2 == 0:
        return (l[n//2-1] + l[n//2])/2
    else:
        return l[n//2]


Prompt:
def is_palindrome(text: str):
    """
    Checks if given string is a palindrome
    """

Response:
def is_palindrome(text: str):
    start = 0
    end = len(text) - 1
    while start < end:
        if text[start] != text[end]:
            return False
        start += 1
        end -= 1
    return True


Prompt:
def modp(n: int, p: int):
    """Return 2^n modulo p (be aware of numerics).
    """

Response:
def modp(n: int, p: int):
    return pow(2, n, p)


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

def decode_shift(s: str):
    """
    takes as input string encoded with encode_shift function. Returns decoded string.
    """

Response:
def decode_shift(s: str):
    return ''.join([chr(((ord(ch) - 5 - ord('a')) % 26) + ord('a')) for ch in s])


Prompt:
def remove_vowels(text):
    """
    remove_vowels is a function that takes string and returns string without vowels.
    """

Response:
def remove_vowels(text):
    vowels = 'aeiouAEIOU'
    new_text = ''
    for char in text:
        if char not in vowels:
            new_text += char
    return new_text


Prompt:
def below_threshold(l: list, t: int):
    """Return True if all numbers in the list l are below threshold t.
    """

Response:
def below_threshold(l: list, t: int):
    for num in l:
        if num >= t:
            return False
    return True


Prompt:
def add(x: int, y: int):
    """Add two numbers x and y
    """

Response:
def add(x: int, y: int):
    return x + y


Prompt:
def same_chars(s0: str, s1: str):
    """
    Check if two words have the same characters.
    """

Response:
def same_chars(s0: str, s1: str):
    return set(s0) == set(s1)


Prompt:
def fib(n: int):
    """Return n-th Fibonacci number.
    """

Response:
def fib(n):
    if n == 0:
        return 0
    elif n == 1:
        return 1
    else:
        return fib(n-1) + fib(n-2)


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

Response:
def correct_bracketing(brackets: str):
    stack = []
    for bracket in brackets:
        if bracket == '<':
            stack.append(bracket)
        elif bracket == '>':
            if not stack or stack.pop() != '<':
                return False
    return not stack


Prompt:
def monotonic(l: list):
    """Return True is list elements are monotonically increasing or decreasing.
    """

Response:
def monotonic(l: list):
    if len(l) <= 1:
        return True
    increasing = all(l[i] <= l[i+1] for i in range(len(l)-1))
    decreasing = all(l[i] >= l[i+1] for i in range(len(l)-1))
    return increasing or decreasing


Prompt:
def common(l1: list, l2: list):
    """Return sorted unique common elements for two lists.
    """

Response:
def common(l1: list, l2: list):
    common_set = set(l1).intersection(set(l2))
    return sorted(list(common_set))


Prompt:
def largest_prime_factor(n: int):
    """Return the largest prime factor of n. Assume n > 1 and is not a prime.
    """

Response:
def largest_prime_factor(n: int):
    factor = 2
    while factor <= n:
        if n % factor == 0:
            n //= factor
        else:
            factor += 1
    return factor


Prompt:
def sum_to_n(n: int):
    """sum_to_n is a function that sums numbers from 1 to n.
    """

Response:
def sum_to_n(n: int):
    total = 0
    for i in range(1, n+1):
        total += i
    return total


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

Response:
def correct_bracketing(brackets: str):
    stack = []
    for bracket in brackets:
        if bracket == '(': # opening bracket
            stack.append(bracket)
        else: # closing bracket
            if not stack or stack.pop() != '(': # stack is empty or top element does not match
                return False
    return not stack # return True if stack is empty, False otherwise


Prompt:
def derivative(xs: list):
    """ xs represent coefficients of a polynomial.
    xs[0] + xs[1] * x + xs[2] * x^2 + ....
     Return derivative of this polynomial in the same form.
    """

Response:
def derivative(xs: list):
    derivative = []
    for i in range(1, len(xs)):
        derivative.append(xs[i] * i)
    return derivative


Prompt:
def fibfib(n: int):
    """The FibFib number sequence is a sequence similar to the Fibbonacci sequnece that's defined as follows:
    fibfib(0) == 0
    fibfib(1) == 0
    fibfib(2) == 1
    fibfib(n) == fibfib(n-1) + fibfib(n-2) + fibfib(n-3).
    Please write a function to efficiently compute the n-th element of the fibfib number sequence.
    """

Response:
def fibfib(n):
    if n == 0:
        return 0
    elif n == 1:
        return 0
    elif n == 2:
        return 1
    else:
        fibfib_list = [0, 0, 1]
        for i in range(3, n+1):
            fibfib_list.append(fibfib_list[i-1] + fibfib_list[i-2] + fibfib_list[i-3])
        return fibfib_list[n]


Prompt:
FIX = """
Add more test cases.
"""

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

Response:
def vowels_count(s):
    vowels = ['a', 'e', 'i', 'o', 'u']
    count = 0
    for i in range(len(s)):
        if s[i] in vowels:
            count += 1
        if i == len(s) - 1 and s[i] == 'y':
            count += 1
    return count


Prompt:
def circular_shift(x, shift):
    """Circular shift the digits of the integer x, shift the digits right by shift
    and return the result as a string.
    If shift > number of digits, return digits reversed.
    """

Response:
def circular_shift(x, shift):
    x_str = str(x)
    n = len(x_str)
    if shift > n:
        return x_str[::-1][(shift-n)%n:] + x_str[::-1][:(shift-n)%n]
    else:
        return x_str[-shift:] + x_str[:-shift]


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

Response:
def digitSum(s):
    sum = 0
    for char in s:
        if char.isupper():
            sum += ord(char)
    return sum


Prompt:
def fruit_distribution(s,n):
    """
    In this task, you will be given a string that represents a number of apples and oranges
    that are distributed in a basket of fruit this basket contains
    apples, oranges, and mango fruits. Given the string that represents the total number of
    the oranges and apples and an integer that represent the total number of the fruits
    in the basket return the number of the mango fruits in the basket.
    """

Response:
def fruit_distribution(s,n):
    total_apples_oranges = 0
    for char in s:
        if char == 'a' or char == 'o':
            total_apples_oranges += 1
    mangoes = n - total_apples_oranges
    return mangoes


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

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

    Constraints:
        * 1 <= nodes.length <= 10000
        * 0 <= node.value
    """

Response:
def pluck(arr):
    smallest_even = float('inf')
    smallest_even_index = float('inf')
    for i in range(len(arr)):
        if arr[i] % 2 == 0 and arr[i] < smallest_even:
            smallest_even = arr[i]
            smallest_even_index = i
    if smallest_even_index == float('inf'):
        return []
    else:
        return [smallest_even, smallest_even_index]


Prompt:
def search(lst):
    '''
    You are given a non-empty list of positive integers. Return the greatest integer that is greater than
    zero, and has a frequency greater than or equal to the value of the integer itself.
    The frequency of an integer is the number of times it appears in the list.
    If no such a value exist, return -1.
    '''

Response:
def search(lst):
    freq = {}
    for num in lst:
        if num in freq:
            freq[num] += 1
        else:
            freq[num] = 1
    max_num = -1
    for num in freq:
        if freq[num] >= num and num > max_num:
            max_num = num
    return max_num


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

Response:
def strange_sort_list(lst):
    lst.sort()
    result = []
    i = 0
    j = len(lst) - 1
    while i <= j:
        if i == j:
            result.append(lst[i])
        else:
            result.append(lst[i])
            result.append(lst[j])
        i += 1
        j -= 1
    return result


Prompt:
def triangle_area(a, b, c):
    '''
    Given the lengths of the three sides of a triangle. Return the area of
    the triangle rounded to 2 decimal points if the three sides form a valid triangle.
    Otherwise return -1
    Three sides make a valid triangle when the sum of any two sides is greater
    than the third side.
    '''

Response:
def triangle_area(a, b, c):
    if a + b > c and b + c > a and a + c > b:
        s = (a + b + c) / 2
        area = (s * (s - a) * (s - b) * (s - c)) ** 0.5
        return round(area, 2)
    else:
        return -1


Prompt:
def will_it_fly(q,w):
    '''
    Write a function that returns True if the object q will fly, and False otherwise.
    The object q will fly if it's balanced (it is a palindromic list) and the sum of its elements is less than or equal the maximum possible weight w.
    '''

Response:
def will_it_fly(q, w):
    if q == q[::-1] and sum(q) <= w:
        return True
    else:
        return False


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

Response:
def smallest_change(arr):
    count = 0
    for i in range(len(arr)//2):
        if arr[i] != arr[-i-1]:
            count += 1
    return count


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

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

Response:
def total_match(lst1, lst2):
    total1 = sum(len(s) for s in lst1)
    total2 = sum(len(s) for s in lst2)
    if total1 < total2:
        return lst1
    else:
        return lst2 if total2 < total1 else lst1


Prompt:
def is_multiply_prime(a):
    """Write a function that returns true if the given number is the multiplication of 3 prime numbers
    and false otherwise.
    Knowing that (a) is less then 100.
    """

Response:
def is_multiply_prime(a):
    # Generate all prime numbers less than 100 using Sieve of Eratosthenes algorithm
    primes = [True] * 100
    primes[0] = primes[1] = False
    for i in range(2, int(100 ** 0.5) + 1):
        if primes[i]:
            for j in range(i ** 2, 100, i):
                primes[j] = False

    # Check all possible combinations of 3 prime numbers
    for i in range(2, 100):
        if primes[i]:
            for j in range(i, 100):
                if primes[j]:
                    for k in range(j, 100):
                        if primes[k] and i * j * k == a:
                            return True
    return False


Prompt:
def is_simple_power(x, n):
    """Your task is to write a function that returns true if a number x is a simple
    power of n and false in other cases.
    x is a simple power of n if n**int=x
    """

Response:
def is_simple_power(x, n):
    log_x = math.log(x, n)
    return log_x.is_integer()


Prompt:
def iscube(a):
    '''
    Write a function that takes an integer a and returns True
    if this ingeger is a cube of some integer number.
    Note: you may assume the input is always valid.
    '''

Response:
def iscube(a):
    cube_root = a**(1/3)
    return cube_root == int(cube_root)


Prompt:
def hex_key(num):
    """You have been tasked to write a function that receives
    a hexadecimal number as a string and counts the number of hexadecimal
    digits that are primes (prime number, or a prime, is a natural number
    greater than 1 that is not a product of two smaller natural numbers).
    Hexadecimal digits are 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F.
    Prime numbers are 2, 3, 5, 7, 11, 13, 17,...
    So you have to determine a number of the following digits: 2, 3, 5, 7,
    B (=decimal 11), D (=decimal 13).
    Note: you may assume the input is always correct or empty string,
    and symbols A,B,C,D,E,F are always uppercase.
    """

Response:
def hex_key(num):
    prime_hex_digits = ['2', '3', '5', '7', 'B', 'D']
    count = 0
    for digit in num:
        if digit in prime_hex_digits:
            count += 1
    return count


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

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

Response:
def decimal_to_binary(decimal):
    binary_list = []
    while decimal > 0:
        remainder = decimal % 2
        binary_list.append(str(remainder))
        decimal = decimal // 2
    binary_list.reverse()
    binary_string = ''.join(binary_list)
    return 'db' + binary_string + 'db'


Prompt:
def is_happy(s):
    """You are given a string s.
    Your task is to check if the string is happy or not.
    A string is happy if its length is at least 3 and every 3 consecutive letters are distinct
    """

Response:
def is_happy(s):
    if len(s) < 3:
        return False
    for i in range(len(s) - 2):
        if s[i] == s[i+1] or s[i] == s[i+2] or s[i+1] == s[i+2]:
            return False
    return True


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

Response:
def numerical_letter_grade(grades):
    letter_grades = []
    for gpa in grades:
        if gpa == 4.0:
            letter_grades.append('A+')
        elif gpa > 3.7:
            letter_grades.append('A')
        elif gpa > 3.3:
            letter_grades.append('A-')
        elif gpa > 3.0:
            letter_grades.append('B+')
        elif gpa > 2.7:
            letter_grades.append('B')
        elif gpa > 2.3:
            letter_grades.append('B-')
        elif gpa > 2.0:
            letter_grades.append('C+')
        elif gpa > 1.7:
            letter_grades.append('C')
        elif gpa > 1.3:
            letter_grades.append('C-')
        elif gpa > 1.0:
            letter_grades.append('D+')
        elif gpa > 0.7:
            letter_grades.append('D')
        elif gpa > 0.0:
            letter_grades.append('D-')
        else:
            letter_grades.append('E')
    return letter_grades


Prompt:
def prime_length(string):
    """Write a function that takes a string and returns True if the string
    length is a prime number or False otherwise
    """

Response:
def prime_length(string):
    if len(string) < 2:
        return False
    for i in range(2, int(len(string)**0.5)+1):
        if len(string) % i == 0:
            return False
    return True


Prompt:
def starts_one_ends(n):
    """
    Given a positive integer n, return the count of the numbers of n-digit
    positive integers that start or end with 1.
    """

Response:
def starts_one_ends(n):
    return 9 * 10**(n-1)


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

    Variables:
        @N integer
             Constraints: 0 ≤ N ≤ 10000.
    Output:
         a string of binary number
    """

Response:
def solve(N):
    binary = bin(N)[2:]
    total_sum = 0
    for digit in binary:
        total_sum += int(digit)
    return bin(total_sum)[2:]


Prompt:
def add(lst):
    """Given a non-empty list of integers lst. add the even elements that are at odd indices..
    """

Response:
def add(lst):
    total = 0
    for i in range(len(lst)):
        if i % 2 == 1 and lst[i] % 2 == 0:
            total += lst[i]
    return total


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

Response:
def anti_shuffle(s):
    words = s.split()
    ordered_words = []
    for word in words:
        ordered_word = ''.join(sorted(word))
        ordered_words.append(ordered_word)
    return ' '.join(ordered_words)


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

Response:
def get_row(lst, x):
    result = []
    for i in range(len(lst)):
        if x in lst[i]:
            for j in range(len(lst[i])):
                if lst[i][j] == x:
                    result.append((i, j))
    result.sort(key=lambda x: (x[0], -x[1]))
    return result


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

    Note:
    * don't change the given array.
    """

Response:
def sort_array(array):
    sum_first_last = array[0] + array[-1]
    if sum_first_last % 2 == 0:
        return sorted(array, reverse=True)
    else:
        return sorted(array)


Prompt:
def encrypt(s):
    """Create a function encrypt that takes a string as an argument and
    returns a string encrypted with the alphabet being rotated.
    The alphabet should be rotated in a manner such that the letters
    shift down by two multiplied to two places.
    """

Response:
def encrypt(s):
    shift = 2 * 2
    encrypted = ''
    for char in s:
        if char.isalpha():
            if char.islower():
                encrypted += chr((ord(char) - 97 + shift) % 26 + 97)
            else:
                encrypted += chr((ord(char) - 65 + shift) % 26 + 65)
        else:
            encrypted += char
    return encrypted


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

Response:
def next_smallest(lst):
    if len(lst) < 2:
        return None
    sorted_lst = sorted(lst)
    return sorted_lst[1]


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

Response:
def is_bored(S):
    boredom_count = 0
    sentences = re.split('[.?!]', S)
    for sentence in sentences:
        if sentence.strip().startswith('I'):
            boredom_count += 1
    return boredom_count


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

Response:
def any_int(x, y, z):
    for i in [x, y, z]:
        for j in [x, y, z]:
            for k in [x, y, z]:
                if i != j and i != k and j != k:
                    if i == j + k or j == i + k or k == i + j:
                        if isinstance(i, int) and isinstance(j, int) and isinstance(k, int):
                            return True
    return False


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

Response:
def encode(message):
    encoded_message = ''
    vowels = 'aeiouAEIOU'
    for char in message:
        if char in vowels:
            encoded_message += chr(ord(char)+2)
        else:
            if char.isupper():
                encoded_message += char.lower()
            else:
                encoded_message += char.upper()
    return encoded_message


Prompt:
def skjkasdkd(lst):
    """You are given a list of integers.
    You need to find the largest prime value and return the sum of its digits.
    """

Response:
def skjkasdkd(lst):
    def is_prime(n):
        if n < 2:
            return False
        for i in range(2, int(n**0.5)+1):
            if n % i == 0:
                return False
        return True
    largest_prime = 0
    for num in lst:
        if is_prime(num):
            digit_sum = sum(int(digit) for digit in str(num))
            if digit_sum > sum(int(digit) for digit in str(largest_prime)):
                largest_prime = num
    return sum(int(digit) for digit in str(largest_prime))


Prompt:
def check_dict_case(dict):
    """
    Given a dictionary, return True if all keys are strings in lower
    case or all keys are strings in upper case, else return False.
    The function should return False is the given dictionary is empty.
    """

Response:
def check_dict_case(dict):
    if len(dict) == 0:
        return False
    is_lower = all(key.islower() for key in dict.keys())
    is_upper = all(key.isupper() for key in dict.keys())
    return is_lower or is_upper


Prompt:
def count_up_to(n):
    """Implement a function that takes an non-negative integer and returns an array of the first n
    integers that are prime numbers and less than n.
    """

Response:
def count_up_to(n):
    primes = []
    for num in range(2, n):
        is_prime = True
        for i in range(2, int(num ** 0.5) + 1):
            if num % i == 0:
                is_prime = False
                break
        if is_prime:
            primes.append(num)
            if len(primes) == n:
                break
    return primes


Prompt:
def multiply(a, b):
    """Complete the function that takes two integers and returns
    the product of their unit digits.
    Assume the input is always valid.
    """

Response:
def multiply(a, b):
    return (a % 10) * (b % 10)


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

Response:
def count_upper(s):
    vowels = set(['A', 'E', 'I', 'O', 'U'])
    count = 0
    for i in range(0, len(s), 2):
        if s[i] in vowels and s[i].isupper():
            count += 1
    return count


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

    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.
    '''

Response:
def closest_integer(value):
    num = float(value)
    rounded_num = round(num)
    if num == rounded_num:
        return int(num)
    elif num > 0:
        return int(rounded_num + 1)
    else:
        return int(rounded_num - 1)


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

Response:
def make_a_pile(n):
    stones = n
    result = [stones]
    for i in range(2, n+1):
        if n % 2 == 0:
            stones += i if i % 2 == 0 else i+1
        else:
            stones += i if i % 2 != 0 else i+1
        result.append(stones)
    return result


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

Response:
def words_string(s):
    words = s.split(', ')
    words = ' '.join(words).split()
    return words


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

Response:
def choose_num(x, y):
    for i in range(y, x-1, -1):
        if i % 2 == 0:
            return i
    return -1


Prompt:
def rounded_avg(n, m):
    """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.
    """

Response:
def rounded_avg(n, m):
    if n > m:
        return -1
    else:
        sum_of_integers = (m*(m+1))/2 - (n-1)*n/2
        num_of_integers = m - n + 1
        avg = round(sum_of_integers/num_of_integers)
        return bin(avg)[2:]


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

    Note: Returned list should be sorted in increasing order.
    """

Response:
def unique_digits(x):
    result = []
    for num in x:
        if all(int(digit) % 2 != 0 for digit in str(num)):
            result.append(num)
    return sorted(result)
}


Prompt:
def by_length(arr):
    """
    Given an array of integers, sort the integers that are between 1 and 9 inclusive,
    reverse the resulting array, and then replace each digit by its corresponding name from
    "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine".
    """

Response:
def by_length(arr):
    digits = [num for num in arr if 1 <= num <= 9]
    digits.sort()
    digits.reverse()
    names = ['One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine']
    result = [names[digit-1] for digit in digits]
    return result


Prompt:
def f(n):
    """ 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).
    """

Response:
def f(n):
    def factorial(num):
        if num == 0:
            return 1
        else:
            return num * factorial(num-1)
    result = []
    for i in range(1, n+1):
        if i % 2 == 0:
            result.append(factorial(i))
        else:
            sum = 0
            for j in range(1, i+1):
                sum += j
            result.append(sum)
    return result


Prompt:
def even_odd_palindrome(n):
    """
    Given a positive integer n, return a tuple that has the number of even and odd
    integer palindromes that fall within the range(1, n), inclusive.

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

Response:
def even_odd_palindrome(n):
    even_count = 0
    odd_count = 0
    for i in range(1, n+1):
        if str(i) == str(i)[::-1]:
            if i % 2 == 0:
                even_count += 1
            else:
                odd_count += 1
    return (even_count, odd_count)


Prompt:
def count_nums(arr):
    """
    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.
    """

Response:
def count_nums(arr):
    def sum_of_digits(num):
        s = 0
        while num:
            s += num % 10
            num //= 10
        return s

    count = 0
    for num in arr:
        if num >= 0:
            if sum_of_digits(num) > 0:
                count += 1
        else:
            if sum_of_digits(-num) > 0:
                count += 1

    return count


Prompt:
def move_one_ball(arr):
    """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.
    """

Response:
def move_one_ball(arr):
    if not arr:
        return True
    max_index = arr.index(max(arr))
    return max_index == len(arr)-1
}


Prompt:
def exchange(lst1, lst2):
    """In this problem, you will implement a function that takes two lists of numbers,
    and determines whether it is possible to perform an exchange of elements
    between them to make lst1 a list of only even numbers.
    There is no limit on the number of exchanged elements between lst1 and lst2.
    If it is possible to exchange elements between the lst1 and lst2 to make
    all the elements of lst1 to be even, return "YES".
    Otherwise, return "NO".

    It is assumed that the input lists will be non-empty.
    """

Response:
def exchange(lst1, lst2):
    if all(num % 2 == 0 for num in lst1):
        return 'YES'
    while True:
        odd_index = next((i for i, num in enumerate(lst1) if num % 2 != 0), None)
        if odd_index is None:
            return 'YES'
        even_index = next((i for i, num in enumerate(lst2) if num % 2 == 0), None)
        if even_index is None:
            return 'NO'
        lst1[odd_index], lst2[even_index] = lst2[even_index], lst1[odd_index]


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

Response:
def histogram(test):
    count_dict = {}
    max_count = 0
    for letter in test:
        if letter in count_dict:
            count_dict[letter] += 1
        else:
            count_dict[letter] = 1
        if count_dict[letter] > max_count:
            max_count = count_dict[letter]
    result = {}
    for letter, count in count_dict.items():
        if count == max_count:
            result[letter] = count
    return result


Prompt:
def reverse_delete(s,c):
    """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.
    """

Response:
def reverse_delete(s, c):
    new_s = ''
    for char in s:
        if char not in c:
            new_s += char
    if new_s == new_s[::-1]:
        return (new_s, True)
    else:
        return (new_s, False)


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

Response:
def odd_count(lst):
    result = []
    for string in lst:
        count = 0
        for digit in string:
            if int(digit) % 2 != 0:
                count += 1
        result.append(count)
    return result


Prompt:
def minSubArraySum(nums):
    """
    Given an array of integers nums, find the minimum sum of any non-empty sub-array
    of nums.
    """

Response:
def minSubArraySum(nums):
    current_sum = min_sum = nums[0]
    for num in nums[1:]:
        current_sum += num
        if current_sum < 0:
            current_sum = 0
        min_sum = min(min_sum, current_sum)
    return min_sum


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

    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
    """

Response:
def max_fill(grid, capacity):
    num_lowering = 0
    remaining_capacity = capacity
    for row in grid:
        for well in row:
            if well == 1:
                if remaining_capacity == 0:
                    num_lowering += 1
                    remaining_capacity = capacity
                remaining_capacity -= 1
        if remaining_capacity < capacity:
            num_lowering += 1
            remaining_capacity = capacity
    return num_lowering


Prompt:
def sort_array(arr):
    """
    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.
    """

Response:
def sort_array(arr):
    def count_ones(num):
        return bin(num).count('1'), num
    return sorted(arr, key=count_ones)
}


Prompt:
def select_words(s, n):
    """Given a string s and a natural number n, you have been tasked to implement
    a function that returns a list of all words from string s that contain exactly
    n consonants, in order these words appear in the string s.
    If the string s is empty then the function should return an empty list.
    Note: you may assume the input string contains only letters and spaces.
    """

Response:
def select_words(s, n):
    result = []
    if not s:
        return result
    words = s.split()
    for word in words:
        consonants = 0
        for letter in word:
            if letter.lower() not in ['a', 'e', 'i', 'o', 'u'] and letter.isalpha():
                consonants += 1
        if consonants == n:
            result.append(word)
    return result


Prompt:
def get_closest_vowel(word):
    """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.
    """

Response:
def get_closest_vowel(word):
    vowels = set(['a', 'e', 'i', 'o', 'u'])
    found_consonant = False
    for i in range(len(word)-2, 0, -1):
        if word[i] not in vowels:
            found_consonant = True
        elif found_consonant:
            return word[i]
    return ''


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

Response:
def match_parens(lst):
    s1, s2 = lst
    total_open = s1.count('(') + s2.count('(')
    total_close = s1.count(')') + s2.count(')')
    if total_open % 2 == 1 or total_close % 2 == 1:
        return 'No'
    else:
        concatenated = s1 + s2
        open_count = 0
        close_count = 0
        for c in concatenated:
            if c == '(': open_count += 1
            elif c == ')': close_count += 1
            if close_count > open_count:
                return 'No'
        if open_count == close_count:
            return 'Yes'
        else:
            return 'No'


Prompt:
def maximum(arr, k):
    """
    Given an array arr of integers and a positive integer k, return a sorted list
    of length k with the maximum k numbers in arr.

    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)
    """

Response:
def maximum(arr, k):
    sorted_arr = sorted(arr, reverse=True)
    return sorted_arr[:k]


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

Response:
def solution(lst):
    odd_sum = 0
    for i in range(len(lst)):
        if i % 2 == 0 and lst[i] % 2 != 0:
            odd_sum += lst[i]
    return odd_sum


Prompt:
def add_elements(arr, k):
    """
    Given a non-empty array of integers arr and an integer k, return
    the sum of the elements with at most two digits from the first k elements of arr.

    Constraints:
        1. 1 <= len(arr) <= 100
        2. 1 <= k <= len(arr)
    """

Response:
def add_elements(arr, k):
    sum = 0
    for i in range(k):
        if abs(arr[i]) < 100:
            sum += arr[i]
    return sum


Prompt:
def get_odd_collatz(n):
    """
    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.
    """

Response:
def get_odd_collatz(n):
    if n == 1:
        return [1]
    elif n % 2 == 0:
        return get_odd_collatz(n//2)
    else:
        odd_collatz = [n]
        odd_collatz.extend(get_odd_collatz(3*n + 1))
        return sorted(list(set(filter(lambda x: x%2 != 0, odd_collatz))))


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

Response:
def valid_date(date):
    try:
        month, day, year = map(int, date.split('-'))
    except ValueError:
        return False
    if month < 1 or month > 12:
        return False
    if month in [1, 3, 5, 7, 8, 10, 12]:
        if day < 1 or day > 31:
            return False
    elif month in [4, 6, 9, 11]:
        if day < 1 or day > 30:
            return False
    elif month == 2:
        if year % 4 == 0 and (year % 100 != 0 or year % 400 == 0):
            if day < 1 or day > 29:
                return False
        else:
            if day < 1 or day > 28:
                return False
    else:
        return False
    if len(date) != 10 or date[2] != '-' or date[5] != '-':
        return False
    return True


Prompt:
def split_words(txt):
    '''
    Given a string of words, return a list of words split on whitespace, if no whitespaces exists in the text you
    should split on commas ',' if no commas exists you should return the number of lower-case letters with odd order in the
    alphabet, ord('a') = 0, ord('b') = 1, ... ord('z') = 25
    '''

Response:
def split_words(txt):
    words = txt.split()
    if len(words) == 1:
        words = txt.split(',')
        if len(words) == 1:
            count = 0
            for c in txt:
                if c.islower() and ord(c) % 2 == 1:
                    count += 1
            return count
    return words


Prompt:
def is_sorted(lst):
    '''
    Given a list of numbers, return whether or not they are sorted
    in ascending order. If list has more than 1 duplicate of the same
    number, return False. Assume no negative numbers and only integers.
    '''

Response:
def is_sorted(lst):
    if len(set(lst)) != len(lst):
        return False
    return lst == sorted(lst)


Prompt:
def intersection(interval1, interval2):
    """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".
    """

Response:
def intersection(interval1, interval2):
    def is_prime(n):
        if n <= 1:
            return False
        for i in range(2, int(n**0.5)+1):
            if n % i == 0:
                return False
        return True
    start = max(interval1[0], interval2[0])
    end = min(interval1[1], interval2[1])
    if start > end:
        return 'NO'
    length = end - start + 1
    if is_prime(length):
        return 'YES'
    else:
        return 'NO'


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

Response:
def prod_signs(arr):
    if not arr:
        return None
    sign_product = 1
    magnitude_sum = 0
    for num in arr:
        sign_product *= 1 if num > 0 else -1 if num < 0 else 0
        magnitude_sum += abs(num)
    return sign_product * magnitude_sum


Prompt:
def minPath(grid, k):
    """
    Given a grid with N rows and N columns (N >= 2) and a positive integer k,
    each cell of the grid contains a value. Every integer in the range [1, N * N]
    inclusive appears exactly once on the cells of the grid.

    You have to find the minimum path of length k in the grid. You can start
    from any cell, and in each step you can move to any of the neighbor cells,
    in other words, you can go to cells which share an edge with you current
    cell.
    Please note that a path of length k means visiting exactly k cells (not
    necessarily distinct).
    You CANNOT go off the grid.
    A path A (of length k) is considered less than a path B (of length k) if
    after making the ordered lists of the values on the cells that A and B go
    through (let's call them lst_A and lst_B), lst_A is lexicographically less
    than lst_B, in other words, there exist an integer index i (1 <= i <= k)
    such that lst_A[i] < lst_B[i] and for any j (1 <= j < i) we have
    lst_A[j] = lst_B[j].
    It is guaranteed that the answer is unique.
    Return an ordered list of the values on the cells that the minimum path go through.
    """

Response:
def minPath(grid, k):
    n = len(grid)
    dp = [[[None for _ in range(k+1)] for _ in range(n)] for _ in range(n)]
    for i in range(n):
        for j in range(n):
            dp[i][j][1] = [grid[i][j]]
    for l in range(2, k+1):
        for i in range(n):
            for j in range(n):
                path = []
                for x, y in [(i-1,j), (i+1,j), (i,j-1), (i,j+1)]:
                    if 0 <= x < n and 0 <= y < n and dp[x][y][l-1] is not None:
                        temp_path = [grid[i][j]] + dp[x][y][l-1]
                        if not path or temp_path < path:
                            path = temp_path
                dp[i][j][l] = path
    min_path = dp[0][0][k]
    for i in range(n):
        for j in range(n):
            if dp[i][j][k] is not None and dp[i][j][k] < min_path:
                min_path = dp[i][j][k]
    return min_path


Prompt:
def tri(n):
    """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.
    """

Response:
def tri(n):
    if n == 0:
        return [0]
    elif n == 1:
        return [3]
    elif n == 2:
        return [3, 2]
    else:
        tribonacci = [0] * (n+1)
        tribonacci[0] = 0
        tribonacci[1] = 3
        tribonacci[2] = 2
        for i in range(3, n+1):
            if i % 2 == 0:
                tribonacci[i] = 1 + i//2
            else:
                tribonacci[i] = tribonacci[i-1] + tribonacci[i-2] + tribonacci[i-3]
        return tribonacci


Prompt:
def digits(n):
    """Given a positive integer n, return the product of the odd digits.
    Return 0 if all digits are even.
    """

Response:
def digits(n):
    product = 1
    has_odd_digit = False
    for digit in str(n):
        if int(digit) % 2 == 1:
            product *= int(digit)
            has_odd_digit = True
    if has_odd_digit:
        return product
    else:
        return 0


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

Response:
def is_nested(string):
    stack = []
    for bracket in string:
        if bracket == '[':
            stack.append(bracket)
        elif bracket == ']':
            if not stack or stack[-1] != '[':
                continue
            stack.pop()
            if not stack:
                return False
    return True


Prompt:
def sum_squares(lst):
    """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.
    """

Response:
def sum_squares(lst):
    import math
    total = 0
    for num in lst:
        rounded_num = math.ceil(num)
        total += rounded_num ** 2
    return total


Prompt:
def check_if_last_char_is_a_letter(txt):
    '''
    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.
    '''

Response:
def check_if_last_char_is_a_letter(txt):
    words = txt.split()
    last_word = words[-1]
    if len(last_word) == len(txt):
        return last_word.isalpha()
    else:
        return last_word[-1].isalpha() and txt[-1] == last_word[-1]


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

Response:
def can_arrange(arr):
    for i in range(1, len(arr)):
        if arr[i] < arr[i-1]:
            return i-1
    return -1


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

Response:
def largest_smallest_integers(lst):
    largest_negative = None
    smallest_positive = None
    for num in lst:
        if num < 0 and (largest_negative is None or num > largest_negative):
            largest_negative = num
        elif num > 0 and (smallest_positive is None or num < smallest_positive):
            smallest_positive = num
    return (largest_negative, smallest_positive)


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

Response:
def compare_one(a, b):
    if type(a) == type(b):
        if a > b:
            return a
        elif b > a:
            return b
        else:
            return None
    else:
        a_float = float(a.replace(',', '.')) if type(a) == str else float(a)
        b_float = float(b.replace(',', '.')) if type(b) == str else float(b)
        if a_float > b_float:
            return a
        elif b_float > a_float:
            return b
        else:
            return None


Prompt:
def is_equal_to_sum_even(n):
    """Evaluate whether the given number n can be written as the sum of exactly 4 positive even numbers
    """

Response:
def is_equal_to_sum_even(n):
    if n < 8 or n % 2 != 0:
        return False
    for i in range(2, n//2 + 1, 2):
        for j in range(2, n//2 + 1, 2):
            for k in range(2, n//2 + 1, 2):
                for l in range(2, n//2 + 1, 2):
                    if i + j + k + l == n:
                        return True
    return False


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

    The function will receive an integer as input and should return the special
    factorial of this integer.
    """

Response:
def special_factorial(n):
    result = 1
    for i in range(n, 0, -1):
        factorial = 1
        for j in range(i, 0, -1):
            factorial *= j
        result *= factorial
    return result


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

Response:
def fix_spaces(text):
    result = ''
    count = 0
    for char in text:
        if char == ' ':
            count += 1
            if count > 2:
                continue
            result += '_'
        else:
            if count > 2:
                result += '-'
            else:
                result += char
            count = 0
    return result


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

Response:
def file_name_check(file_name):
    import re
    pattern = r'^[a-zA-Z][a-zA-Z0-9]*[a-zA-Z0-9]*\.[txt|exe|dll]{3}$'
    if re.match(pattern, file_name):
        return 'Yes'
    else:
        return 'No'


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

Response:
def sum_squares(lst):
    sum = 0
    for i in range(len(lst)):
        if i % 3 == 0:
            sum += lst[i]**2
        elif i % 4 == 0 and i % 3 != 0:
            sum += lst[i]**3
        else:
            sum += lst[i]
    return sum


Prompt:
def words_in_sentence(sentence):
    """
    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.

    Constraints:
        * 1 <= len(sentence) <= 100
        * sentence contains only letters
    """

Response:
def is_prime(n):
    if n <= 1:
        return False
    for i in range(2, int(n**0.5)+1):
        if n % i == 0:
            return False
    return True


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

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

Response:
def simplify(x, n):
    x_num, x_den = map(int, x.split('/'))
    n_num, n_den = map(int, n.split('/'))
    num = x_num * n_num
    den = x_den * n_den
    return num % den == 0


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

Response:
def order_by_points(nums):
    def sum_of_digits(num):
        return sum(int(digit) for digit in str(num))
    return sorted(nums, key=lambda num: (sum_of_digits(num), nums.index(num)))


Prompt:
def specialFilter(nums):
    """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).
    """

Response:
def specialFilter(nums):
    count = 0
    for num in nums:
        if num > 10 and int(str(num)[0]) % 2 != 0 and int(str(num)[-1]) % 2 != 0:
            count += 1
    return count


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

Response:
def get_max_triples(n):
    a = [i*i-i+1 for i in range(1, n+1)]
    count = 0
    for i in range(n-2):
        for j in range(i+1, n-1):
            for k in range(j+1, n):
                if (a[i]+a[j]+a[k]) % 3 == 0:
                    count += 1
    return count


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

Response:
def bf(planet1, planet2):
    planets = {
        'Mercury': 1,
        'Venus': 2,
        'Earth': 3,
        'Mars': 4,
        'Jupiter': 5,
        'Saturn': 6,
        'Uranus': 7,
        'Neptune': 8
    }
    if planet1 not in planets or planet2 not in planets:
        return ()
    if planets[planet1] > planets[planet2]:
        planet1, planet2 = planet2, planet1
    result = []
    for planet, orbit in planets.items():
        if planets[planet1] < orbit < planets[planet2]:
            result.append(planet)
    return tuple(sorted(result, key=lambda x: planets[x]))


Prompt:
def sorted_list_sum(lst):
    """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.
    """

Response:
def sorted_list_sum(lst):
    lst = [word for word in lst if len(word) % 2 == 0]
    return sorted(lst, key=lambda x: (len(x), x))


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

Response:
def x_or_y(n, x, y):
    from sympy import isprime
    if isprime(n):
        return x
    else:
        return y


Prompt:
def double_the_difference(lst):
    '''
    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.

    If the input list is empty, return 0.
    '''

Response:
def double_the_difference(lst):
    sum_of_squares = 0
    for num in lst:
        if isinstance(num, int) and num > 0 and num % 2 != 0:
            sum_of_squares += num ** 2
    return sum_of_squares * 2 if sum_of_squares > 0 else 0


Prompt:
def compare(game,guess):
    """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.
    """

Response:
def compare(game, guess):
    result = []
    for i in range(len(game)):
        if game[i] == guess[i]:
            result.append(0)
        else:
            result.append(abs(game[i] - guess[i]))
    return result


Prompt:
def Strongest_Extension(class_name, extensions):
    """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).
    """

Response:
def Strongest_Extension(class_name, extensions):
    strongest_extension = None
    for extension in extensions:
        cap = sum(1 for c in extension if c.isupper())
        sm = sum(1 for c in extension if c.islower())
        strength = cap - sm
        if strongest_extension is None or strength > strongest_extension[1] or (strength == strongest_extension[1] and extensions.index(extension) < extensions.index(strongest_extension[0])):
            strongest_extension = (extension, strength)
    return class_name + '.' + strongest_extension[0]


Prompt:
def cycpattern_check(a , b):
    """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
    """

Response:
def cycpattern_check(a, b):
    new_str = a + a
    for i in range(len(a)):
        if b in new_str[i:i+len(a)]:
            return True
    return False


Prompt:
def even_odd_count(num):
    """Given an integer. return a tuple that has the number of even and odd digits respectively.
    """

Response:
def even_odd_count(num):
    even_count = 0
    odd_count = 0
    for digit in str(num):
        if int(digit) % 2 == 0:
            even_count += 1
        else:
            odd_count += 1
    return (even_count, odd_count)


Prompt:
def int_to_mini_roman(number):
    """
    Given a positive integer, obtain its roman numeral equivalent as a string,
    and return it in lowercase.
    Restrictions: 1 <= num <= 1000
    """

Response:
def int_to_mini_roman(number):
    roman_dict = {1000: 'm', 900: 'cm', 500: 'd', 400: 'cd', 100: 'c', 90: 'xc', 50: 'l', 40: 'xl', 10: 'x', 9: 'ix', 5: 'v', 4: 'iv', 1: 'i'}
    result = ''
    for value, numeral in sorted(roman_dict.items(), reverse=True):
        while number >= value:
            result += numeral
            number -= value
    return result.lower()


Prompt:
def right_angle_triangle(a, b, c):
    '''
    Given the lengths of the three sides of a triangle. Return True if the three
    sides form a right-angled triangle, False otherwise.
    A right-angled triangle is a triangle in which one angle is right angle or
    90 degree.
    '''

Response:
def right_angle_triangle(a, b, c):
    if a**2 + b**2 == c**2 or b**2 + c**2 == a**2 or a**2 + c**2 == b**2:
        return True
    else:
        return False


Prompt:
def find_max(words):
    """Write a function that accepts a list of strings.
    The list contains different words. Return the word with maximum number
    of unique characters. If multiple strings have maximum number of unique
    characters, return the one which comes first in lexicographical order.
    """

Response:
def find_max(words):
    max_word = ''
    max_length = 0
    for word in words:
        unique_chars = {}
        for char in word:
            if char not in unique_chars:
                unique_chars[char] = True
        if len(unique_chars) > max_length:
            max_word = word
            max_length = len(unique_chars)
        elif len(unique_chars) == max_length:
            if word < max_word:
                max_word = word
    return max_word


Prompt:
def eat(number, need, remaining):
    """
    You're a hungry rabbit, and you already have eaten a certain number of carrots,
    but now you need to eat more carrots to complete the day's meals.
    you should return an array of [ total number of eaten carrots after your meals,
                                    the number of carrots left after your meals ]
    if there are not enough remaining carrots, you will eat all remaining carrots, but will still be hungry.

    Variables:
    @number : integer
        the number of carrots that you have eaten.
    @need : integer
        the number of carrots that you need to eat.
    @remaining : integer
        the number of remaining carrots thet exist in stock

    Constrain:
    * 0 <= number <= 1000
    * 0 <= need <= 1000
    * 0 <= remaining <= 1000

    Have fun :)
    """

Response:
def eat(number, need, remaining):
    if remaining >= need:
        total_eaten = number + need
        remaining -= need
    else:
        total_eaten = number + remaining
        remaining = 0
    return [total_eaten, remaining]


Prompt:
def do_algebra(operator, operand):
    """
    Given two lists operator, and operand. The first list has basic algebra operations, and
    the second list is a list of integers. Use the two given lists to build the algebric
    expression and return the evaluation of this expression.

    The basic algebra operations:
    Addition ( + )
    Subtraction ( - )
    Multiplication ( * )
    Floor division ( // )
    Exponentiation ( ** )

    Note:
        The length of operator list is equal to the length of operand list minus one.
        Operand is a list of of non-negative integers.
        Operator list has at least one operator, and operand list has at least two operands.

    """

Response:
def do_algebra(operator, operand):
    expression = str(operand[0])
    for i in range(len(operator)):
        expression += operator[i] + str(operand[i+1])
    return eval(expression)


Prompt:
def solve(s):
    """You are given a string s.
    if s[i] is a letter, reverse its case from lower to upper or vise versa,
    otherwise keep it as it is.
    If the string contains no letters, reverse the string.
    The function should return the resulted string.
    """

Response:
def solve(s):
    has_letter = False
    for char in s:
        if char.isalpha():
            has_letter = True
            s = s.replace(char, char.swapcase())
    if not has_letter:
        s = s[::-1]
    return s


Prompt:
def string_to_md5(text):
    """
    Given a string 'text', return its md5 hash equivalent string.
    If 'text' is an empty string, return None.
    """

Response:
def string_to_md5(text):
    import hashlib
    if not text:
        return None
    else:
        return hashlib.md5(text.encode()).hexdigest()


Prompt:
def generate_integers(a, b):
    """
    Given two positive integers a and b, return the even digits between a
    and b, in ascending order.
    """

Response:
def generate_integers(a, b):
    even_digits = []
    for num in range(a, b+1):
        for digit in str(num):
            if int(digit) % 2 == 0:
                even_digits.append(int(digit))
    even_digits.sort()
    return even_digits