Prompt:
from typing import List
def max_profit(n:int, items: List[List[int]], capacity: int) -> int:
    """Given a list of items and a capacity, return the maximum value of the transferred items.
    Each item is a list of [value, weight].
    The item can be broken into fractions to maximize the value of the transferred items.
    Take input from the user for n items and the capacity of the bag. and return the maximum value of the transferred items.

    Example:
    Input: 3, [[60, 10], [100, 20], [120, 30]], 50
    Output: 240
    Input: 2, [[60, 10], [100, 20]], 50
    Output: 160"""

# Calculate value per unit weight for each item and store it along with the item
items_with_ratio = [(item[0] / item[1], item[0], item[1]) for item in items]  # (value/weight, value, weight)

# Sort the items by value per unit weight in descending order
items_with_ratio.sort(reverse=True)

max_value = 0  # Maximum value of the transferred items
for ratio, value, weight in items_with_ratio:
    if capacity >= weight:
        # If the knapsack can carry the entire item, take all of it
        max_value += value
        capacity -= weight
    else:
        # If the knapsack cannot carry the entire item, take the fractional part
        max_value += ratio * capacity
        break  # The knapsack is now full

return max_value

METADATA = {
    'author': 'ay',
    'dataset': 'test'
}

def check(candidate):
    # Test Case 1:
    input_items1 = [[60, 10], [100, 20], [120, 30]]
    input_capacity1 = 50
    assert candidate(3, input_items1, input_capacity1) == 240

    # Test Case 2:
    input_items2 = [[60, -10], [100, 20]]
    input_capacity2 = 50
    assert candidate(2, input_items2, input_capacity2) == 30

    # Test Case 3:
    input_items3 = [[40, 10], [30, 5], [50, 15]]
    input_capacity3 = 20
    assert candidate(3, input_items3, input_capacity3) == 87

    # Test Case 4:
    input_items4 = [[25, 7], [15, 5], [30, 10], [10, 2], [5, 1]]
    input_capacity4 = 15
    assert candidate(5, input_items4, input_capacity4) == 55


Prompt:
from typing import List
def max_prof(n: int, jobs: List[List[int]]) -> List[int]:
    """I want to sequence the job in such a way that my profit is maximized by the end of time.
    let say i'm given N jobs with their deadline and profit.
    I need to find the sequence of jobs that will maximize my profit.
    Each job takes 1 unit of time to complete and only one job can be scheduled at a time.
    Take input from the user for the number of jobs and their deadline and profit. and return the maximum profit and number of jobs done.
    Example:
    Input: 4, [[4, 20], [1, 10], [1, 40], [1, 30]]
    Output: [60, 2]"""

# Sort jobs by profit in descending order
jobs.sort(key=lambda x: x[1], reverse=True)

# Initialize variables
max_deadline = max(job[0] for job in jobs)  # Find the maximum deadline
slots = [False] * max_deadline  # To keep track of occupied time slots
job_count = 0  # To count the number of jobs done
total_profit = 0  # To calculate the total profit

# Schedule jobs
for deadline, profit in jobs:
    for slot in range(min(deadline, max_deadline) - 1, -1, -1):
        if not slots[slot]:  # If the slot is free
            slots[slot] = True  # Mark the slot as occupied
            job_count += 1  # Increment the job count
            total_profit += profit  # Add the profit
            break  # Break after scheduling the job

return [total_profit, job_count]


Prompt:
from typing import List

def min_cost(length: int, width: int, cost: List[List[int]]) -> int:
    """I have a big piece of granite tile that I want to cut into squares.
    Size of my tile is length 'p' and width 'q'. I want to cut it into p*q squaressquares such that cost of breaking is minimum.
    cutting cost for each edge will be given for the tile. In short, we need to choose such a sequence of cutting such that cost is minimized.
    Take input from user p, q and cost of breaking each edge both horizontal and vertical. and return the minimum cost of cutting.

    Example:
    Input: 6, 4, [[2, 1, 3, 1, 4], [4, 1, 2]]
    Output: 42"""

# Separate the horizontal and vertical costs
horizontal_cuts = cost[0]
vertical_cuts = cost[1]

# Add a marker to distinguish between horizontal and vertical cuts
horizontal_cuts = [(c, 'h') for c in horizontal_cuts]
vertical_cuts = [(c, 'v') for c in vertical_cuts]

# Combine and sort all cuts by cost in descending order
all_cuts = sorted(horizontal_cuts + vertical_cuts, key=lambda x: x[0], reverse=True)

# Initialize the number of segments in each direction
horizontal_segments = 1
vertical_segments = 1

total_cost = 0
for cost, cut_type in all_cuts:
    if cut_type == 'h':
        # The cost of a horizontal cut is multiplied by the current number of vertical segments
        total_cost += cost * vertical_segments
        horizontal_segments += 1
    else:
        # The cost of a vertical cut is multiplied by the current number of horizontal segments
        total_cost += cost * horizontal_segments
        vertical_segments += 1

return total_cost

METADATA = {'author': 'ay', 'dataset': 'test'}

def check(candidate):
    length1, width1 = 6, 4
    cost1 = [[2, 1, 3, 1, 4], [4, 1, 2]]
    assert candidate(length1, width1, cost1) == 42

    length3, width3 = 4, 4
    cost3 = [[1, 1, 1], [1, 1, 1]]
    assert candidate(length3, width3, cost3) == 15


Prompt:
from typing import List

def equal_ele(nums: List[int], k: int) -> int:
    """User provides list of number and value X.
    We have to find the maximum number of equal elements possible for the list
    just by increasing the elements of the list by incrementing a total of atmost k.
    Take input from user for list of numbers and value X and return the maximum number of equal elements possible for the list.
    Example:

    Input: [5, 5, 3, 1], 5
    Output: 3
    Input: [2, 4, 9], 3
    Output: 2"""

nums.sort()  # Step 1: Sort the list
max_equal = 1  # To keep track of the maximum number of equal elements
j = 0  # Start of the sliding window

for i in range(len(nums)):
    # Step 3: Calculate the total increments needed for the current window
    while nums[i] * (i - j + 1) - sum(nums[j:i + 1]) > k:
        j += 1  # Slide the window forward if the total increments exceed k

    # Step 4: Update the maximum number of equal elements
    max_equal = max(max_equal, i - j + 1)

return max_equal

METADATA = {'author': 'ay', 'dataset': 'test'}

def check(candidate):
    # Test Case 1:
    nums1, k1 = [5, 5, 3, 1], 5
    assert candidate(nums1, k1) == 3

    # Test Case 2:
    nums2, k2 = [2, 4, 9], 3
    assert candidate(nums2, k2) == 2

    # Test Case 3:
    nums3, k3 = [1, 2, 3, 4, 5], 3
    assert candidate(nums3, k3) == 1

    # Test Case 4:
    nums4, k4 = [10, 10, 10, 10, 10], 2
    assert candidate(nums4, k4) == 5


Prompt:
def max_palindrom(num: str) -> str:
    """My friend say there's always some possibliy to make any given number into palindrome by permutation of its digits.
    So take a input from user for a number and return a maximum possible palindrome number from it. and if not possible return 'not possible'.
    Example:
    Input: '313515'
    Output: '531135'
    Input: '123'
    Output: 'not possible'"""

# Count the frequency of each digit
digit_count = [0] * 10
for digit in num:
    digit_count[int(digit)] += 1

# Build the left half of the palindrome
left_half = []
middle_digit = ""
for digit in range(9, -1, -1):
    count = digit_count[digit]

    if count % 2 != 0:
        if middle_digit:
            return "not possible"
        middle_digit = str(digit)
        count -= 1

    left_half.extend([str(digit)] * (count // 2))

# Build the right half by reversing the left half
right_half = left_half[::-1]

# Combine the left half, middle digit (if any), and the right half
palindrome = "".join(left_half + [middle_digit] + right_half)

return palindrome

METADATA = {'author': 'ay', 'dataset': 'test'}

def check(candidate):
    # Test Case 1:
    num1 = '313515'
    assert candidate(num1) == '531135'

    # Test Case 2:
    num2 = '123'
    assert candidate(num2) == 'not possible'

    # Test Case 3:
    num3 = '1223333'
    assert candidate(num3) == '3321233'

    # Test Case 4:
    num4 = '999977755533211'
    assert candidate(num4) == 'not possible'


Prompt:
from typing import List

def path(n: int, maze: List[List[int]]) -> List[List[int]]:
    """I came to know about a very interesting topic known as backtracking.
    So, my friend gave me a problem to solve using backtracking.
    Let's say I have a maze and I have to find the path from source to destination.
    Maze is n*n matrix and starting point is (0,0) and destination is (n-1,n-1). I can move either right or down.
    In the maze matrix, 0 means the block is a dead end and 1 means the block can be used in the path from source to destination.
    Take input from the user for n and the maze matrix and print the path from source to destination.
    Example:
    Input: 4,[[1,0,0,0],[1,1,0,1],[0,1,0,1],[1,1,1,1]]
    Output: [[1,0,0,0],[1,1,0,0],[0,1,0,0],[0,1,1,1]]"""

def solve_maze(maze, x, y, solution, n):
    # Base Case: If x, y is the destination, return True
    if x == n - 1 and y == n - 1 and maze[x][y] == 1:
        solution[x][y] = 1
        return True

    # Check if maze[x][y] is a valid move
    if 0 <= x < n and 0 <= y < n and maze[x][y] == 1:
        # Mark x, y as part of the solution path
        solution[x][y] = 1

        # Move Right
        if solve_maze(maze, x + 1, y, solution, n):
            return True

        # Move Down
        if solve_maze(maze, x, y + 1, solution, n):
            return True

        # If neither move right nor move down works, backtrack
        solution[x][y] = 0
        return False

    return False

def path(n: int, maze: List[List[int]]) -> List[List[int]]:
    # Initialize solution matrix with 0s
    solution = [[0 for _ in range(n)] for _ in range(n)]

    if not solve_maze(maze, 0, 0, solution, n):
        return "No path exists"

    return solution


Prompt:
def big_number(num: str, swaps: int) -> str:
    """In a lottery game, I have a large number and value X. I'm asked to swap the digits of the number at most X times such that the value of the number is maximized.
    I have to print the maximum value of the number after swapping the digits at most X times.
    Take a number and value X as input from the user. and print the maximum value of the number after swapping the digits at most X times.
    Example 1:
    Input: '1234567', 4
    Output: '7654321'
    Input: '3435335', 3
    Output: '5543333'"""

# Convert the string to a list of digits for easier manipulation
num_list = list(num)

i = 0
while swaps > 0 and i < len(num_list) - 1:
    max_digit_index = i
    # Find the maximum digit in the remaining part of the number
    for j in range(i + 1, len(num_list)):
        if num_list[j] > num_list[max_digit_index]:
            max_digit_index = j

    # If the maximum digit is different from the current digit, perform the swap
    if max_digit_index != i:
        num_list[i], num_list[max_digit_index] = num_list[max_digit_index], num_list[i]
        swaps -= 1

    i += 1

# Convert the list back to a string
result = ''.join(num_list)
return result


Prompt:
from typing import List

def graph_colooring(n: int, m: int, e: int, edges: List[List[int]]) -> bool:
    """I'm assigned an undirected graph and an integer M. The task is to determine if the graph can be colored with at most M colors
    such that no two adjacent vertices of the graph are colored with the same color.
    Here coloring of a graph means the assignment of colors to all vertices.
    Print 1 if it is possible to color vertices and 0 otherwise.
    Take input from the user for n i.e vertices , m i.e colors and e i.e edges and return 1 if it is possible to color vertices and 0 otherwise.
    Example 1:
    Input: 4,3,5,[[0,1],[1,2],[1,3],[2,3],[3,0],[0,2]]
    Output: 1"""


Prompt:
def additive_number(num: str) -> str:
    """By tossing a number at me, my teacher asked to tell whether it is additive or not.
    An additive number is a string whose digits can form an additive sequence.
    A valid additive sequence should contain at least three numbers. Except for the first two numbers,
    each subsequent number in the sequence must be the sum of the preceding two.
    Take a number as input from the user and print 'It is an additive number' if it is additive else print 'It is not an additive number'.
    Example:
    Input: '112358'
    Output: 'It is an additive number'
    Input: '199100199'
    Output: 'It is an additive number'"""

def additive_number(num: str) -> str:
    def is_additive(s, num1, num2):
        while s:
            num_sum = str(int(num1) + int(num2))
            if not s.startswith(num_sum):
                return False
            s = s[len(num_sum):]
            num1, num2 = num2, num_sum
        return True

    n = len(num)
    for i in range(1, n // 2 + 1):
        for j in range(i + 1, n):
            num1, num2 = num[:i], num[i:j]
            if (len(num1) > 1 and num1[0] == '0') or (len(num2) > 1 and num2[0] == '0'):
                continue
            if is_additive(num[j:], num1, num2):
                return "It is an additive number"

    return "It is not an additive number"

METADATA = {'author': 'ay', 'dataset': 'test'}

def check(candidate):
    assert candidate('112358') == 'It is an additive number'
    assert candidate('199100199') == 'It is an additive number'
    assert candidate('123456') == 'It is not an additive number'
    assert candidate('111222333') == 'It is an additive number'


Prompt:
from typing import List

def solve_eq(left: List[str], right: str) -> bool:
    """I have an equation, represented by words on the left side and the result on the right side.
    You need to check if the equation is solvable under the following rules:
    1. Each character is decoded as one digit (0 - 9).
    2. No two characters can map to the same digit.
    3. Each words[i] and result are decoded as one number without leading zeros.
    4. Sum of numbers on the left side (words) will equal to the number on the right side (result).
    Take input from the user and check if the equation is solvable or not.

    Example 1:
    Input: ['send', 'more'], 'money' # Here send and more are words and money is result.
    Output: True
    Input: ['ox', 'ox'], 'xx' # Here ox and ox are words and xx is result.
    Output: False"""

unique_chars = set(''.join(left) + right)  # Gather all unique characters
if len(unique_chars) > 10:  # More unique characters than digits
    return False

char_to_digit = {}
digits_taken = set()

def solve(index):
    if index == len(unique_chars):  # All characters have been assigned digits
        left_sum = sum(int("".join(char_to_digit[char] for char in word)) for word in left)
        right_sum = int("".join(char_to_digit[char] for char in right))
        return left_sum == right_sum

    char = list(unique_chars)[index]
    for digit in range(10):
        if str(digit) not in digits_taken and not (digit == 0 and any(word[0] == char for word in left + [right])):
            char_to_digit[char] = str(digit)
            digits_taken.add(str(digit))
            if solve(index + 1):
                return True
            del char_to_digit[char]
            digits_taken.remove(str(digit))
    return False

return solve(0)

METADATA = {'author': 'ay', 'dataset': 'test'}

def check(candidate):
    assert candidate(['send', 'more'], 'money') == True
    assert candidate(['ox', 'ox'], 'xx') == False
    assert candidate(['bat', 'tab'], 'bat') == False
    assert candidate(['house', 'water'], 'money') == False


Prompt:
def is_good(s: str) -> str:
    """I have a task to find whether a string is good or not. A string s is good if
    for every letter of the alphabet that s contains, it appears both in uppercase and lowercase.
    Take input from the user and print whether the string is good or not.
    return the longest substring of s that is nice. If there are multiple, return the substring of the earliest occurrence.
    If there are none, return an 'Not good'.
    Example:
    Input: 'uSaisAI'
    Output: 'SaisAI'
    Input: 'xYz'
    Output: 'Not good'"""

def is_good(s: str) -> str:
    def is_nice(substr):
        return all(c.islower() and c.upper() in substr or c.isupper() and c.lower() in substr for c in set(substr))

    n = len(s)
    longest_nice_substr = ""
    for i in range(n):
        for j in range(i + 1, n + 1):
            substring = s[i:j]
            if is_nice(substring) and len(substring) > len(longest_nice_substr):
                longest_nice_substr = substring

    return longest_nice_substr if longest_nice_substr else "Not good"

METADATA = {'author': 'ay', 'dataset': 'test'}

def check(candidate):
    assert candidate('uSaisAI') == 'SaisAI'
    assert candidate('xYz') == 'Not good'
    assert candidate('aAbBcC') == 'aAbBcC'
    assert candidate('AbCdEfG') == 'Not good'


Prompt:
from typing import List

def power_mod(a: int, b: List[int]) -> int:
    """I have a very large number a and another number b.
    b is such large it is given in form of list. I need to calculate pow(a,b) % 1337.
    But I have to use a divide and conquer approach.
    Take a and b as input from the user and return pow(a,b) % 1337.

    Example:
    Input: 2, [3]
    Output: 8
    Input: 2, [1,0] # Here 2 is a and 10 is b
    Output: 1024"""

def power_mod(a: int, b: List[int]) -> int:
    MOD = 1337

    def pow_helper(base, exponent):
        if exponent == 0:
            return 1
        if exponent == 1:
            return base % MOD

        half_pow = pow_helper(base, exponent // 2)
        result = (half_pow * half_pow) % MOD

        if exponent % 2 == 1:
            result = (result * base) % MOD

        return result

    b_int = int("".join(map(str, b)))  # Convert list to integer
    return pow_helper(a, b_int)

METADATA = {'author': 'ay', 'dataset': 'test'}

def check(candidate):
    assert candidate(2, [3]) == 8
    assert candidate(2, [1, 0]) == 1024
    assert candidate(3, [2, 5]) == 1151
    assert candidate(5, [1, 3, 7]) == 52


Prompt:
from typing import List

def max_sum(arr: List[int]) -> int:
    """I have a list of integers. I want to find the maximum sum of a sublist.
    You can access the list in circular fashion.
    Take input from the user and print the maximum sum and the sublist.
    Example:
    Input: [1, -5, 6, -2]
    Output: 6
    Input: [9, -4, 9]
    Output: 18"""

def kadane(arr: List[int]) -> int:
    """Standard Kadane's algorithm to find the maximum subarray sum."""
    max_ending_here = max_so_far = arr[0]
    for x in arr[1:]:
        max_ending_here = max(x, max_ending_here + x)
        max_so_far = max(max_so_far, max_ending_here)
    return max_so_far

def max_sum(arr: List[int]) -> int:
    max_kadane = kadane(arr)  # Maximum subarray sum in non-circular fashion

    # Invert the array and apply Kadane's algorithm to find the minimum subarray sum
    max_wrap = 0
    for i in range(len(arr)):
        max_wrap += arr[i]  # Calculate array-sum
        arr[i] = -arr[i]  # Invert the array elements

    # Max sum with corner elements will be: array-sum - (-max subarray sum of inverted array)
    max_wrap = max_wrap + kadane(arr)

    # The maximum circular sum will be maximum of two sums
    if max_wrap > max_kadane and max_wrap != 0:
        return max_wrap
    else:
        return max_kadane

METADATA = {'author': 'ay', 'dataset': 'test'}

def check(candidate):
    assert candidate([1, -5, 6, -2]) == 6
    assert candidate([9, -4, 9]) == 18
    assert candidate([5, -3, 5]) == 10
    assert candidate([4, -1, 2, -1]) == 5
    assert candidate([-2, 8, -3, 7, -1]) == 12


Prompt:
from typing import List

def recover_list(n: int, sums: List[int]) -> List[int]:
    """My job is to recover all the forgotten list by subset sums.
    given a list sums containing the values of all 2^n subset sums of the unknown array (in no particular order).
    Take input from the user for the length of the forgotten list and subset sums, and return the forgotten list.
    Example:
    Input: 3 ,[ -3,-2,-1,0,0,1,2,3]
    Output: [1,2,-3]
    Input: 2, [0,0,0,0]
    Output: [0,0]"""


Prompt:
from typing import List

def being_sum(being: List[int], lower: int, upper: int) -> int:
    """I have a list 'being' of integers and I want to find the being-sum.
    Given two integers lower and upper, return the number of being-sums that lie in [lower, upper] inclusive.
    Range sum S(i, j) is defined as the sum of the elements in 'being' between indices i and j inclusive, where i <= j.
    Take input from the user for 'being' and lower and upper and return the number of being-sums that lie in [lower, upper] inclusive.
    Example:
    Input: [-2, 5, -1], -2, 2
    Output: 3"""

def being_sum(being: List[int], lower: int, upper: int) -> int:
    n = len(being)
    prefix_sums = [0] * (n + 1)  # Initialize prefix sums array with an extra 0 at the beginning

    # Compute prefix sums
    for i in range(n):
        prefix_sums[i + 1] = prefix_sums[i] + being[i]

    count = 0
    # Iterate through all pairs (i, j) and calculate range sums S(i, j)
    for i in range(n):
        for j in range(i, n):
            range_sum = prefix_sums[j + 1] - prefix_sums[i]
            if lower <= range_sum <= upper:
                count += 1

    return count

METADATA = {'author': 'ay', 'dataset': 'test'}

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


Prompt:
def nCr(n: int, r: int) -> int:
    """I'm very much interested in mathematical problems, and today I learned nCr.
    Help me to implement it using dynamic programming.
    Take input from the user n and r and return nCr.
    Example:
    Input: 4, 2 # here 4 is n and 2 is r
    Output: 6
    Input: 3, 2
    Output: 3"""

def nCr(n: int, r: int) -> int:
    # Using dynamic programming to calculate binomial coefficient
    dp = [[0] * (r + 1) for _ in range(n + 1)]

    for i in range(n + 1):
        for j in range(min(i, r) + 1):
            if j == 0 or j == i:
                dp[i][j] = 1
            else:
                dp[i][j] = dp[i - 1][j - 1] + dp[i - 1][j]

    return dp[n][r]

METADATA = {'author': 'ay', 'dataset': 'test'}

def check(candidate):
    assert candidate(4, 2) == 6
    assert candidate(3, 2) == 3
    assert candidate(6, 3) == 20
    assert candidate(8, 4) == 70


Prompt:
def bouncing_balls(n: int, h: int) -> int:
    """I have to test my bouncing ball, but there's a catch.
    The ball only bounces if it falls from a certain height; otherwise, it will burst if the height is above that.
    So provided N identical balls and a height H (1 to H), there exists a threshold T (1 to H) such that if a ball is dropped from a height greater than T, it will burst, otherwise it will bounce.
    There are a few other conditions:
    1. If the ball survives the fall, it can be used again.
    2. If the ball bursts, it cannot be used again.
    3. If the ball survives the fall from a certain height, it will also survive the fall from any height below that.
    4. If the ball does not survive the fall from a certain height, it will also not survive the fall from any height above that.
    5. All balls are identical and are of the same weight.
    Find the minimum number of balls required to find the threshold T.
    Take input for the number of balls N and height H from the user and return the minimum number of balls required to find the threshold T.
    Example:
    Input: 2, 10 # Here 2 is N and 10 is H
    Output: 4
    Input: 1, 2 # Here 1 is N and 2 is H
    Output: 2"""

ballFloor = [[0 for x in range(k + 1)] for x in range(n + 1)]

for i in range(1, n + 1):
    ballFloor[i][1] = 1
    ballFloor[i][0] = 0

for j in range(1, k + 1):
    ballFloor[1][j] = j

for i in range(2, n + 1):
    for j in range(2, k + 1):
        ballFloor[i][j] = INT_MAX
        for x in range(1, j + 1):
            res = 1 + max(ballFloor[i - 1][x - 1], ballFloor[i][j - x])
            if res < ballFloor[i][j]:
                ballFloor[i][j] = res

return ballFloor[n][k]

METADATA = {'author': 'ay', 'dataset': 'test'}

def check(candidate):
    assert candidate(2, 10) == 4
    assert candidate(1, 2) == 2
    assert candidate(3, 15) == 5
    assert candidate(5, 25) == 5


Prompt:
def zebra_crossing(n: int) -> int:
    """I'm waiting for a bus, and now I'm getting bored. To entertain myself, I looked around and found a zebra crossing.
    There can be two ways to cross the road. If there are n white stripes on the zebra crossing, then I can cross
    either by stepping 1 stripe at a time or 2 stripes at a time. But I can't step on the same stripe twice.
    Tell the number of ways I can cross the zebra crossing.
    Use dynamic programming to solve this problem.
    Take input for the number of stripes in the zebra crossing from the user and return the number of ways to cross the zebra crossing.
    Example:
    Input: 4
    Output: 5
    Input: 10
    Output: 89"""

def zebra_crossing(n):
    def f(n, dp):
        if n == 0:
            return 1
        if n == 1:
            return 1
        if n == 2:
            return 2
        if dp[n] != -1:
            return dp[n]
        one_step = f(n - 1, dp)
        two_step = f(n - 2, dp)
        dp[n] = one_step + two_step
        return (dp[n] % 1000000007)

    dp = [-1] * (n + 1)
    return f(n, dp)

METADATA = {'author': 'ay', 'dataset': 'test'}

def check(candidate):
    assert candidate(4) == 5
    assert candidate(10) == 89
    assert candidate(8) == 34
    assert candidate(2) == 2


Prompt:
def count_ways(number: str) -> int:
    """I wrote down a string of positive integers named 'number' but forgot to include commas to separate the numbers.
    The list of integers is non-decreasing, and no integer has leading zeros.
    I need to figure out the number of possible ways I could have written down the string 'number.'
    The result should be returned modulo 10^9 + 7, as the answer might be large.
    Take input as a string and return the number of possible ways to write down the string modulo 10^9 + 7.
    Example 1:
    Input: '327'
    Output: 2
    Input: '094'
    Output: 0"""

MOD = 10**9 + 7

def count_ways(number: str) -> int:
    n = len(number)
    dp = [0] * (n + 1)
    dp[0] = 1  # Base case

    for i in range(1, n + 1):
        for length in range(1, 4):  # Check substrings of length 1 to 3 (since integers can range from 1 to 999)
            if i - length >= 0:
                substr = number[i - length:i]
                if (substr[0] != '0' or length == 1) and (i - length == 0 or substr >= number[max(i - 2 * length, 0):i - length]):
                    # Check if substr is valid and non-decreasing
                    dp[i] = (dp[i] + dp[i - length]) % MOD

    return dp[n]

METADATA = {'author': 'ay', 'dataset': 'test'}

def check(candidate):
    assert candidate('327') == 2
    assert candidate('094') == 0
    assert candidate('111') == 2


Prompt:
from typing import List
def treasureHunt(a: int, b: int, x: int, forbidden: List[int]) -> int:
    """I'm playing a game on road where to win treasure I have to hop
    forward or backward on the x-axis. I start at position 0, and my treasure is at position x.
    There are rules for how I can hop:
    I can jump exactly a positions forward (to the right).
    I can jump exactly b positions backward (to the left).
    I cannot jump backward twice in a row.
    I cannot jump to any forbidden positions.
    The forbidden positions are given in the array 'forbidden.' If forbidden[i] is true, it means I cannot jump to position forbidden[i]. The integers a, b, and x are provided.
    My goal is to find the minimum number of jumps needed to reach my treasure at position x. If there's no possible sequence of jumps that lands me on position x, the result is -1.
    Take input as a, b, x, forbidden from user and return the minimum number of jumps needed to reach my treasure at position x. If there's no possible sequence of jumps that lands
    me on position x, the result is -1.
    Example 1:
    Input: 15, 13, 11, [8,3,16,6,12,20] # a, b, x, forbidden
    Output: -1
    Input: 16, 9, 7, [1,6,2,14,5,17,4] # a, b, x, forbidden
    Output: 2
    """

MOD = 10**9 + 7  # For large numbers
visited = set()  # To keep track of visited positions with a flag for last move
forbidden = set(forbidden)  # Convert list to set for efficient lookups

queue = deque([(0, 0, False)])  # Position, steps, last move was backward
while queue:
    position, steps, last_backward = queue.popleft()

    if position == x:
        return steps % MOD

    # Forward move
    forward_pos = position + a
    if forward_pos not in forbidden and (forward_pos, False) not in visited:
        visited.add((forward_pos, False))
        queue.append((forward_pos, steps + 1, False))

    # Backward move, ensuring not to move backward twice in a row
    if not last_backward and position - b not in forbidden and position - b >= 0:
        backward_pos = position - b
        if (backward_pos, True) not in visited:
            visited.add((backward_pos, True))
            queue.append((backward_pos, steps + 1, True))

return -1  # Treasure is unreachable


Prompt:
from collections import deque
from typing import List
def houses(n:int, connections:List[List[int]]) -> List[int]:
    """I'm standing at entry point of village. In this village there's no proper streets. Houses are randomly connected
    with each other, but there's always a way to reach all houses from starting point. I want to distribute some items to all houses.
    But in such fashion that first i visit to first house, than i visit to all second houses which can be reached from first house,
    than i visit to all third houses which can be reached from second house and so on.
    Take input from user in form of number of houses and connections between houses and return the order in which i should visit houses.
    Starting point is always house 0. and later all houses are numbered in order of their appearance in input.
    Example:
    Input: 5, [[1,2,3],[],[4],[],[]]
    Output: [0,1,2,3,4]
    Input: 3, [[1,2],[],[]]
    Output: [0,1,2]"""

order = []  # To store the order of visiting houses
visited = [False] * n  # To keep track of visited houses
queue = deque([0])  # Start from house 0

while queue:
    house = queue.popleft()
    if not visited[house]:
        order.append(house)
        visited[house] = True
        # Enqueue all connected, unvisited houses
        for connected_house in connections[house]:
            if not visited[connected_house]:
                queue.append(connected_house)

return order


Prompt:
from collections import deque
from typing import List

def knight_moves(n:int, start:List[int], end:List[int]) -> int:
    """I started playing chess now a days. And now i have curiousity to how many steps it would take to reach from one position to another using knight.
    Let's say i have a chess board of N*N size and i have a knight at position (x1,y1) and i want to reach to (x2,y2).
    how many minimum steps it would take to reach from (x1,y1) to (x2,y2).
    Take input from user for size of board and position of knight and position of destination. and return minimum steps.
    Example:
    Input: 6, [4,5], [1,1] # 6 is size of board, [4,5] is position of knight and [1,1] is position of destination.
    Output: 3 """

from collections import deque

source_row = KnightPos[0] - 1
source_col = KnightPos[1] - 1

dist = (TargetPos[0] - 1, TargetPos[1] - 1)

queue = deque([(source_row, source_col, 0)])

deltas = [(2, 1), (1, 2), (-2, 1), (-1, 2), (2, -1), (1, -2), (-2, -1), (-1, -2)]

visited = set()

while queue:
    row, col, step = queue.popleft()

    if (row, col) == dist: return step

    for drow, dcol in deltas:
        row_delta = drow + row
        col_delta = dcol + col

        row_inbound = 0 <= row_delta < N
        col_inbound = 0 <= col_delta < N

        if not row_inbound or not col_inbound: continue

        if (row_delta, col_delta) not in visited:
            queue.append((row_delta, col_delta, step + 1))
            visited.add((row_delta, col_delta))

return -1

METADATA = {
    'author': 'ay',
    'dataset': 'test'
}

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


Prompt:
from typing import List
def remove_poles(v:int, w:int, wires:List[List[int]]) -> List[int]:
    """I have new job where i have to remove electric poles. There a v electric poles conected by w wires in random order.
    But soome how each pole is connected to every other pole directly or indirectly. let's say this complete setup as one chunk.
    I want to find all that pole by removal of that just one pole, whole chunk will be disconnected.
    There can be multiple such poles which can be removed to disconnect the chunk. list all those poles.
    Take input from user for number of poles , wires and path of each wire and return list of poles which can be removed to disconnect the chunk.
    Few things to note:
    pole number starts from 0 to v-1 and wires are bidirectional.
    Example:
    Input: 5, 5, [[0,1],[1,4],[4,2],[2,3],[3,4]]
    Output: [1,4]
    Input: 5, 4, [[0,1],[1,4],[4,2],[2,3]]
    Output: [1,4,2]"""

def dfs(v, u, visited, disc, low, parent, ap, graph, time):
    children = 0
    visited[u] = True
    disc[u] = low[u] = time[0]
    time[0] += 1

    for neighbour in graph[u]:
        if not visited[neighbour]:
            parent[neighbour] = u
            children += 1
            dfs(v, neighbour, visited, disc, low, parent, ap, graph, time)

            low[u] = min(low[u], low[neighbour])

            if parent[u] == -1 and children > 1:
                ap[u] = True
            if parent[u] != -1 and low[neighbour] >= disc[u]:
                ap[u] = True
        elif neighbour != parent[u]:
            low[u] = min(low[u], disc[neighbour])

def remove_poles(v: int, w: int, wires: List[List[int]]) -> List[int]:
    graph = [[] for _ in range(v)]
    for wire in wires:
        graph[wire[0]].append(wire[1])
        graph[wire[1]].append(wire[0])

    visited = [False] * v
    disc = [float('inf')] * v
    low = [float('inf')] * v
    parent = [-1] * v
    ap = [False] * v  # Articulation points
    time = [0]

    for i in range(v):
        if not visited[i]:
            dfs(v, i, visited, disc, low, parent, ap, graph, time)

    return [i for i, x in enumerate(ap) if x]


Prompt:
from typing import List
def strongly_connected(S:int, T:int, tracks:List[List[int]]) -> List[List[int]]:
    """I'm the new railway state incharge and I want to know few things about railway networks.
    right now there are S stations and T tracks in between them . Some how all stations are connected to some other stations.
    Your task is to find the members of strongly connected stations in the state.
    Take input for S , T and T lines of input for tracks. and return the all strongly connected stations.
    Assume each station starts with 0 and ends with S-1 and each track if directed from one station to another.
    Example:
    Input: 5, 5, [[1,0],[0,2],[2,1],[0,3],[3,4]]
    Output: [[0,1,2] ,[3] ,[4]]"""

def dfs(graph, v, visited, stack):
    visited[v] = True
    for i in graph[v]:
        if not visited[i]:
            dfs(graph, i, visited, stack)
    stack.append(v)

def transpose(graph, S):
    gT = [[] for _ in range(S)]
    for i in range(S):
        for j in graph[i]:
            gT[j].append(i)
    return gT

def dfsUtil(graph, v, visited, component):
    visited[v] = True
    component.append(v)
    for i in graph[v]:
        if not visited[i]:
            dfsUtil(graph, i, visited, component)

def strongly_connected(S, T, tracks):
    graph = [[] for _ in range(S)]
    for track in tracks:
        graph[track[0]].append(track[1])

    stack = []
    visited = [False] * S

    # Step 1: Fill the stack with vertices based on their finishing times
    for i in range(S):
        if not visited[i]:
            dfs(graph, i, visited, stack)

    # Step 2: Transpose the graph
    graphT = transpose(graph, S)

    # Step 3: Perform DFS on the transposed graph in the order given by the stack
    visited = [False] * S
    scc = []
    while stack:
        v = stack.pop()
        if not visited[v]:
            component = []
            dfsUtil(graphT, v, visited, component)
            scc.append(sorted(component))

    return scc


Prompt:
from typing import List
def maze(n:int, m:int, maze:List[List[str]]) -> bool:
    """I'n new game of maze intead of moving from 0,0 to n,n you will be given start and end point any where in maze and
    you have to find whether you can reach from start to end or not. You can traverse up, down, right and left.
    The description of cells is as follows:
    A value of cell S means start.
    A value of cell D means end.
    A value of cell X means Blank cell.
    A value of cell 0 means Wall.
    Take input from user for rows and columns of maze and then take input for maze.
    Return True if you can reach from start to end else return False.
    Example:
    Input: 5, 5, [[X,0,X,0,0],[X,0,0,0,X],[X,X,X,X,X],[0,D,X,0,0],[X,0,0,S,X]]
    Output: False"""

def dfs(maze, i, j, visited):
    # Base conditions
    if not (0 <= i < len(maze) and 0 <= j < len(maze[0])) or maze[i][j] == '0' or visited[i][j]:
        return False
    if maze[i][j] == 'D':  # Destination found
        return True

    # Mark the current cell as visited
    visited[i][j] = True

    # Explore all four directions from the current cell
    directions = [(0, 1), (0, -1), (1, 0), (-1, 0)]
    for di, dj in directions:
        if dfs(maze, i + di, j + dj, visited):
            return True

    return False

def maze(n, m, maze):
    visited = [[False for _ in range(m)] for _ in range(n)]

    # Find the starting point
    for i in range(n):
        for j in range(m):
            if maze[i][j] == 'S':
                return dfs(maze, i, j, visited)

    return False  # Start point not found


Prompt:
from typing import List
def student_room(query: List[List[int]]) -> List[bool]:
    """I have to put few students in different rooms. At a time one student can be in one room. in one room there can be more than one student.
    If same student is added with another student, it goes to same room.
    Do two task :
    1. Take input for 2 students at a time and put them in same room.
    2. Or give input for 2 students and check if they are in same room or not.
    Take input from user for queries he want to perform, queries can be of two types:
    1. Add student to room
    2. Check if two students are in same room
    3. Exit
    Example:  [query, student1, student2]
    Input: [[1,1,3], [2,1,4], [1,2,3], [2,1,3], [3]] # 1 means add student to room, 2 means check if two students are in same room, 3 means exit
    Output: [False, True]"""

def find(parent, i):
    if parent[i] != i:
        parent[i] = find(parent, parent[i])  # Path compression
    return parent[i]

def union(parent, a, b):
    rootA = find(parent, a)
    rootB = find(parent, b)
    if rootA != rootB:
        parent[rootB] = rootA  # Merge the sets

def student_room(query: List[List[int]]) -> List[bool]:
    parent = {}  # To keep track of the representative (leader) of each room
    output = []

    for q in query:
        if q[0] == 1:  # Add student to room
            a, b = q[1], q[2]
            if a not in parent:
                parent[a] = a
            if b not in parent:
                parent[b] = b
            union(parent, a, b)
        elif q[0] == 2:  # Check if two students are in the same room
            a, b = q[1], q[2]
            if a in parent and b in parent and find(parent, a) == find(parent, b):
                output.append(True)
            else:
                output.append(False)
        elif q[0] == 3:  # Exit
            break

    return output


Prompt:
from typing import List
def water_pipeline(tanks: int, pipes: List[List[int]]) -> bool:
    """I have a water pipeline system with water tanks and pipes.
    All pipes are biderctional and all tanks are connected to each other either directly or indirectly.
    There's no self loop in the system. I want to find all the cycles in the system to avoid water wastage.
    Take input from user for W water tanks and P pipes. Then take input for each pipe in the format (tank1, tank2).
    Return True if there's any cycle in the system else return False.
    Few points to note:
    1. Each tank have number from 0 to W-1.
    2. Try to use disjoint set data structure to solve this problem.
    Example:
    Input: 5, [[1,3],[3,0],[0,2],[2,4],[4,0]]
    Output: True"""

def find(parent, i):
    if parent[i] != i:
        parent[i] = find(parent, parent[i])  # Path compression
    return parent[i]

def union(parent, a, b):
    rootA = find(parent, a)
    rootB = find(parent, b)
    if rootA == rootB:  # A cycle is found
        return True
    parent[rootB] = rootA  # Merge the sets
    return False

def water_pipeline(tanks: int, pipes: List[List[int]]) -> bool:
    parent = list(range(tanks))  # Each tank is initially its own parent

    for a, b in pipes:
        if union(parent, a, b):  # If union returns True, a cycle is found
            return True

    return False  # No cycles found


Prompt:
from typing import List
def water_supply(villages: int, wells: List[int], pipes: List[List[int]]) -> int:
    """I have an N number of villages numbered 1 to N, an list wells[]
    where wells[i] denotes the cost to build a water well in the i'th city, a 2D array pipes in form of [X Y C]
    which denotes that the cost to connect village X and Y with water pipes is C.
    Your task is to provide water to each and every village either by building a well in the village or connecting
    it to some other village having water. Find the minimum cost to do so.
    Take input from user for N, wells[] and pipes[][]. and return the minimum cost to provide water to all villages.
    Example 1:
    Input: 3, [1, 2, 2], [[1, 2, 1], [2, 3, 1]] # 3 is the number of villages, [1, 2, 2] is the cost of wells in each village,
    [[1, 2, 1], [2, 3, 1]] is the cost of connecting pipes in each village
    Output: 3"""

def find(parent, i):
    if parent[i] != i:
        parent[i] = find(parent, parent[i])  # Path compression
    return parent[i]

def union(parent, rank, x, y):
    xroot = find(parent, x)
    yroot = find(parent, y)
    if rank[xroot] < rank[yroot]:
        parent[xroot] = yroot
    elif rank[xroot] > rank[yroot]:
        parent[yroot] = xroot
    else:
        parent[yroot] = xroot
        rank[xroot] += 1

def water_supply(villages: int, wells: List[int], pipes: List[List[int]]) -> int:
    parent = [i for i in range(villages + 1)]  # Including the virtual node
    rank = [0] * (villages + 1)

    # Create edges list: (cost, village1, village2), including virtual node connections
    edges = [(cost, 0, i + 1) for i, cost in enumerate(wells)]  # Connecting villages to the virtual node (0) via wells
    for x, y, c in pipes:
        edges.append((c, x, y))

    edges.sort()  # Sort by cost

    total_cost = 0
    for cost, x, y in edges:
        if find(parent, x) != find(parent, y):  # If adding this edge doesn't form a cycle
            union(parent, rank, x, y)
            total_cost += cost

    return total_cost


Prompt:
from typing import List
def gang_fight(fights: List[List[int]]) -> int:
    """There's a fight going on in the school. It is between 2 gangs.
    Let's say there are N fights going on between gang A and gang B. We have 2D list of size N, Denotig
    that student list[i][0] and list[i][1] are fighting with each other.
    The task is to find the maximum number of student belonging to an gang if it is
    possible to distribute all the student among A and B, otherwise print -1.
    Take input from user in the form of 2D list and return the maximum number of student belonging to an gang.
    Example 1:
    Input: [[1,2],[2,3],[2,4],[2,5]]
    Output: 4
    Example 2:
    Input: [[1,2],[2,3],[3,1]]
    Output: -1 """

def is_bipartite(graph, start, color):
    queue = deque([start])
    color[start] = 1  # Assign a color to the starting vertex

    while queue:
        u = queue.popleft()
        for v in graph[u]:
            if color[v] == -1:  # If not colored
                color[v] = 1 - color[u]  # Assign an alternate color
                queue.append(v)
            elif color[v] == color[u]:  # If the adjacent has the same color, it's not bipartite
                return False
    return True

def gang_fight(fights: List[List[int]]) -> int:
    if not fights:
        return 0

    # Find the maximum student number to determine the graph size
    max_student = max(max(fight) for fight in fights)
    graph = [[] for _ in range(max_student + 1)]
    color = [-1] * (max_student + 1)  # -1 indicates not colored

    # Build the graph
    for fight in fights:
        graph[fight[0]].append(fight[1])
        graph[fight[1]].append(fight[0])

    # Check if the graph is bipartite and color the graph
    for student in range(1, max_student + 1):
        if color[student] == -1 and not is_bipartite(graph, student, color):
            return -1  # The graph is not bipartite

    # Count the number of students in one of the gangs
    max_gang_size = color.count(1)
    return max(max_gang_size, len(color) - max_gang_size - 1)  # Exclude the -1 (not colored) count


Prompt:
from typing import List
def colony_pipes(houses: int, pipes: int, connections: List[List[int]]) -> List[int]:
    """i'm connecting houses in colony with pipeline. I have H houses and P pipes.
    I can conect one pipe between two houses (a to b). after each connection I have to print the minimmum
    differnce possible between the size any two chunck of the colony. If there is only one chunk simply print 0.
    chunck is a set of houses connected with each other.
    Take input from user foor H and P and then take input for P pipe connections. and return the minimum difference.
    example:
    Input: 2, 1, [[1,2]] # 2 is the number of houses, 1 is the number of pipes, [[1,2]] is the pipe connection
    Output: 0
    Input: 4, 2, [[1,2],[2,4]] # 4 is the number of houses, 2 is the number of pipes, [[1,2],[2,4]] is the pipe connection
    Output: 2"""


Prompt:
from typing import List
def water_plant(cities: int, connections: List[List[int]]) -> int:
    """i have a one water processong plant and a city. The job of water plant is to supply water to the city.
    But in between city there are other small villages. So the water plant has to supply water to first theses villages and then to the city.
    Now a days there's complain about lack of water in the city. I need to check what is amout of water supplied to the city.
    Points to be noted:
    1. there may be multiple villages in between water plant and city.
    2. villages are interconceted with each other (not all) with pipes.
    3. Names of villages are 1 to n.
    Take input from user in form of matrix. where first row is for water plant and last row is for city.
    in between rows are for villages. If there is no connection between two villages then put 0 in matrix.
    If there is connection between two villages then put the rate of water flow in matrix.
    Return the amount of water supplied to the city. Try to use max flow concept.
    Example:
    Input: 4, [[0, 16, 13, 0, 0, 0], [0, 0, 10, 12, 0, 0], [0, 4, 0, 0, 14, 0], [0, 0, 9, 0, 0, 20], [0, 0, 0, 7, 0, 4], [0, 0, 0, 0, 0, 0]]
    Output: 23"""

def bfs(rGraph, s, t, parent):
    visited = [False] * len(rGraph)
    queue = deque()
    queue.append(s)
    visited[s] = True

    while queue:
        u = queue.popleft()

        for ind, val in enumerate(rGraph[u]):
            if not visited[ind] and val > 0:
                if ind == t:
                    parent[ind] = u
                    return True
                queue.append(ind)
                parent[ind] = u
                visited[ind] = True
    return False

def edmonds_karp(graph, source, sink):
    rGraph = [row[:] for row in graph]  # Residual graph
    parent = [-1] * len(graph)
    max_flow = 0

    while bfs(rGraph, source, sink, parent):
        path_flow = float('inf')
        s = sink

        while(s != source):
            path_flow = min(path_flow, rGraph[parent[s]][s])
            s = parent[s]

        max_flow += path_flow
        v = sink

        while(v != source):
            u = parent[v]
            rGraph[u][v] -= path_flow
            rGraph[v][u] += path_flow
            v = parent[v]

    return max_flow

def water_plant(cities, connections):
    # The source is the water plant (0) and the sink is the city (cities - 1)
    return edmonds_karp(connections, 0, cities - 1)


Prompt:
from typing import List
def truck_load(cities: int, connections: List[List[int]]) -> int:
    """in a network of cities and road there are number of trucks that are carrying goods from one city to another city.
    I have selected to make a load to be carried by a truck from ciy A to city B. I have to find how many maximum number of truck can be present on a road at a time
    From city A to city B given the capacity of each road in terms of number of trucks that can be present on a road at a time.
    There can be multiple other cities in between city A and city B.
    Roads can be bidirectional.
    Take input from user for the number of cities in between city A and city B and the
    Matrix of the capacity of the road between each city. and return the maximum number of trucks that can be present on the road at a time.
    Example:
    Input: 4, [[0,12,14,0,0,0],[12,0,1,0,0,0],[14,1,0,20,10,0],[0,0,20,0,0,5],[0,0,10,0,0,15],[0,0,0,5,15,0]]
    Output: 10"""


Prompt:
import sys
from typing import List
def parcel(cities: int, route: List[List[int]]) -> int:
    """I have to courier the parcel from my home to my college.
    I want to know minimum days it will take to reach the parcel to my college.
    Give:
    1. Number of cities in between my home and college.
    2. Days taken between each city.
    3. The route is undirected.
    Take input from user for number of cities in between home and college; the days taken between each city if there's a route between them.
    take input in form of matrix. and return minimum days taken to reach college.
    Example:
    input: 2, [[0,3,2,0],[0,0,5,2],[0,0,0,3],[0,0,0,0]]
    output: 5"""


Prompt:
from collections import deque
from typing import List
def blood_flow(organ: int, blood_vessel: List[List[int]]) -> int:
    """Let's say i want to find max amount of blood that can flow from one organ to another.
    And in between there are n other organs. organ are connected via blood vessels.
    Take input from user as number of organ and capacity of each blood vessel fron organ to organ.
    Do this in form of matrix and return max amount of blood that can flow from one organ A to organ B.
    Also blood can flow is unidirectional.
    Example:
    Input: 4, [[0,7,7,0,0,0],[0,0,0,2,7,0],[0,2,0,0,5,0],[0,0,0,0,0,6],[0,0,0,4,0,8],[0,0,0,0,0,0]]
    Output: 7 """


Prompt:
from collections import defaultdict
from typing import List
def data_transfer(routers: int, network_links: List[List[int]]) -> int:
    """Suppose you want to determine the maximum amount of data that can be transferred from one computer (Computer A) to another (Computer B) in a network.
    Between these computers, there are n routers connected via network links with specific capacities.
    Data transfer is unidirectional.
    Example:
    Input: 4, [[0,7,7,0,0,0],[0,0,0,2,7,0],[0,2,0,0,5,0],[0,0,0,0,0,6],[0,0,0,4,0,8],[0,0,0,0,0,0]
    Output: 7 # The maximum amount of data that can flow from Computer A to Computer B is 7."""


Prompt:
def divide_100_by(x:int)->str:
    """Let's say you have function divide(x,y) that returns x/y.
    Write a function called bind1st(func, value) that can create a one parameter function from
    this two parameter function? create a new function called divide_100_by(y).
    Use bind2func to create a function that divides 100 by a number.
    Take input from user for any number and return the result of 100 divided by that number.
    Try to use decorator and closure to solve this problem.
    Example:
    Input: 10
    Output: "100 divided by 10 is 10.00"
    Input: 3
    Output: "100 divided by 3 is 33.33"
    """

def bind1st(func):
    @wraps(func)
    def wrapper(value):
        return func(100, value)
    return wrapper

@bind1st
def divide(x, y):
    return x / y

def divide_100_by(y):
    result = divide(y)
    return f"100 divided by {y} is {result:.2f}"

# Example usage:
user_input = int(input("Enter a number: "))
output = divide_100_by(user_input)
print(output)

METADATA = {'author': 'ay','dataset': 'test'}
def check(candidate):
    user_input_1 = 10
    output_1 = candidate(user_input_1)
    assert output_1 == '100 divided by 10 is 10.00'

    user_input_2 = 3
    output_2 = candidate(user_input_2)
    assert output_2 == '100 divided by 3 is 33.33'

    user_input_3 = 7
    output_3 = candidate(user_input_3)
    assert output_3 == '100 divided by 7 is 14.29'

    user_input_4 = 11
    output_4 = candidate(user_input_4)
    assert output_4 == '100 divided by 11 is 9.09'


Prompt:
import time
from typing import List

def math_ops(a: int, b: int) -> List[List[str]]:
    """Let's say I have two number a and b, and I few functions:
    1. mutliply(a, b)
    2. divide(a, b)
    3. power(a, b)
    But these function uses loops instead of direct multiplication, division, and power to solve the problem.
    I want to see how much time each function takes to run.
    But I don't want to write a code to calculate the time for each function. show time in nanoseconds.
    I want to create one function for that and use it for all the functions.
    Try to use concept of decorators and closures to solve this problem.
    Take input from user for a and b and return the result of multiplication, division, and power of a and b; along with the time taken to run each function.
    In time is greater than 0 return true else return false.
    Example:
    Input: 10, 5
    Output: [["50", "True"], ["2", "True"], ["100000", "True"]]
    """

import time
from typing import List
def time_decorator(func):
    def wrapper(a, b):
        start = time.time_ns()  # Capture start time in nanoseconds
        result = func(a, b)  # Call the original function
        end = time.time_ns()  # Capture end time in nanoseconds
        elapsed = end - start  # Calculate elapsed time
        return [str(result), str(elapsed > 0)]  # Format result and time check
    return wrapper

@time_decorator
def multiply(a, b):
    result = 0
    for _ in range(b):
        result += a
    return result

@time_decorator
def divide(a, b):
    count = 0
    while a >= b:
        a -= b
        count += 1
    return count

@time_decorator
def power(a, b):
    result = 1
    for _ in range(b):
        result *= a
    return result

def math_ops(a: int, b: int) -> List[List[str]]:
    return [multiply(a, b), divide(a, b), power(a, b)]


Prompt:
from typing import List
def number_plate(number: List[str]) -> List[str]:
    """I have a bunch of car number plates in the format of 'XX XX XXXX'.
    I want to print them in sorted order. Also, sometimes there is
    a prefix 'HS', 'AB', or 'XX' in front and sometimes it is not there.
    Take input from the user and print them in sorted order along with the new prefix
    'Hind'. If there is a prefix already present then remove it and add 'Hind'.
    If there is no prefix then add 'Hind' in front of the number plate.
    Try to use decorator and closure concept.
    Example:
    Input: 5, ['HS 01 1234', '06 1234', 'AB 01 1134', '01 1234', 'XX 11 1234']
    Output: ['Hind 01 1134', 'Hind 01 1234', 'Hind 01 1234', 'Hind 06 1234', 'Hind 11 1234']"""

def number_plate_decorator(func: Callable[[List[str]], List[str]]) -> Callable[[List[str]], List[str]]:
    def wrapper(number: List[str]) -> List[str]:
        # Process each number plate: remove existing prefix and add "Hind" prefix
        processed = ["Hind " + " ".join(plate.split()[1:]) if plate.split()[0] in ["HS", "AB", "XX"] else "Hind " + plate for plate in number]
        # Sort the processed number plates
        sorted_plates = sorted(processed)
        # Return the sorted number plates through the original function
        return func(sorted_plates)
    return wrapper

@number_plate_decorator
def number_plate(number: List[str]) -> List[str]:
    return number


Prompt:
from typing import List
def introduction(n:int ,name: List[str]) -> List[str]:
    """Utilize decorators and closure to create a name directory using provided information about individuals,
    including first name, last name, age, and sex. Display their names in a designated format,
    sorted in ascending order based on age. The output should list the names of the
    youngest individuals first, and for individuals of the same age, maintain the order of their input.
    Take input from the user for the number of individuals, and then for each individual.
    Example:
    Input: 3, [['amit', 'yadav', 23, 'm'], ['amit', 'jain', 12, 'm'], ['ankita', 'did', 23, 'f']]
    Output: ['Mr. amit jain', 'Mr. amit yadav', 'Ms. ankita did']"""

def name_directory_decorator(func):
    def wrapper(name: List[List[str]]):
        # Process the input list: format names and sort by age
        processed_list = sorted(name, key=lambda x: x[2])  # Sort by age
        formatted_list = [("Mr. " if person[3] == "m" else "Ms. ") + person[0] + " " + person[1] for person in processed_list]
        return func(formatted_list)
    return wrapper

@name_directory_decorator
def introduction(name: List[str]) -> List[str]:
    return name

METADATA = {
    'author': 'ay',
    'dataset': 'test'
}

def check(candidate):
    assert candidate([['amit', 'yadav', 23, 'm'], ['amit', 'jain', 12, 'm'], ['ankita', 'did', 23, 'f']]) == ['Mr. amit jain', 'Mr. amit yadav', 'Ms. ankita did']
    assert candidate([['john', 'doe', 30, 'm'], ['jane', 'smith', 25, 'f'], ['alice', 'jones', 25, 'f']]) == ['Ms. jane smith', 'Ms. alice jones', 'Mr. john doe']
    assert candidate([['bob', 'brown', 22, 'm'], ['emma', 'white', 22, 'f'], ['david', 'lee', 22, 'm']]) == ['Mr. bob brown', 'Ms. emma white', 'Mr. david lee']
    assert candidate([['sam', 'johnson', 18, 'm'], ['sarah', 'miller', 17, 'f'], ['mark', 'anderson', 19, 'm']]) == ['Ms. sarah miller', 'Mr. sam johnson', 'Mr. mark anderson']


Prompt:
from typing import List
def mat_sum(n:int, m:int, matrix: List[List[int]]) -> int:
    """I have an n*m matrix, filled with positive integers.
    I want to find the path in this matrix, from top left to bottom right,
    that minimizes the sum of the integers along the path.
    Try to use decorator and closure to solve this problem.
    Take input from the user of n * m matrix and print the minimum sum of the integers along the path.

    Example:
    Input: 3,3,[[1,3,1],[1,5,1],[4,2,1]]
    Output: 7
    Input: 2,3,[[1,2,3],[4,5,6]]
    Output: 12"""

def min_path_decorator(func):
    def wrapper(n, m, matrix):
        return func(n, m, matrix)
    return wrapper

@min_path_decorator
def mat_sum(n: int, m: int, matrix: List[List[int]]) -> int:
    # Dynamic Programming to calculate the minimum path sum
    for i in range(n):
        for j in range(m):
            if i == 0 and j == 0:  # Skip the top-left corner
                continue
            elif i == 0:  # Top row, can only come from the left
                matrix[i][j] += matrix[i][j-1]
            elif j == 0:  # Leftmost column, can only come from above
                matrix[i][j] += matrix[i-1][j]
            else:  # Interior cell, take the minimum of the top and left cells
                matrix[i][j] += min(matrix[i-1][j], matrix[i][j-1])
    return matrix[n-1][m-1]  # The minimum path sum is in the bottom-right corner


Prompt:
from typing import List
import concurrent.futures
def sum_divisible_by_3(n: int, pairs: List[List[int]]) -> List[int]:
    """I want to implement concurrency and parallelism in code for faster execution.
    Take input from the user for n pair of numbers (a,b) where a<b.
    Print sum of all numbers between a and b (inclusive) which are divisible by 3.
    Example:
    Input: 2, [[1,10],[3,5]] # 3+6+9=18,
    Output: 18, 0"""

def sum_divisible_by_3_in_range(pair: List[int]) -> int:
    """Calculate the sum of numbers divisible by 3 within the given range (a, b], where b is inclusive."""
    a, b = pair
    # Start from the next number if 'a' is not divisible by 3
    start = a + 1 if a % 3 != 0 else a
    return sum(x for x in range(start, b + 1) if x % 3 == 0)

def sum_divisible_by_3(n: int, pairs: List[List[int]]) -> List[int]:
    results = []
    with concurrent.futures.ThreadPoolExecutor() as executor:
        # Submit tasks to the executor for each pair
        futures = [executor.submit(sum_divisible_by_3_in_range, pair) for pair in pairs]
        for future in concurrent.futures.as_completed(futures):
            # Collect the results as they are completed
            results.append(future.result())
    return results


Prompt:
import threading
import concurrent.futures
from typing import List
def matrix_multiplication(n: int, matrix: List[List[int]]) -> List[List[int]]:
    """I want to implement matrix multiplication of n matrices each of size 3x3.
    Each matrix element is [n,n+1,n+2,n+3,n+4,n+5,n+6,n+7,n+8].
    But I want to do this process concurrently and parallely using threads.
    Take input from the user for the number of matrices and n for each matrix and return the result.
    Example:
    Input: 3, [3,4,5]
    Output: [[[3,4,5],[6,7,8],[9,10,11]],[[4,5,6],[7,8,9],[10,11,12]],[[5,6,7],[8,9,10],[11,12,13]], [[114, 126, 138], [156, 174, 192], [198, 222, 246]]]
    # 3 matrices of size 3x3 and result of multiplication of 3 matrices
    """


Prompt:
import time
import multiprocessing
import concurrent.futures
from typing import List
def input_func(a:int, b:int) -> List[str]:
    """I want to learn how concurrency and parallelism works in python.
    To do that i want to calculate pow(a,b) using for loops.
    I want to do this using concurrent.futures and multiprocessing module.
    Take input from the user for a and b and return time taken by both functions to complete the task in nano seconds.
    If time taken is greater than 0 return True else False.
    Example:
    Input: 2, 1000
    Output: [Time taken by concurently_done is True, Time taken by parallel_done is True]"""

METADATA = {
    'author': 'ay',
    'dataset': 'test'
}

def check(candidate):
    assert candidate(2, 1000) == ['Time taken by concurrently_done is True', 'Time taken by parallel_done is True']
    assert candidate(3, 500) == ['Time taken by concurrently_done is True', 'Time taken by parallel_done is True']
    assert candidate(5, 200) == ['Time taken by concurrently_done is True', 'Time taken by parallel_done is True']
    assert candidate(10, 100) == ['Time taken by concurrently_done is True', 'Time taken by parallel_done is True']


Prompt:
import concurrent.futures
from typing import List
def conc_work(n: int, tasks: List[int]) -> List[str]:
    """I want to learn how concurrent processes work in Python. To do that take multiple tasks and their duration to complete their work.
    Your goal is to create a program that executes these tasks concurrently to reduce overall processing time.
    In the end, you should be able to see the total time taken to complete all tasks.
    Take input from the user for the number of tasks and their duration and return the total time taken to complete all tasks in seconds if it is greater than 0 return True else False.
    example:
    Input: 4, [3,5,2,4] # 4 tasks with duration 3,5,2,4
    Output: ["Executing Task C...", "Executing Task A...", "Executing Task D...", "Executing Task B...", True]"""

def simulate_task(duration: int, task_name: str) -> str:
    """Simulate a task that takes 'duration' seconds to complete."""
    print(f"Executing Task {task_name}...")
    time.sleep(duration)
    return f"Task {task_name} completed."

def conc_work(n: int, tasks: List[int]) -> List[str]:
    start_time = time.time()
    results = []
    task_names = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J"][:n]  # Generate task names

    with concurrent.futures.ThreadPoolExecutor(max_workers=n) as executor:
        # Schedule the tasks concurrently
        future_to_task = {executor.submit(simulate_task, task, task_names[i]): i for i, task in enumerate(tasks)}
        for future in concurrent.futures.as_completed(future_to_task):
            task_name = task_names[future_to_task[future]]
            try:
                result = future.result()
            except Exception as exc:
                results.append(f"Task {task_name} generated an exception: {exc}")
            else:
                results.append(result)

    total_time = time.time() - start_time
    results.append(True if total_time > 0 else False)
    return results

METADATA = {
    'author': 'ay',
    'dataset': 'test'
}

def check(candidate):
    assert candidate(4, [3, 5, 2, 4]) == ["Executing Task C...", "Executing Task A...", "Executing Task D...", "Executing Task B...", True]
    assert candidate(3, [2, 4, 1]) == ["Executing Task C...", "Executing Task A...", "Executing Task B...", True]
    assert candidate(5, [1, 2, 3, 4, 5]) == ["Executing Task A...", "Executing Task B...", "Executing Task C...", "Executing Task D...", "Executing Task E...", True]
    assert candidate(2, [5, 3]) == ["Executing Task B...", "Executing Task A...", True]


Prompt:
import concurrent.futures
from typing import List
def math_tasks(n: int, tasks: List[int]) -> List[str]:
    """I want to implement concurrency and parallelism in code for faster execution.
    Take input from user for n tasks and their parameters.
    Print the result of each task. If parameters are invalid return "Not Done". else return "Done".
    Example:
    Input: 4, [1000000, 500000, 750000, 200000]
    Output: ["Performing Task A...", "Performing Task B...", "Performing Task C...", "Performing Task D...", "Done", "Done", "Done", "Done"]"""

def perform_task(param: int) -> str:
    """Simulate a math task that computes the sum of numbers up to 'param'.
    If 'param' is invalid, returns 'Not Done'."""
    if param < 0:
        return "Not Done"
    result = sum(range(param + 1))  # Example task: sum of numbers up to 'param'
    return "Done"

def math_tasks(n: int, tasks: List[int]) -> List[str]:
    results = []
    with concurrent.futures.ThreadPoolExecutor(max_workers=n) as executor:
        # Schedule the tasks concurrently
        future_to_task = {executor.submit(perform_task, task): i for i, task in enumerate(tasks)}
        for future in concurrent.futures.as_completed(future_to_task):
            task_id = future_to_task[future]
            try:
                result = future.result()
            except Exception as exc:
                results.append(f"Task {task_id} generated an exception: {exc}")
            else:
                results.append(f"Performing Task {chr(65 + task_id)}...")  # Task A, B, C, etc.
                results.append(result)
    return results

METADATA = {
    'author': 'ay',
    'dataset': 'test'
}

def check(candidate):
    assert candidate(4, [1000000, 500000, 750000, 200000]) == [
        "Performing Task A...",
        "Performing Task B...",
        "Performing Task C...",
        "Performing Task D...",
        "Done",
        "Done",
        "Done",
        "Done"
    ]
    assert candidate(3, [200, 500, 1000]) == [
        "Performing Task A...",
        "Performing Task B...",
        "Performing Task C...",
        "Done",
        "Done",
        "Done"
    ]
    assert candidate(2, [5, 10]) == [
        "Performing Task A...",
        "Performing Task B...",
        "Done",
        "Done"
    ]
    assert candidate(1, [3]) == [
        "Performing Task A...",
        "Done"
    ]


Prompt:
from typing import List
def input_for_class1(coffs:List[List[int]])->List[str]:
    """Create a Python class named Polynomial that represents a polynomial of a single variable.
    The Polynomial class should support the following operations:
    1. Initialization: The class should be initialized with a list of coefficients in decreasing order of powers.
    For example, Polynomial([1, -3, 0, 2]) represents the polynomial 1x^3 - 3x^2 + 2.
    2. String Representation: Implement a __str__ method that returns a human-readable string representation of the polynomial.
    For example, if the polynomial is Polynomial([1, -3, 0, 2]), the __str__ method should return the string "x^3 - 3x^2 + 2".
    3. Addition and Subtraction: Implement methods add and subtract that take another Polynomial object as an argument and return a
    new Polynomial object representing the sum or difference of the two polynomials, respectively.
    Take input from the user for the coefficients of the two polynomials and create two Polynomial objects.
    Example:
    Input: [[1, -3, 0, 2], [2, 0, 1]] # cofficients of first polynomial, coefficients of second polynomial
    Output: ["x^3 - 3x^2 + 2", "2x^2 + 1", "x^3 - x^2 + 3", "x^3 - 5x^2-1"] # first polynomial, second polynomial, sum, difference
    Input: [[1, 2, 3], [3, 2, 1]]
    Output: ["x^2 + 2x + 3", "3x^2 + 2x + 1", "4x^2 + 4x + 4", "-2x^2 +2"]"""

class Polynomial:
    def __init__(self, coeffs: List[int]):
        self.coeffs = coeffs

    def __str__(self):
        terms = []
        n = len(self.coeffs)
        for i, coeff in enumerate(self.coeffs):
            power = n - i - 1
            if coeff == 0:
                continue
            if power == 0:
                terms.append(str(coeff))
            elif power == 1:
                terms.append(f"{coeff}x" if coeff != 1 else "x")
            else:
                terms.append(f"{coeff}x^{power}" if coeff != 1 else f"x^{power}")
        return " + ".join(terms).replace("+ -", "- ")

    def add(self, other):
        max_len = max(len(self.coeffs), len(other.coeffs))
        result_coeffs = [0] * max_len
        for i in range(max_len):
            coeff1 = self.coeffs[-i-1] if i < len(self.coeffs) else 0
            coeff2 = other.coeffs[-i-1] if i < len(other.coeffs) else 0
            result_coeffs[-i-1] = coeff1 + coeff2
        return Polynomial(result_coeffs)

    def subtract(self, other):
        max_len = max(len(self.coeffs), len(other.coeffs))
        result_coeffs = [0] * max_len
        for i in range(max_len):
            coeff1 = self.coeffs[-i-1] if i < len(self.coeffs) else 0
            coeff2 = other.coeffs[-i-1] if i < len(other.coeffs) else 0
            result_coeffs[-i-1] = coeff1 - coeff2
        return Polynomial(result_coeffs)

def input_for_class1(coffs: List[List[int]]) -> List[str]:
    poly1 = Polynomial(coffs[0])
    poly2 = Polynomial(coffs[1])
    sum_poly = poly1.add(poly2)
    diff_poly = poly1.subtract(poly2)
    return [str(poly1), str(poly2), str(sum_poly), str(diff_poly)]


Prompt:
from typing import List

def input_for_class2(entries:List[str])->str:
    """I want to see magic using class and object. Let's say i have a class named "Person".
    In object i will pass name, id nummber, salary and position. Then i want to print all the information of that object.
    But twist is i want class Person to have only name and id number. And i want to add salary and position to another class named "Employee" which
    Does the all the work of printing the information. I want to see how you do it. I want to see how you use inheritance and polymorphism.
    Take input from user for name, id number, salary and position and create object of class Employee and print all the information of that object.
    Example:
    Input: ["John", 1234, 10000, "Manager"]
    Output: "My name is John, My id number is 1234, My salary is 10000 and my position is Manager."
    Input: ["Ram", 12223, 20000, "CEO"]
    Output: "My name is Ram, My id number is 12223, My salary is 20000 and my position is CEO."
  """

class Person:
    def __init__(self, name: str, id_number: int):
        self.name = name
        self.id_number = id_number

class Employee(Person):
    def __init__(self, name: str, id_number: int, salary: int, position: str):
        super().__init__(name, id_number)
        self.salary = salary
        self.position = position

    def print_information(self):
        return f"My name is {self.name}, My id number is {self.id_number}, My salary is {self.salary} and my position is {self.position}."

# Example usage:
def input_for_class2(entries: List[str]) -> str:
    name, id_number, salary, position = entries
    employee = Employee(name, int(id_number), int(salary), position)
    return employee.print_information()

METADATA = {
    'author': 'ay',
    'dataset': 'test'
}

def check(candidate):
    assert candidate(["John", "1234", "10000", "Manager"]) == "My name is John, My id number is 1234, My salary is 10000 and my position is Manager."
    assert candidate(["Ram", "12223", "20000", "CEO"]) == "My name is Ram, My id number is 12223, My salary is 20000 and my position is CEO."
    assert candidate(["Alice", "5678", "15000", "Engineer"]) == "My name is Alice, My id number is 5678, My salary is 15000 and my position is Engineer."
    assert candidate(["Bob", "9876", "12000", "Developer"]) == "My name is Bob, My id number is 9876, My salary is 12000 and my position is Developer."


Prompt:
def input_for_class3(typess:str)->str:
    """I want to test my knowledge of polymorphism.
    I want to create a car catalog using classes and polymorphism.
    On top we have class Car, with description "Welcome to car catalog, here you can find all the cars you need."
    Let's say I have class name sedan, suv, coupe, hatchback, and truck.
    1. Sedan class displays " This is a sedan car with 4 doors and 5 seats, usage is for family."
    2. SUV class displays " This is a SUV car with 4 doors and 5 seats, usage is for offroad."
    3. Coupe class displays " This is a coupe car with 2 doors and 2 seats, usage is for sport."
    4. Hatchback class displays " This is a hatchback car with 4 doors and 5 seats, usage is for small family."
    5. Truck class displays " This is a truck car with 2 doors and 3 seats, usage is for work."
    when user inputs the car type, it will display the description of the of class car and the description of the car type.
    Take input from user and display the description of the car type.
    Example:
    Input: sedan
    Output: Welcome to car catalog, here you can find all the cars you need. This is a sedan car with 4 doors and 5 seats, usage is for family.
    Input: suv
    Output: Welcome to car catalog, here you can find all the cars you need. This is a SUV car with 4 doors and 5 seats, usage is for offroad."""

class Car:
    def __init__(self):
        self.description = "Welcome to car catalog, here you can find all the cars you need."

    def get_description(self):
        return self.description

class Sedan(Car):
    def __init__(self):
        super().__init__()
        self.description += " This is a sedan car with 4 doors and 5 seats, usage is for family."

class SUV(Car):
    def __init__(self):
        super().__init__()
        self.description += " This is a SUV car with 4 doors and 5 seats, usage is for offroad."

class Coupe(Car):
    def __init__(self):
        super().__init__()
        self.description += " This is a coupe car with 2 doors and 2 seats, usage is for sport."

class Hatchback(Car):
    def __init__(self):
        super().__init__()
        self.description += " This is a hatchback car with 4 doors and 5 seats, usage is for small family."

class Truck(Car):
    def __init__(self):
        super().__init__()
        self.description += " This is a truck car with 2 doors and 3 seats, usage is for work."

# Example usage:
def input_for_class3(typess: str) -> str:
    car_types = {
        'sedan': Sedan(),
        'suv': SUV(),
        'coupe': Coupe(),
        'hatchback': Hatchback(),
        'truck': Truck(),
    }

    if typess.lower() in car_types:
        return car_types[typess.lower()].get_description()
    else:
        return "Invalid car type. Please choose from sedan, suv, coupe, hatchback, or truck."

METADATA = {
    'author': 'ay',
    'dataset': 'test'
}

def check(candidate):
    assert candidate("sedan") == "Welcome to car catalog, here you can find all the cars you need. This is a sedan car with 4 doors and 5 seats, usage is for family."
    assert candidate("suv") == "Welcome to car catalog, here you can find all the cars you need. This is a SUV car with 4 doors and 5 seats, usage is for offroad."
    assert candidate("coupe") == "Welcome to car catalog, here you can find all the cars you need. This is a coupe car with 2 doors and 2 seats, usage is for sport."
    assert candidate("hatchback") == "Welcome to car catalog, here you can find all the cars you need. This is a hatchback car with 4 doors and 5 seats, usage is for small family."
    assert candidate("truck") == "Welcome to car catalog, here you can find all the cars you need. This is a truck car with 2 doors and 3 seats, usage is for work."


Prompt:
from typing import List
def input_for_class4(data:List[str])->List[str]:
    """Create a Python class named BankAccount that represents a bank account.
    The BankAccount class should support the following operations:
    1. Initialization: The class should be initialized with an account holder's name and an initial balance.
    2. Deposit and Withdrawal: Implement methods deposit and withdraw that allow the account holder to deposit and withdraw funds, respectively.
    Ensure that withdrawals do not exceed the available balance. # "Withdrawal amount exceeds available balance."
    3. Balance Inquiry: Implement a method get_balance that returns the current balance.
    Take input from the user for the account holder's name and initial balance. later, take input from the user for the amount to deposit, withdraw, or check balance.
    Example
    Input: ["John", 1000, "Deposit", 500, "Withdraw", 200, "Balance", "Exit" ]
    Output: ["Your current balance is 1300"]"""

from typing import List
class BankAccount:
    def __init__(self, name: str, initial_balance: float):
        self.name = name
        self.balance = initial_balance

    def deposit(self, amount: float):
        self.balance += amount

    def withdraw(self, amount: float):
        if amount > self.balance:
            return "Withdrawal amount exceeds available balance."
        self.balance -= amount

    def get_balance(self):
        return self.balance

def input_for_class4(data: List[str]) -> List[str]:
    account = BankAccount(data[0], float(data[1]))
    i = 2  # Start from the third item in the list, which is the first operation
    output = []

    while i < len(data):
        operation = data[i]
        if operation == "Deposit":
            i += 1
            account.deposit(float(data[i]))
        elif operation == "Withdraw":
            i += 1
            withdrawal_message = account.withdraw(float(data[i]))
            if withdrawal_message:
                output.append(withdrawal_message)
        elif operation == "Balance":
            output.append(f"Your current balance is {account.get_balance()}")
        elif operation == "Exit":
            break
        i += 1

    return output

def check(candidate):
    assert candidate(["John", "1000", "Deposit", "500", "Withdraw", "200", "Balance", "Exit"]) == ["Your current balance is 1300"]
    assert candidate(["Alice", "1500", "Deposit", "300", "Balance", "Withdraw", "200", "Exit"]) == ["Your current balance is 1800", "Your current balance is 1600"]
    assert candidate(["Bob", "500", "Withdraw", "700", "Deposit", "200", "Balance", "Exit"]) == ["Withdrawal amount exceeds available balance.", "Your current balance is 700"]
    assert candidate(["Eve", "2000", "Withdraw", "500", "Deposit", "1000", "Balance", "Exit"]) == ["Your current balance is 2500"]


Prompt:
from typing import List
def input_for_class5(data:List[str])->List[str]:
    """You are tasked with designing a Python class to manage and monitor activities at a construction site.
    The class should encapsulate various aspects of construction management. Implement the following functionalities:
    Initialization: The class should be initialized with the construction site's name and the initial budget.
    Material Inventory: Implement methods to add materials to the construction site's inventory and retrieve the current inventory status.
    Worker Management: Implement methods to add and remove workers from the construction site. Each worker has a unique identifier, and name.
    Budget Tracking: Implement methods to track expenses and remaining budget. Ensure that expenses are deducted from the budget
    when materials are purchased or workers are hired.
    Progress Monitoring: Implement a method to monitor the overall progress of the construction site based on completed tasks and remaining tasks.
    Take apporpriate input from the user to test your class. You may use the following sample input/output to test your class:
    Example:
    Input: ["IIT", 100000, "material addition", "cement", 100, "material addition", "bricks", 1000, "material addition", "sand", 500, "worker addition", "John", 1, "worker addition", "Mike", 2, "worker addition", "Mary", 3, "status update", "completed", "EXIT"]
    Output: [Construction site name is IIT, budget is 100000, material inventory is {'cement': 100, 'bricks': 1000, 'sand': 500}, workers are {1: 'John', 2: 'Mike', 3: 'Mary'}]"""

class ConstructionSite:
    def __init__(self, name: str, initial_budget: float):
        self.name = name
        self.budget = initial_budget
        self.material_inventory = {}
        self.workers = {}

    def add_material(self, material_name: str, quantity: int):
        if material_name in self.material_inventory:
            self.material_inventory[material_name] += quantity
        else:
            self.material_inventory[material_name] = quantity

    def get_material_inventory(self):
        return self.material_inventory

    def add_worker(self, worker_name: str, worker_id: int):
        self.workers[worker_id] = worker_name

    def remove_worker(self, worker_id: int):
        if worker_id in self.workers:
            del self.workers[worker_id]

    def get_workers(self):
        return self.workers

    def track_expense(self, expense: float):
        self.budget -= expense

    def get_budget(self):
        return self.budget

    def monitor_progress(self, status: str):
        if status.lower() == "completed":
            return f"Construction site {self.name} has been completed."
        elif status.lower() == "in progress":
            return f"Construction site {self.name} is still in progress."
        else:
            return "Invalid progress status."

# Example usage:
def input_for_class5(data: List[str]) -> List[str]:
    construction_site_name = data[0]
    initial_budget = float(data[1])
    construction_site = ConstructionSite(construction_site_name, initial_budget)

    results = []
    i = 2
    while i < len(data):
        action = data[i]
        if action.lower() == "material addition":
            material_name = data[i + 1]
            quantity = int(data[i + 2])
            construction_site.add_material(material_name, quantity)
            i += 3
        elif action.lower() == "worker addition":
            worker_name = data[i + 1]
            worker_id = int(data[i + 2])
            construction_site.add_worker(worker_name, worker_id)
            i += 3
        elif action.lower() == "worker removal":
            worker_id = int(data[i + 1])
            construction_site.remove_worker(worker_id)
            i += 2
        elif action.lower() == "status update":
            status = data[i + 1]
            progress = construction_site.monitor_progress(status)
            results.append(progress)
            i += 2
        elif action.lower() == "exit":
            break

    results.append(f"Construction site name is {construction_site.name}, budget is {construction_site.budget}, material inventory is {construction_site.get_material_inventory()}, workers are {construction_site.get_workers()}")
    return results

METADATA = {'author': 'ay', 'dataset': 'test'}

def check(candidate):
    assert candidate(['IIT', '100000', 'material addition', 'cement', '100', 'material addition', 'bricks', '1000', 'material addition', 'sand', '500', 'worker addition', 'John', '1', 'worker addition', 'Mike', '2', 'worker addition', 'Mary', '3', 'status update', 'completed', 'EXIT']) == ['Construction site name is IIT, budget is 99900.0, material inventory is {'cement': 100, 'bricks': 1000, 'sand': 500}, workers are {1: 'John', 2: 'Mike', 3: 'Mary'}']
    assert candidate(['TechPark', '50000', 'material addition', 'steel', '200', 'material addition', 'concrete', '300', 'worker addition', 'Alice', '1', 'status update', 'in progress', 'EXIT']) == ['Construction site name is TechPark, budget is 50000.0, material inventory is {'steel': 200, 'concrete': 300}, workers are {1: 'Alice'}']
    assert candidate(['HomeProject', '200000', 'material addition', 'wood', '150', 'material addition', 'tiles', '400', 'worker addition', 'Bob', '1', 'worker addition', 'Charlie', '2', 'status update', 'completed', 'EXIT']) == ['Construction site name is HomeProject, budget is 200000.0, material inventory is {'wood': 150, 'tiles': 400}, workers are {1: 'Bob', 2: 'Charlie'}']
    assert candidate(['HospitalBuild', '1000000', 'material addition', 'cement', '500', 'material addition', 'bricks', '1200', 'worker addition', 'David', '1', 'worker removal', '1', 'status update', 'in progress', 'EXIT']) == ['Construction site name is HospitalBuild, budget is 1000000.0, material inventory is {'cement': 500, 'bricks': 1200}, workers are {}']


Prompt:
from typing import List
def input_for_cont1(data:str)->List[str]:
    """I want to create dummy context manager.
    Here's it should be:
    1. create class ContextManager
    2. When I call it, it should print "init method called"
    3. When I call it with "with" statement, it should print "enter method called"
    4. When I exit from "with" statement, it should print "exit method called"
    5. Before exit from "with" statement, it should print "XXXX" (XXXX - any text from user)
    Take XXXX from user and print all 4 messages in order mentioned above.
    Example:
    Input: "Hello i'm in context manager"
    Output: ["init method called", "enter method called", "Hello i'm in context manager", "exit method called"]"""

class ContextManager:
    def __init__(self, text: str):
        self.text = text
        print("init method called")

    def __enter__(self):
        print("enter method called")
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        print(self.text)
        print("exit method called")

def input_for_cont1(data: str) -> List[str]:
    messages = []

    # Define a function to capture print statements
    def mock_print(*args, **kwargs):
        messages.append(' '.join(map(str, args)))

    # Replace the built-in print function with mock_print within this context
    original_print = __builtins__.print
    __builtins__.print = mock_print

    # Use the ContextManager with the provided data
    with ContextManager(data):
        pass

    # Restore the original print function
    __builtins__.print = original_print

    return messages

METADATA = {'author': 'ay', 'dataset': 'test'}

def check(candidate):
    assert candidate("Hello i'm in context manager") == ["init method called", "enter method called", "Hello i'm in context manager", "exit method called"]


Prompt:
from decimal import Decimal, getcontext
def input_for_cont2(data:str)->str:
    """I'm working in space and astronomy institute where calculations need to be
    done in a very precise way. I'm working on a project where I need to calculate.
    Small part of it is division of two numbers which need to be very precise upto
    n decimal places.
    Take input from user for two numbers and precision value n. and return the
    result upto n decimal places in form of string.
    You should use context manager to set precision value.
    Example:
    Input: 1, 42, 42 # 1 is a, 42 is b, 42 is precision value
    Output: "0.0238095238095238095238095238095238095238095"
 """

# Set the precision
getcontext().prec = n

# Perform the division using Decimal for high precision
result = Decimal(a) / Decimal(b)

# Reset the precision to default (28) to avoid side effects
getcontext().prec = 28

return str(result)  # Convert the result to a string


Prompt:
from decimal import Decimal, getcontext
def input_for_cont3(data:str)->str:
    """I'm working in science lab where experminets and their calculations
    done in a very precise way. I'm working on a project where I need to calculate.
    Small part of it is division of two numbers which need to be very precise upto
    n decimal places.
    Take input from user for two numbers and precision value n. and return the
    result upto n decimal places in form of string.
    You should use context manager to set precision value.
    Example:
    Input: 1, 42, 42 # 1 is a, 42 is b, 42 is precision value
    Output: "0.0238095238095238095238095238095238095238095"
 """


Prompt:
def divide(x:int, y:int) -> str:
    """I have few codes which may or may not run successfully.
    I want to know what error it will print if it fails to run.
    And if it runs successfully, it should print the output.
    The code if for division of two numbers.
    Take two numbers as input from user and divide them.
    The error is:  unsupported operand type(s) for //: 'int' and 'str'
    The error is:  integer division or modulo by zero
    Example:
    Input: 5,2
    Output: "2.5"
    Input: 5,0
    Output: "The error is: integer division or modulo by zero """

METADATA = {
    'author': 'ay',
    'dataset': 'test'
}

def check(candidate):
    assert candidate(2,5) == "0.4"
    assert candidate(2,0) == "integer division or modulo by zero"
    assert candidate(1,5) == "0.2"
    assert candidate(11,0) == "integer division or modulo by zero"


Prompt:
def write_file(first:str, second:str) -> str:
    """I have a file named dummy.txt. I want to write some text in it i.e. "This is a dummy file."
    Later I want to write some more text in it i.e. "This is a dummy file2."
    But when I run the code, it gives me an error. I want to know what error it is, please print it.
    The error is: I/O operation on closed file."""

METADATA = {
    'author': 'ay',
    'dataset': 'test'
}

def check(candidate):
    assert candidate("This is a dummy file.", "This is a dummy file2.") == "I/O operation on closed file."


Prompt:
def max_capacity(n:int, m:int) -> int:
    """I have 2 pack of floor of n and m kgs. I have to purchase a scope of such capacity that it can be used for both bags.
    But the idea is the number of scoops to empty both bag should be natural number respectively.
    Also the scope should be of maximum capacity as possible.
    Take input from user for n and m and return the maximum capacity of scope.
    Try to use recursion to solve this problem.
    Example:
    Input: 3, 5
    Output: 1
    Input: 4,20
    Output: 4
    Input: 6,15
    Output: 3"""

if b == 0:
    return a
return max_capacity(b, a % b)

METADATA = {'author': 'ay', 'dataset': 'test'}

def check(candidate):
    assert candidate(3,5) == 1
    assert candidate(4,20) == 4
    assert candidate(6,15) == 3
    assert candidate(26,39) == 13


Prompt:
def max_stencils(n:int, a:int, b:int, c:int) -> int:
    """I have a wall of length n, and 3 stencils of length a, b, and c. I have to paint the wall using these stencils.
    But in such a way that the number of stencils used to paint the wall should be maximum to bring out the best design.
    Also, the length of the wall should be completely covered by the stencils.
    Take input from user for n, a, b, and c and return the maximum number of stencils used to paint the wall.
    Try to use recursion to solve this problem.
    Example:
    Input: 23, 11, 9, 12
    Output: 2
    Input: 17, 10, 11, 3
    Output: 3"""

if n == 0 :
    return 0
if n <= -1 :
    return -1
res = max(max_stencils(n-a,a,b,c),
            max_stencils(n-b,a,b,c),
            max_stencils(n-c,a,b,c))
if res == -1 :
    return -1
return res + 1

METADATA = {'author': 'ay', 'dataset': 'test'}

def check(candidate):
    assert candidate(23, 11, 9, 12) == 2
    assert candidate(17, 10, 11, 3) == 3
    assert candidate(18, 11, 9, 3) == 6
    assert candidate(21, 11, 9, 2) == 7


Prompt:
def round_chairs(n:int, k:int) -> int:
    """I am playing a game of round chairs with my friends. Where n chairs are arranged in a circle.
    Every time a game starts the kth chair is removed from the circle and the game continues.
    Until only one chair is left. I have to find out the position of the last chair left in the circle so that I can win the game.
    Take input from user for n and k and return the position of the last chair left in the circle.
    Try to use recursion to solve this problem.
    Example:
    Input: 14, 2
    Output: 13
    Input: 7, 3
    Output: 4"""

if (n == 1):
    return 1
else:
    return (round_chairs(n - 1, k) + k-1) % n + 1

METADATA = {'author': 'ay', 'dataset': 'test'}

def check(candidate):
    assert candidate(14, 2) == 13
    assert candidate(7, 3) == 4
    assert candidate(10, 2) == 5
    assert candidate(11, 5) == 8


Prompt:
def qwerty_phone(key_presses: list) -> list:
    """I saw the qwerty phones and i was thinking about the number of key presses to type a word.
    So, now I want to find the numbers of words that can be typed using the given number of key presses.
    My keypad looks like this:
    1:{},2:{'a','b','c'},3:{'d','e','f'},4:{'g','h','i'},5:{'j','k','l'},6:{'m','n','o'},7:{'p','q','r','s'},8:{'t','u','v'},9:{'w','x','y','z'},0:{}
    Take input from user for the order of key presses and return the words that can be typed using the given number of key presses.
    Try to use recursion to solve this problem.
    Example:
    Input: [2,3,4]
    Output: ['adg', 'adh', 'adi', 'aeg', 'aeh', 'aei', 'afg', 'afh', 'afi', 'bdg', 'bdh', 'bdi', 'beg', 'beh', 'bei', 'bfg', 'bfh', 'bfi', 'cdg', 'cdh', 'cdi', 'ceg', 'ceh', 'cei', 'cfg', 'cfh', 'cfi']"""

digit_map = {
    '2': 'abc',
    '3': 'def',
    '4': 'ghi',
    '5': 'jkl',
    '6': 'mno',
    '7': 'pqrs',
    '8': 'tuv',
    '9': 'wxyz',
}

def qwerty_phone(input):
  input = str(input)
  ret = ['']
  for char in input:
    letters = digit_map.get(char, '')
    ret = [prefix+letter for prefix in ret for letter in letters]
  return ret

METADATA = {'author': 'ay', 'dataset': 'test'}

def check(candidate):
    assert candidate([2,3,4]) == ['adg', 'adh', 'adi', 'aeg', 'aeh', 'aei', 'afg', 'afh', 'afi', 'bdg', 'bdh', 'bdi', 'beg', 'beh', 'bei', 'bfg', 'bfh', 'bfi', 'cdg', 'cdh', 'cdi', 'ceg', 'ceh', 'cei', 'cfg', 'cfh', 'cfi']
    assert candidate([1]) == []
    assert candidate([2,3]) == ['ad', 'ae', 'af', 'bd', 'be', 'bf', 'cd', 'ce', 'cf']


Prompt:
def match_ptr(s:str, ptr:str) -> bool:
    """Given an string s and a pattern ptr, implement  pattern matching with support for '+' and '-' where:
    '+' Matches any single character.
    '-' Matches any sequence of characters (including the empty sequence).
    The matching should cover the entire input string (not partial).
    Take input from user for s and ptr and return True if the pattern matches the string, else False.
    Try to use recursion to solve this problem.
    Example:
    Input: s = "aa", ptr = "a+"
    Output: True
    Input: s = "aa", ptr = "a"
    Output: false
    """

i, j, si, m = 0, 0, -1, 0
while i < len(s):
    if j < len(p) and (s[i] == p[j] or p[j] == '+'):
        j += 1
        i += 1
    elif j < len(p) and p[j] == '-':
        si = j
        m = i
        j += 1
    elif si != -1:
        j = si + 1
        m += 1
        i = m
    else:
        return False
while j < len(p) and p[j] == '-':
    j += 1
return j == len(p)

METADATA = {'author': 'ay', 'dataset': 'test'}

def check(candidate):
    assert candidate('aa', 'a+') == True
    assert candidate('aa','a') == False
    assert candidate('aab', '-a-') == True
    assert candidate('aab', '-a') == False