{"task_id":"PythonSaga/0", "prompt":"\nfrom typing import List\n\ndef extra_marks(marks:List[float])-> float:\n \"\"\"let say i have a list of marks scored in each question by person. I want a sum of all the extra marks he/she scored in exam,\n extra score is whatever he scored above 100 in each question.\n but if marks is below 0 in any question it would reduce the total extra scores.\n Take input from user and return the sum of extra marks.\n Example:\n Input: [100, 120, -30, 140, -50, -60, 170, 22,55,-20]\n Output: -30\n Input: [100, 120, -30]\n Output: -10\n Input: [100, 22,75,99]\n Output: 0\n \"\"\"\n", "entry_point": "extra_marks", "canonical_solution":"\nextra = 0\nfor mark in marks:\n if mark > 100:\n extra += mark - 100\n elif mark < 0:\n extra += mark\nreturn extra", "test": "\n\nMETADATA = {\n 'author': 'ay',\n 'dataset': 'test'\n}\n\n\ndef check(candidate):\n assert candidate([100, 120, -30, 140, -50, -60, 170, 22,55,-20,-90]) == -120\n assert candidate([111, 20, -130, 140, -50, -60, 170, 22,55,-20,-190]) == -329\n assert candidate([170, 22,55,-20,-90]) == -40\n assert candidate([100.1, 120, -30, 140, -50, -60, 170, 22,55,-20,-90]) == -119.9\n"} {"task_id":"PythonSaga/1", "prompt":"\nfrom typing import List\n\ndef split_big_bag(big_bag: List[int])->bool:\n \"\"\"i have one big bag in which there are multiple small bags fill with sand. bag of each small bag is different from each other.\n i want to split the big bad into 2 medium bags, such that avergae weight of each medium bag is same.\n Take input from user and return True if it is possible to split the big bag into 2 medium bags, else return False.\n Input: big_bag = [1,2,3,4,5,6,7,8]\n Output: true\n Input: big_bag = [3,1]\n Output: false\"\"\"\n", "entry_point": "split_big_bag", "canonical_solution":"\ntotal_weight = sum(big_bag)\n# Check if the total weight is even\nif total_weight % 2 != 0:\n return False\n\ntarget_weight = total_weight // 2\n\n# Create a 2D array to store whether it's possible to achieve a certain weight with the given bags\ndp = [[False] * (target_weight + 1) for _ in range(len(big_bag) + 1)]\n\n# Base case: If the target weight is 0, it's always possible (by not selecting any bag)\nfor i in range(len(big_bag) + 1):\n dp[i][0] = True\n\nfor i in range(1, len(big_bag) + 1):\n for j in range(1, target_weight + 1):\n # If the current bag weight is greater than the target weight, skip it\n if big_bag[i - 1] > j:\n dp[i][j] = dp[i - 1][j]\n else:\n # Either include or exclude the current bag to achieve the target weight\n dp[i][j] = dp[i - 1][j] or dp[i - 1][j - big_bag[i - 1]]\n\nreturn dp[len(big_bag)][target_weight]", "test": "METADATA = {\n 'author': 'ay',\n 'dataset': 'test'\n}\n\n\ndef check(candidate):\n assert candidate([0]) == True\n assert candidate([5,2,3]) == True\n assert candidate([8]) == False\n assert candidate([1 2 3 4 5 6]) == False"} {"task_id":"PythonSaga/2", "prompt":"\nfrom typing import List\n\ndef is_path_crossing(distances: List[int]) -> bool:\n \"\"\"Check whether the path crosses itself or not.\n Suppose you are standing at the origin (0,0), and you are given a list of 4 distances,\n where each distance is a step in a direction (N, W, S, E).\n\n Take input from the user and return True if your path crosses itself, else False.\n\n Example:\n Input: [2, 1, 1, 1]\n Output: True\n Input: [1, 2, 3, 4]\n Output: False\n Input: [1, 2, 1, 2]\n Output: True\n \"\"\"\n", "entry_point": "is_path_crossing", "canonical_solution":"\nif len(distances) < 4:\n return False\n\n# Initialize the starting point and direction\nx, y = 0, 0\ndirections = [(0, 1), (-1, 0), (0, -1), (1, 0)] # N, W, S, E\nvisited = {(0, 0)}\n\nfor i in range(len(distances)):\n # Calculate the new position based on the current direction\n x += distances[i] * directions[i % 4][0]\n y += distances[i] * directions[i % 4][1]\n\n # Check if the new position has been visited before\n if (x, y) in visited:\n return True\n\n # Add the current position to the visited set\n visited.add((x, y))\n\nreturn False", "test": "\nMETADATA = {\n 'author': 'ay',\n 'dataset': 'test'\n}\n\ndef check(candidate):\n assert candidate([1, 2, 3, 4]) == False\n assert candidate([1, 2, 1, 2]) == True\n assert candidate([2, 1, 1, 1]) == True\n assert candidate([11, 0, 1, 3]) == True"} {"task_id":"PythonSaga/3", "prompt":"\nfrom typing import List\n\ndef is_boomarang(points: List[List[int]]) -> bool:\n \"\"\"Check if the 3 points form a boomerang.\n A boomerang is a set of 3 points that are all distinct and not in a straight line.\n\n Take input from the user and return True if the 3 points are a boomerang and False if not.\n\n Input: [[1,1],[2,3],[3,2]]\n Output: True\n Input: [[1,1],[2,2],[3,3]]\n Output: False\n \"\"\"\n # Your implementation here\n pass", "entry_point": "is_boomarang", "canonical_solution":"\n# Ensure there are exactly 3 points\nif len(points) != 3:\n return False\n\n# Extract coordinates of the three points\nx1, y1 = points[0]\nx2, y2 = points[1]\nx3, y3 = points[2]\n\n# Check if the points are distinct\nif (x1, y1) == (x2, y2) or (x1, y1) == (x3, y3) or (x2, y2) == (x3, y3):\n return False\n\n# Check if the points are not in a straight line\nif (x1 * (y2 - y3) + x2 * (y3 - y1) + x3 * (y1 - y2)) != 0:\n return True\n\nreturn False", "test": "\nMETADATA = {\n 'author': 'ay',\n 'dataset': 'test'\n}\n\ndef check(candidate):\n assert candidate([[1, 1], [2, 3], [3, 2]]) == True\n assert candidate([[1, 1], [2, 2], [3, 3]]) == False\n assert candidate([[-1, -1], [0, 0], [1, 1]]) == False\n assert candidate([[0, 0], [1, 2], [3, 4]]) == True\n assert candidate([[0, 0], [1, 2]]) == False"} {"task_id":"PythonSaga/4", "prompt":"\nfrom typing import List\n\ndef max_square_area(coordinates: List[List[int]]) -> int:\n \"\"\"Find the maximum area of a square that can be formed from the given coordinates.\n The square has all sides equal and each side is parallel to the x or y axis with a length of at least 1 unit.\n\n Take input from the user and return the maximum area of the square that can be formed from these coordinates.\n\n Example:\n INPUT: [[1,1],[1,3],[3,1],[3,3],[2,2]]\n Output: 4\n INPUT: [[1,1],[1,3],[3,1],[4,1],[4,4]]\n Output: 0\n \"\"\"\n", "entry_point": "max_square_area", "canonical_solution":"", "test": "\n\nMETADATA = {\n 'author': 'ay',\n 'dataset': 'test'\n}\n\n\ndef check(candidate):\n assert candidate([[1,1],[1,3],[4,1],[4,5],[5,3]]) == 4\n assert candidate([[1,1],[1,5],[3,1],[3,3],[2,2]]) == 9\n assert candidate([[1,1], [2,2],[4,1]]) == 0\n assert candidate([[1, 1], [1, 3], [3, 1], [4, 1], [4, 4]]) == 4\n"} {"task_id":"PythonSaga/5", "prompt":"\nfrom typing import List\ndef pattern1(n: int) -> List[str]:\n \"\"\"Return the list of the specified pattern based on the input 'n'.\n The pattern consists of letters from 'A' to 'Z' arranged in a specific manner.\n\n Example:\n Input: 5\n Output: [' A', ' B A', ' A B C', ' D C B A', 'E D C B A']\n\n Input: 3\n Output: [' A', ' B A', 'A B C']\n \"\"\"\n", "entry_point": "pattern1", "canonical_solution":"\nresult = []\nfor i in range(n):\n # Add leading spaces\n line = ' ' * (n - i - 1)\n\n # Add characters in ascending order\n for j in range(i + 1):\n line += chr(65 + (j % 26))\n if j < i: # Add a space after each character except the last one\n line += ' '\n\n result.append(line)\n\nreturn result", "test":"\nMETADATA = {\n 'author': 'ay',\n 'dataset': 'test'\n}\n\n\ndef check(candidate):\n assert candidate(5) == [\" A\", \" B A\", \" A B C\", \" D C B A\", \"E D C B A\"]\n assert candidate(3) == [\" A\", \" B A\", \"A B C\"]\n assert candidate(1) == [\"A\"]\n assert candidate(0) == []"} {"task_id":"PythonSaga/6", "prompt":"\ndef pattern2(n: int) -> str:\n \"\"\"\n take n as input from user, where n is number of terms and print the following pattern in form of string.\n write python code using for loop\n Example:\n Input: 5\n Output: 1+4-9+16-25\n Input: 3\n Output: 1+4-9\n \"\"\"\n", "entry_point": "pattern2", "canonical_solution":"\nresult = ''\nfor i in range(1, n + 1):\n term = i ** 2\n\n # Add the term to the result with the appropriate sign\n if i % 2 == 1: # If i is odd\n result += f'{term}+'\n else:\n result += f'{term}-'\n\n# Remove the trailing '+' or '-'\nresult = result.rstrip('+-')\n\nreturn result", "test": "\nMETADATA = {\n 'author': 'ay',\n 'dataset': 'test'\n}\n\n\ndef check(candidate):\n assert candidate(5) == \"1+4-9+16-25\"\n assert candidate(3) == \"1+4-9\"\n assert candidate(1) == \"1\"\n assert candidate(0) == \"\""} {"task_id":"PythonSaga/7", "prompt":"\nfrom typing import List\n\ndef find_roots(a: int, b: int, c: int) -> List[int]:\n \"\"\"\n write program to find all the roots of a quadratic equation using match case in python.\n Take input from user that will be a, b, c of the quadratic equation.\n Example:\n Input: 1, 5, 6\n Output: [-2, -3]\n Input: 1, 4, 4\n Output: [-2, -2]\n \"\"\"\n", "entry_point": "find_roots", "canonical_solution":"\ndiscriminant = b**2 - 4*a*c\nroots = []\n\nif discriminant > 0:\n root1 = int((-b + (discriminant)**0.5) / (2*a))\n root2 = int((-b - (discriminant)**0.5) / (2*a))\n roots = [root1, root2]\nelif discriminant == 0:\n root = int(-b / (2*a))\n roots = [root]\n\nreturn roots", "test": "\nMETADATA = {\n 'author': 'ay',\n 'dataset': 'test'\n}\n\n\ndef check(candidate):\n assert candidate(1, 5, 6) == [-2, -3]\n assert candidate(1, 4, 4) == [-2, -2]\n assert candidate(1, 0, -1) == [1, -1]\n assert candidate(2, -8, 6) == [3, 1]"} {"task_id":"PythonSaga/8", "prompt":"\ndef price_of_painting(mrp: float, age: int) -> float:\n \"\"\"\n lets say the price of painting depends on how old it is.\n if it is less than 5 years old, it will cost mrp + 5% of mrp\n if it is 5 or more than 5 years old but less than 11, it will cost mrp + 8% of mrp\n if it is older than 11 years it will be mrp + 10% of mrp\n take mrp and age of painting as input and print the final price of painting\n Example:\n Input: 1000, 5\n Output: 1080.0\n Input: 1000, 12\n Output: 1100.0\n \"\"\"\n", "entry_point": "price_of_painting", "canonical_solution":"\nif age < 5:\n return mrp + 0.05 * mrp\nelif 5 <= age < 11:\n return mrp + 0.08 * mrp\nelse:\n return mrp + 0.10 * mrp", "test": "\nMETADATA = {\n 'author': 'ay',\n 'dataset': 'test'\n}\n\ndef check(candidate):\n assert candidate(1000, 5) == 1080.0\n assert candidate(1000, 12) == 1100.0\n assert candidate(1500, 3) == 1575.0\n assert candidate(800, 8) == 864.0"} {"task_id":"PythonSaga/9", "prompt":"\nfrom typing import List\n\ndef division(a: int, b: int) -> List[str]:\n \"\"\"\n let's say we get a, b from the user as 2 numbers, we have to return the division of a and b.\n solve it using a try-except block. if b is zero then print 'You cannot divide by zero!'\n if a and b are not numbers then print 'Please enter a valid integer!'\n and finally if everything is fine then print the division of a and b and also print 'This is always executed'\n using the finally block.\n Return the result in the form of a list.\n Example:\n Input: 10, 2\n Output: ['5', 'This is always executed']\n Input: 10, 0\n Output: ['You cannot divide by zero!']\n Input: 10, 'a'\n Output: ['Please enter a valid integer!']\n \"\"\"\n", "entry_point": "division", "canonical_solution":"\nfrom typing import List\n\ndef division(a: int, b: int) -> List[str]:\n \"\"\"\n let's say we get a, b from the user as 2 numbers, we have to return the division of a and b.\n solve it using a try-except block. if b is zero then print 'You cannot divide by zero!'\n if a and b are not numbers then print 'Please enter a valid integer!'\n and finally if everything is fine then print the division of a and b and also print 'This is always executed'\n using the finally block.\n Return the result in the form of a list.\n Example:\n Input: 10, 2\n Output: ['5', 'This is always executed']\n Input: 10, 0\n Output: ['You cannot divide by zero!']\n Input: 10, 'a'\n Output: ['Please enter a valid integer!']\n \"\"\"\n try:\n result = a / b\n return [str(result), 'This is always executed']\n except ZeroDivisionError:\n return ['You cannot divide by zero!']\n except TypeError:\n return ['Please enter a valid integer!']\n finally:\n print('This is always executed')", "test": "\nMETADATA = {\n 'author': 'ay',\n 'dataset': 'test'\n}\n\ndef check(candidate):\n assert candidate(10, 2) == ['5.0', 'This is always executed']\n assert candidate(10, 0) == ['You cannot divide by zero!']\n assert candidate(10, 'a') == ['Please enter a valid integer!']\n assert candidate(20, 4) == ['5.0', 'This is always executed']"} {"task_id":"PythonSaga/10", "prompt":"\nfrom typing import List\n\ndef pattern(n: int) -> List[str]:\n \"\"\"\n Lets say I want to create a hollow diamond shape using asterisk(*) in python of size n.\n where n is the number of rows from top to end.\n eg. if n=5 then output should be like this:\n *\n * *\n * *\n * *\n *\n Take input from the user and return the pattern in the form of a list of strings.\n Example:\n Input: 5\n Output: [' * ', ' * * ', '* *', ' * * ', ' * ']\n Input: 3\n Output: [' * ', '* *', ' * ']\n Input: 1\n Output: ['*']\n \"\"\"\n", "entry_point": "pattern", "canonical_solution":"", "test": "\nMETADATA = {\n 'author': 'ay',\n 'dataset': 'test'\n}\n\ndef check(candidate):\n assert candidate(5) == [' * ', ' * * ', '* *', ' * * ', ' * ']\n assert candidate(3) == [' * ', '* *', ' * ']\n assert candidate(1) == ['*']\n assert candidate(7) == [' * ', ' * * ', ' * * ', '* *', ' * * ', ' * * ', ' * ']"} {"task_id":"PythonSaga/11", "prompt":"\nfrom typing import List\n\ndef pattern(n: int) -> List[str]:\n \"\"\"\n K shape character pattern program for n lines\n if n = 4 then output should be like this\n A B C D\n B C D\n C D\n D\n C D\n B C D\n A B C D\n Take input from the user and return the pattern in the form of a list of strings.\n Example:\n Input: 4\n Output: ['A B C D', 'B C D', 'C D', 'D', 'C D', 'B C D', 'A B C D']\n Input: 3\n Output: ['A B C', 'B C', 'C', 'B C', 'A B C']\n \"\"\"\n", "entry_point": "pattern", "canonical_solution":"\nresult = []\n\n# Upper half of the pattern\nfor i in range(n, 0, -1):\n row = ' '.join(chr(64 + j) for j in range(n - i + 1, n + 1))\n result.append(row)\n\n# Lower half of the pattern\nfor i in range(2, n + 1):\n row = ' '.join(chr(64 + j) for j in range(n - i + 1, n + 1))\n result.append(row)", "test": "\nMETADATA = {\n 'author': 'ay',\n 'dataset': 'test'\n}\n\ndef check(candidate):\n assert candidate(4) == ['A B C D', 'B C D', 'C D', 'D', 'C D', 'B C D', 'A B C D']\n assert candidate(3) == ['A B C', 'B C', 'C', 'B C', 'A B C']\n assert candidate(1) == ['A']\n assert candidate(6) == ['A B C D E F', 'B C D E F', 'C D E F', 'D E F', 'E F', 'F', 'E F', 'D E F', 'C D E F', 'B C D E F', 'A B C D E F']"} {"task_id":"PythonSaga/12", "prompt":"\nfrom typing import List\n\ndef pattern(n: int) -> List[int]:\n \"\"\"\n let's say given the number n, I want to print all the n prime numbers starting from 5 in such a way that,\n the sum of any two consecutive prime numbers is divisible by 3.\n Take input from the user and return the pattern in the form of a list.\n example: if n = 5, then output should be [5, 7, 11, 13, 17]\n example: if n = 6, then output should be [5, 7, 11, 13, 17, 19]\n \"\"\"\n", "entry_point": "pattern", "canonical_solution":"\ndef is_prime(num):\n \"\"\"\n Check if a number is prime.\n \"\"\"\n if num < 2:\n return False\n for i in range(2, int(num**0.5) + 1):\n if num % i == 0:\n return False\n return True\n\ndef pattern(n: int) -> List[int]:\n primes = []\n current_number = 5\n\n while len(primes) < n:\n if is_prime(current_number):\n if len(primes) >= 2 and (primes[-1] + current_number) % 3 == 0:\n primes.append(current_number)\n elif len(primes) < 2:\n primes.append(current_number)\n current_number += 2\n\n return primes", "test": "\nMETADATA = {\n 'author': 'ay',\n 'dataset': 'test'\n}\n\ndef check(candidate):\n assert pattern(5) == [5, 7, 11, 13, 17]\n assert pattern(6) == [5, 7, 11, 13, 17, 19]\n assert pattern(10) == [5, 7, 11, 13, 17, 19, 23, 31, 41, 43]\n assert pattern(8) == [5, 7, 11, 13, 17, 19, 23, 31]"} {"task_id":"PythonSaga/13", "prompt":"\nfrom typing import List\n\ndef pattern(n: int) -> List[int]:\n \"\"\"\n Let's say on getting n as input code gives n numbers for a particular series, which looks like 5, 7, 10, 36... and so on.\n where the series is based on the following rule:\n 5 x 1 + 2 = 7\n 7 x 2 - 4 = 10\n 10 x 3 + 6 = 36\n 36 x 4 - 8 = 136\n ....\n print the series till the nth number.\n Take input from the user and return the pattern in the form of a list.\n example:\n Input: 5\n Output: [5, 7, 10, 36, 136]\n Input: 7\n Output: [5, 7, 10, 36, 136, 690, 4128]\n \"\"\"\n", "entry_point": "pattern", "canonical_solution":"\nresult = [5]\n\nfor i in range(1, n):\n if i % 2 == 1:\n result.append(result[-1] * i + 2*i)\n else:\n result.append(result[-1] * i - 2*i)\n\nreturn result", "test": "\nMETADATA = {\n 'author': 'ay',\n 'dataset': 'test'\n}\n\ndef check(candidate):\n assert candidate(5) == [5, 7, 10, 36, 136]\n assert candidate(7) == [5, 7, 10, 36, 136, 690, 4128]\n assert candidate(3) == [5, 7, 10]\n assert candidate(10) == [5, 7, 10, 36, 136, 690, 4128, 28910, 231264, 2081394]"} {"task_id":"PythonSaga/14", "prompt":"\ndef pattern(n: int) -> List[str]:\n \"\"\"\n Write a program that receives a number n as input and prints it in the following format as shown below.\n Like for n = 2 the pattern will be:\n 1*2*5*6\n --3*4\n or for n = 3 the pattern will be:\n 1*2*3*10*11*12\n --4*5*8*9\n ----6*7\n Take input from the user and return the pattern in the form of a list of strings.\n Example:\n Input: 3\n Output: ['1*2*3*10*11*12', '--4*5*8*9', '----6*7']\n Input: 2\n Output: ['1*2*5*6', '--3*4']\n \"\"\"\n", "entry_point": "pattern", "canonical_solution":"", "test": "\nMETADATA = {\n 'author': 'ay',\n 'dataset': 'test'\n}\n\ndef check(candidate):\n assert pattern(2) == ['1*2*5*6', '--3*4']\n assert pattern(3) == ['1*2*3*10*11*12', '--4*5*8*9', '----6*7']\n assert pattern(4) == ['1*2*3*4*17*18*19*20', '--5*6*7*14*15*16', '----8*9*12*13', '------10*11']\n assert pattern(5) == ['1*2*3*4*5*26*27*28*29*30', '--6*7*8*9*22*23*24*25', '----10*11*12*19*20*21', '------13*14*17*18', '--------15*16']"} {"task_id":"PythonSaga/15", "prompt":"\ndef toy_distribution(n: int) -> str:\n \"\"\"\n Let's say I have a bag of toys, which are 'n' in number. I know that these toys can be distributed either to n children or 1 child.\n I want to know what can be other ways to distribute these toys to children in such a way that each child gets at least an equal number of toys.\n Take input from the user for the number of toys.\n Use the divmod function to solve this problem.\n\n Example 1: If 15 toys are there, then 15 children can get 1 toy each or 1 child can get 15 toys or 3 children can get 5 toys each or 5 children can get 3 toys each.\n In this case, return 'Yes, it is possible'.\n Example 2: If 11 toys are there, then 11 children can get 1 toy each or 1 child can get 11 toys, that's it.\n In this case, return 'No, it is not possible'.\n \"\"\"\n", "entry_point": "toy_distribution", "canonical_solution":"\ndef is_prime(num):\n \"\"\"\n Check if a number is prime using divmod.\n \"\"\"\n if num < 2:\n return False\n\n for i in range(2, int(num**0.5) + 1):\n quotient, remainder = divmod(num, i)\n if remainder == 0:\n return False\n\n return True\n\ndef toy_distribution(n: int) -> str:\n if n <= 0 or not is_prime(n):\n return 'Yes, it is possible'\n\n return 'No, it is not possible'", "test": "METADATA = {\n 'author': 'ay',\n 'dataset': 'test'\n}\n\n\ndef check(candidate):\n assert candidate(15) == 'Yes, it is possible'\n assert candidate(11) == 'No, it is not possible'\n assert candidate(20) == 'Yes, it is possible'\n assert candidate(2) == 'No, it is possible'"} {"task_id":"PythonSaga/16", "prompt":"\nfrom typing import List\n\ndef filter_numbers(x: int, numbers: List[int]) -> List[int]:\n \"\"\"\n Filter all numbers in a list of numbers whose bitwise xor with the given value x is equal to 4 with the help of filter() in Python.\n Take value x and list of numbers as input from the user.\n input: 5, [1, 2, 3, 4, 5, 6, 7]\n output: [1]\n input: 5, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n output: [1, 9]\n \"\"\"", "entry_point": "filter_numbers", "canonical_solution":"\nfiltered_numbers = list(filter(lambda num: num ^ x == 4, numbers))\nreturn filtered_numbers", "test": "METADATA = {\n 'author': 'ay',\n 'dataset': 'test'\n}\n\ndef check(candidate):\n assert candidate(5, [1, 2, 3, 4, 5, 6, 7]) == [1]\n assert candidate(3, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) == [7]\n assert candidate(2, [3, 6, 9, 12, 15, 18]) == [6]\n assert candidate(6, [0, 2, 4, 6, 8, 10]) == [2]"} {"task_id":"PythonSaga/17", "prompt":"from typing import Dict, List\n\ndef patient_info(patient: Dict[str, List[float]]) -> List[Dict[str, float]]:\n \"\"\"Take a dictionary of patient information as input and return a list of dictionaries where each dictionary contains the key as patient name and value as one of the attributes at a time.\n Do this using the map function.\n Take input from the user for the dictionary and return a list of dictionaries.\n Example: \n Input: {'patient1': [20, 50, 5.5, 20], 'patient2': [30, 60, 5.6, 21], 'patient3': [40, 70, 5.7, 22]}\n Output: [{'patient1': 20, 'patient2': 30 ,'patient3': 40}, {'patient1': 50, 'patient2': 60 ,'patient3': 70}, {'patient1': 5.5, 'patient2': 5.6 ,'patient3': 5.7}, {'patient1': 20, 'patient2': 21 ,'patient3': 22}]\"\"\"\n", "entry_point": "patient_info", "canonical_solution":"attributes = list(patient.values())\nresult = list(map(lambda attr: {key: value for key, value in zip(patient.keys(), attr)}, zip(*attributes)))\nreturn result", "test": "METADATA = {\n 'author': 'ay',\n 'dataset': 'test'\n}\n\n\ndef check(candidate):\n input_data1 = {'patient1': [20, 50, 5.5, 20], 'patient2': [30, 60, 5.6, 21], 'patient3': [40, 70, 5.7, 22]}\n output1 = [{'patient1': 20, 'patient2': 30, 'patient3': 40}, {'patient1': 50, 'patient2': 60, 'patient3': 70},\n {'patient1': 5.5, 'patient2': 5.6, 'patient3': 5.7}, {'patient1': 20, 'patient2': 21, 'patient3': 22}]\n\n input_data2 = {'patient1': [25, 55, 5.4, 25], 'patient2': [35, 65, 5.8, 23], 'patient3': [45, 75, 5.9, 24]}\n output2 = [{'patient1': 25, 'patient2': 35, 'patient3': 45}, {'patient1': 55, 'patient2': 65, 'patient3': 75},\n {'patient1': 5.4, 'patient2': 5.8, 'patient3': 5.9}, {'patient1': 25, 'patient2': 23, 'patient3': 24}]\n\n input_data3 = {'patient1': [22, 52, 5.6, 22], 'patient2': [32, 62, 5.7, 20], 'patient3': [42, 72, 5.3, 21]}\n output3 = [{'patient1': 22, 'patient2': 32, 'patient3': 42}, {'patient1': 52, 'patient2': 62, 'patient3': 72},\n {'patient1': 5.6, 'patient2': 5.7, 'patient3': 5.3}, {'patient1': 22, 'patient2': 20, 'patient3': 21}]\n\n input_data4 = {'patient1': [21, 51, 5.8, 23], 'patient2': [31, 61, 5.4, 22], 'patient3': [41, 71, 5.6, 25]}\n output4 = [{'patient1': 21, 'patient2': 31, 'patient3': 41}, {'patient1': 51, 'patient2': 61, 'patient3': 71},\n {'patient1': 5.8, 'patient2': 5.4, 'patient3': 5.6}, {'patient1': 23, 'patient2': 22, 'patient3': 25}]\n\n assert candidate(input_data1) == output1\n assert candidate(input_data2) == output2\n assert candidate(input_data3) == output3\n assert candidate(input_data4) == output4"} {"task_id":"PythonSaga/18", "prompt":"from typing import Dict, List\n\ndef rank_students(students: Dict[str, int]) -> List[str]:\n \"\"\"Take a dictionary of student names and their scores as input and return the rank of each student based on their score.\n Example: \n Input: {\"Ankit\": 92, \"Bhavya\": 78, \"Charvi\": 88}\n Output: ['Rank 1: Ankit scored 92', 'Rank 2: Charvi scored 88', 'Rank 3: Bhavya scored 78']\n Do this using enumerate() function.\n Take input from the user for the dictionary and return the rank in form of list of strings.\"\"\"\n\n", "entry_point": "rank_students", "canonical_solution":"sorted_students = sorted(students.items(), key=lambda x: x[1], reverse=True)\nresult = [f\"Rank {rank + 1}: {name} scored {score}\" for rank, (name, score) in enumerate(sorted_students)]\nreturn result\n", "test": "METADATA = {\n 'author': 'ay',\n 'dataset': 'test'\n}\n\n\ndef check(candidate):\n input_data1 = {\"Ankit\": 92, \"Bhavya\": 78, \"Charvi\": 88}\n output1 = ['Rank 1: Ankit scored 92', 'Rank 2: Charvi scored 88', 'Rank 3: Bhavya scored 78']\n\n input_data2 = {\"John\": 85, \"Alice\": 90, \"Bob\": 78, \"Eve\": 92}\n output2 = ['Rank 1: Eve scored 92', 'Rank 2: Alice scored 90', 'Rank 3: John scored 85', 'Rank 4: Bob scored 78']\n\n\n assert candidate(input_data1) == output1\n assert candidate(input_data2) == output2\n"} {"task_id":"PythonSaga/19", "prompt":"def converter(num: int, choice: int) -> str:\n \"\"\"I want to create converter which takes number with base 10 as input and ask user to select one of the 3 options:\n 1. Convert to binary\n 2. Convert to hexadecimal\n 3. Convert to octal\n write a code which takes input from user and convert it to binary, hexadecimal or octal based on user's choice.\n Example:\n Input: 1, 10\n Output: 1010\n Input: 2, 10\n Output: A\n Input: 3, 10\n Output: 12\"\"\"\n", "entry_point": "converter", "canonical_solution":"if choice == 1:\n return bin(num)[2:]\nelif choice == 2:\n return hex(num)[2:].upper()\nelif choice == 3:\n return oct(num)[2:]\nelse:\n return 'Invalid choice. Please choose 1, 2, or 3.'", "test": "METADATA = {'author': 'ay', 'dataset': 'test'}\n\ndef check(candidate):\n assert converter(10, 1) == '1010'\n assert converter(10, 2) == 'A'\n assert converter(10, 3) == '12'\n assert converter(111, 3) == '1101111'"} {"task_id":"PythonSaga/20", "prompt":"from typing import List\ndef next_smallest(num:List[int]) -> List[int]:\n \"\"\"let's say I have to show a trick to my friend.\n That there are numbers whose a digits can be read from left to right or right to left, the number remains the same.\n For example, 121 is such a number. If you read it from left to right, it's 121. If you read it from right to left, it's still 121.\n But Now he gave me some random number and asked me to tell what is the next possible smallest number which can do this trick.\n for example, if he gave 23544 then the next possible smallest number is 23632.\n Take input from user and return the next possible smallest number which can do the trick.\n Take input as a List of digits and return the number as list of digits.\n Example:\n Input: [2,3,5,4,4]\n Output: [2,3,6,3,2]\n Input: [1,2,2]\n Output: [1,3,1]\"\"\"", "entry_point": "next_smallest", "canonical_solution":"num_int = int(''.join(map(str, num)))\n\n# Check if the number is already a palindrome\nif str(num_int) == str(num_int)[::-1]:\n num_int += 1\n\nwhile True:\n num_int += 1\n # Convert the incremented number to a list of digits\n num_list = [int(digit) for digit in str(num_int)]\n\n # Check if the number is a palindrome when read from left to right\n if num_list == num_list[::-1]:\n return num_list", "test": "METADATA = {'author': 'ay', 'dataset': 'test'}\n\ndef check(candidate):\n assert candidate([2, 3, 5, 4, 4]) == [2, 3, 6, 3, 2]\n assert candidate([1, 2, 2]) == [1, 3, 1]\n assert candidate([9, 9, 9]) == [1, 0, 0, 1]\n assert candidate([0]) == [1]"} {"task_id":"PythonSaga/21", "prompt":"from typing import List\ndef class_dict(teacher: List[str], student: List[str]) -> dict:\n \"\"\"let's say I have to maintain dictionary for class.\n here first key will be class name and value will be whether it's teacher or student.\n if it is student value will be name of student and a key marks will be there which will have marks of student.\n if it is teacher value will be name of teacher and a key subject will be there which will have subject of teacher.\n it will be nested dictionary.\n example: {'class1':{ 'teacher': {'name': 'abc', 'subject': 'maths'}, 'student': {'name': 'xyz', 'marks': {'maths': 90, 'science': 80}, 'name': 'pqr', 'marks': {'maths': 80, 'science': 90}}}}\n Input: class name, teacher/student, name, subject/marks, subject/marks\n Output: dictionary\n Take input from user and return the dictionary. Input can be in form of list one for teacher and one for student with their respective details.\n Example:\n Input: ['class1', 'teacher', 'abc', 'maths'], ['class1', 'student', 'xyz', 'maths', 90, 'science', 80]\n Output: {'class1':{ 'teacher': {'name': 'abc', 'subject': 'maths'}, 'student': {'name': 'xyz', 'marks': {'maths': 90, 'science': 80}}}}\n Input: ['class1', 'teacher', 'xyz', 'maths'], ['class1', 'student', 'abc', 'maths', 90, 'science', 80]\n Output: {'class1':{ 'teacher': {'name': 'xyz', 'subject': 'maths'}, 'student': {'name': 'abc', 'marks': {'maths': 90, 'science': 80}}}}\"\"\"", "entry_point": "class_dict", "canonical_solution":"class_data = {}\n\nfor t in teacher:\n class_name, role, name, subject = t[0], t[1], t[2], t[3]\n if class_name not in class_data:\n class_data[class_name] = {'teacher': {'name': '', 'subject': ''}, 'student': {}}\n\n if role == 'teacher':\n class_data[class_name]['teacher']['name'] = name\n class_data[class_name]['teacher']['subject'] = subject\n\nfor s in student:\n class_name, role, name, *marks = s\n marks_dict = {marks[i]: marks[i + 1] for i in range(0, len(marks), 2)}\n\n if class_name not in class_data:\n class_data[class_name] = {'teacher': {'name': '', 'subject': ''}, 'student': {}}\n\n if role == 'student':\n class_data[class_name]['student'][name] = {'marks': marks_dict}\n\nreturn class_data", "test": "METADATA = {'author': 'ay', 'dataset': 'test'}\n\ndef check(candidate):\n teacher_data_1 = [['class1', 'teacher', 'abc', 'maths']]\n student_data_1 = [['class1', 'student', 'xyz', 'maths', 90, 'science', 80]]\n assert candidate(teacher_data_1, student_data_1) == {'class1': {'teacher': {'name': 'abc', 'subject': 'maths'}, 'student': {'xyz': {'marks': {'maths': 90, 'science': 80}}}}}\n\n teacher_data_2 = [['class1', 'teacher', 'xyz', 'maths']]\n student_data_2 = [['class1', 'student', 'abc', 'maths', 90, 'science', 80]]\n assert candidate(teacher_data_2, student_data_2) == {'class1': {'teacher': {'name': 'xyz', 'subject': 'maths'}, 'student': {'abc': {'marks': {'maths': 90, 'science': 80}}}}}\n\n teacher_data_3 = [['class2', 'teacher', 'def', 'history']]\n student_data_3 = [['class2', 'student', 'uvw', 'history', 95, 'geography', 85]]\n assert candidate(teacher_data_3, student_data_3) == {'class2': {'teacher': {'name': 'def', 'subject': 'history'}, 'student': {'uvw': {'marks': {'history': 95, 'geography': 85}}}}}\n\n teacher_data_4 = [['class3', 'teacher', 'ghi', 'english'], ['class3', 'teacher', 'jkl', 'physics']]\n student_data_4 = [['class3', 'student', 'mno', 'english', 92, 'physics', 88]]\n assert candidate(teacher_data_4, student_data_4) == {'class3': {'teacher': {'name': 'jkl', 'subject': 'physics'}, 'student': {'mno': {'marks': {'english': 92, 'physics': 88}}}}}"} {"task_id":"PythonSaga/22", "prompt":"from typing import Tuple,Optional\ndef new_sum(nested_tuple: Tuple[int, Optional[Tuple]]) -> int:\n \"\"\"let's say I have a very bad habit of not using comments and I wrote something that my friend says is nested tuple.\n I have written a something whick looks like this: (5, (6, (1, (9, (10, None))))))\n I want to do the following with each value, value1 + value2 - value3 + value4 - value5 and soo on.\n example: 5 + 6 - 1 + 9 - 10 = 9\n Input: this nested tuple as a string from user.\n Output: the sum of the values in the nested tuple as shown above\n Example:\n Input: (5, (6, (1, (9, (10, None))))))\n Output: 9\n Input: (1, (2, (3, (4, (5, None))))))\n Output: -1\"\"\"", "entry_point": "new_sum", "canonical_solution":"", "test": "METADATA = {'author': 'ay', 'dataset': 'test'}\n\ndef check(candidate):\n assert candidate((5, (6, (1, (9, (10, None)))))) == 9\n assert candidate((1, (2, (3, (4, (5, None)))))) == -1\n assert candidate((10, (20, (30, (40, (50, None)))))) == -10\n assert candidate((2, (4, (8, (16, (32, None)))))) == -18"} {"task_id":"PythonSaga/23", "prompt":"from typing import List\ndef shoes_in_bag(bag: List[int]) -> int:\n \"\"\"let's say I have a bag full of shoes n boxes of same and different shoe sizes.\n I want to sell them in market so I have to hire some labors to do the job.\n I want to to do in such a way that no two shoe sizes are same with one labour.\n what is the minimum number of labors I need to hire to do the job?\n example1 : bag = [1,2,3,3] , labour = {1,2,3} and {3} so minimum 2 labours are required OR {1,3} and {2,3} so minimum 2 labours are required\n example2 : bag = [2,4,5,6] , labour = {2,4,5,6} so minimum 1 labour is required\n Input: take input from user for size of shoe in form of list\n Output: print minimum number of labours required to do the job\n Take input from user for size of shoe in form of list and return the minimum number of labours required to do the job\n Example:\n Input: [1,2,3,3]\n Output: 2\n Input: [2,4,5,6]\n Output: 1\"\"\"", "entry_point": "shoes_in_bag", "canonical_solution":"unique_sizes = set()\nlabors_needed = 0\n\nfor size in bag:\n if size not in unique_sizes:\n unique_sizes.add(size)\n else:\n labors_needed += 1\n unique_sizes.clear()\n unique_sizes.add(size)\n\nif unique_sizes:\n labors_needed += 1\n\nreturn labors_needed", "test": "METADATA = {'author': 'ay', 'dataset': 'test'}\n\ndef check(candidate):\n assert candidate([1,2,3,3]) == 2\n assert candidate([2,4,5,6,2,3,2]) == 3\n assert candidate([1,2,3,4,5]) == 1\n assert candidate([1,1,1,1,1]) == 5"} {"task_id":"PythonSaga/24", "prompt":"from typing import List\ndef flower_arrangement(flowers: List[str], start: int = 0, end: int = None, result: List[List[str]] = None) -> List[List[str]]:\n \"\"\"Let's say I have a 3 flowers which i have to lie on table in a row\n What are the all possible ways to arrange them.\n Input: Names of flowers from user\n Output: All possible ways to arrange them in a row\n Get the names of the flowers from the user and return list of lists of all possible ways to arrange them in a row\n Example:\n Input: [Rose, Lily, Jasmine]\n Output: [[Rose, Lily, Jasmine], [Rose, Jasmine, Lily], [Lily, Rose, Jasmine], [Lily, Jasmine, Rose], [Jasmine, Rose, Lily], [Jasmine, Lily, Rose]]\n Input: [Rose, Lily]\n Output: [[Rose, Lily], [Lily, Rose]]\"\"\"", "entry_point": "flower_arrangement", "canonical_solution":"if end is None:\n end = len(flowers) - 1\nif result is None:\n result = []\n\nif start == end:\n result.append(flowers.copy())\n return result\n\nfor i in range(start, end + 1):\n flowers[start], flowers[i] = flowers[i], flowers[start]\n flower_arrangement(flowers, start + 1, end, result)\n flowers[start], flowers[i] = flowers[i], flowers[start]\n\nreturn result", "test": "METADATA = {'author': 'ay', 'dataset': 'test'}\n\ndef check(candidate):\n assert candidate(['Rose', 'Lily', 'Jasmine']) == [['Rose', 'Lily', 'Jasmine'], ['Rose', 'Jasmine', 'Lily'], ['Lily', 'Rose', 'Jasmine'], ['Lily', 'Jasmine', 'Rose'], ['Jasmine', 'Rose', 'Lily'], ['Jasmine', 'Lily', 'Rose']]\n assert candidate(['Rose', 'Lily']) == [['Rose', 'Lily'], ['Lily', 'Rose']]\n assert candidate(['Daisy', 'Tulip', 'Sunflower']) == [['Daisy', 'Tulip', 'Sunflower'], ['Daisy', 'Sunflower', 'Tulip'], ['Tulip', 'Daisy', 'Sunflower'], ['Tulip', 'Sunflower', 'Daisy'], ['Sunflower', 'Daisy', 'Tulip'], ['Sunflower', 'Tulip', 'Daisy']]\n assert candidate(['Orchid', 'Carnation', 'Daffodil']) == [['Orchid', 'Carnation', 'Daffodil'], ['Orchid', 'Daffodil', 'Carnation'], ['Carnation', 'Orchid', 'Daffodil'], ['Carnation', 'Daffodil', 'Orchid'], ['Daffodil', 'Orchid', 'Carnation'], ['Daffodil', 'Carnation', 'Orchid']]"} {"task_id":"PythonSaga/25", "prompt":"import cmath\n\ndef phase(a: int, b: int) -> float:\n \"\"\"I have a number which my teacher told is complex number. \n Now my teacher asked me to find phase of that number.\n He gave me one definition that \"The angle or phase or argument of the complex number a + bj is the angle, measured in radians, from the point 1 + 0j to a + bj, \n with counterclockwise denoting positive angle.\" write a code to find phase of the complex number in radians.\n Take input from user in the form of a + bi and print the phase of the complex number.\n User will input a and b as integers. return float till 2 decimal places.\n Example:\n Input: -1, 0\n Output: 3.14\n Input: 2, 5\n Output: 1.19\"\"\"", "entry_point": "phase", "canonical_solution":"complex_number = complex(a, b)\nphase_angle = cmath.phase(complex_number)\nreturn round(phase_angle, 2)", "test": "METADATA = {'author': 'ay', 'dataset': 'test'}\n\ndef check(candidate):\n assert candidate(1, 0) == 0.0\n assert candidate(-1, 0) == 3.14\n assert candidate(0, 1) == 1.57\n assert candidate(2, -2) == -0.79"} {"task_id":"PythonSaga/26", "prompt":"from typing import List\n\ndef gate(gate_type: str, n: int, variables: List[int]) -> int:\n \"\"\"My electronics professor was teaching us about and, or, not, xor, nand, nor gates.\n He said we given n variables x1, x2, x3, x4, x5, or more, 6 gates and, or, not, xor, nand, nor can be made.\n He asked us to make a program that will take the gate type and value of n and n variables as input and print the output.\n Take input from user for the gate type and value of n and n variables.\n Print the output based on the gate type.\n example: if gate type is and and n is 3 and variables are 1, 0, 1 then output will be 0.\n if gate type is or and n is 3 and variables are 1, 0, 1 then output will be 1.\n Input: \"and\", 3, [1, 0, 1]\n Output: 0\n Input: \"or\", 3, [1, 0, 1]\n Output: 1\n \"\"\"", "entry_point": "gate", "canonical_solution":"if gate_type == \"and\":\n result = 1 # Initialize result with 1, as AND gate needs all inputs to be 1 for output to be 1.\n for variable in variables:\n result = result and variable\nelif gate_type == \"or\":\n result = 0 # Initialize result with 0, as OR gate needs at least one input to be 1 for output to be 1.\n for variable in variables:\n result = result or variable\nelif gate_type == \"not\":\n # NOT gate has only one input, so take the first variable and negate it.\n result = not variables[0]\nelif gate_type == \"xor\":\n # XOR gate output is 1 if the number of 1s in the inputs is odd.\n result = sum(variables) % 2 == 1\nelif gate_type == \"nand\":\n # NAND gate is the opposite of AND gate.\n result = not gate(\"and\", n, variables)\nelif gate_type == \"nor\":\n # NOR gate is the opposite of OR gate.\n result = not gate(\"or\", n, variables)\nelse:\n raise ValueError(\"Invalid gate type\")\n\nreturn int(result)", "test": "METADATA = {'author': 'ay', 'dataset': 'test'}\n\ndef check(candidate):\n assert candidate(\"and\", 3, [1, 0, 1]) == 0\n assert candidate(\"or\", 3, [1, 0, 1]) == 1\n assert candidate(\"not\", 1, [0]) == 1\n assert candidate(\"xor\", 4, [1, 0, 1, 1]) == 1"} {"task_id":"PythonSaga/27", "prompt":"def division(num: int, deno: int, float_num: float) -> list:\n \"\"\"Take 2 number as input from user and return the float division of them till 2 decimals. If the second number is 0, return None.\n similarly take float number as input from user and return numerator and denominator of the fraction, \n return all such possible pair of numerator and denominator.\n Take input from user in for num, deno and float number. and return division of num and deno till 2 decimals. and return numerator and denominator of the float number.\n Example:\n Input: 2, 3 , 0.25\n Output: [0.67 , 1 ,4]\n Input: 1,4, 0.67\n Output: [0.25, 2, 3]\"\"\"", "entry_point": "division", "canonical_solution":"", "test": "METADATA = {'author': 'ay', 'dataset': 'test'}\n\ndef check(candidate):\n assert candidate(2, 3, 0.25) == [0.67, 1, 4]\n assert candidate(5, 2, 0.6) == [2.5, 3, 5]\n assert candidate(8, 4, 0.125) == [2.0, 1, 8]\n assert candidate(22, 7, 0.72) == [3.14, 18, 25]"} {"task_id":"PythonSaga/28", "prompt":"def check_alphabet(sentence: str) -> str:\n \"\"\"My teacher gave me one sentence asked me to tell whether it's contains all the letters of the alphabet or not.\n So help me to write code which take input from user and tell whether it contains all the letters of the alphabet or not\n Example: The quick brown fox jumps over the lazy dog\n Output: It's does contain all the letters of the alphabet\n Example: The quick brown fox jumps over the dog\n Output: It's doesn't contain all the letters of the alphabet\"\"\"", "entry_point": "check_alphabet", "canonical_solution":"alphabet_set = set(\"abcdefghijklmnopqrstuvwxyz\")\nsentence_set = set(sentence.lower().replace(\" \", \"\"))\n\nif alphabet_set == sentence_set:\n return \"It does contain all the letters of the alphabet.\"\nelse:\n return \"It doesn't contain all the letters of the alphabet.\"", "test": "METADATA = {'author': 'ay', 'dataset': 'test'}\n\ndef check(candidate):\n assert candidate(\"The quick brown fox jumps over the lazy dog\") == \"It does contain all the letters of the alphabet.\"\n assert candidate(\"The quick brown fox jumps over the dog\") == \"It doesn't contain all the letters of the alphabet.\"\n assert candidate(\"Pack my box with five dozen liquor jugs\") == \"It does contain all the letters of the alphabet.\"\n assert candidate(\"How razorback-jumping frogs can level six piqued gymnasts!\") == \"It doesn't contain all the letters of the alphabet.\""} {"task_id":"PythonSaga/29", "prompt":"def card(color_or_number: str) -> str:\n \"\"\"I have deck of cards, and i want to play game with my friend.\n My friend will pick one card and can only either tell me its color or its number.\n I have to predict probability of card of being that color or number in a deck of 52 cards.\n Take input as color or number from user and return probability of that color or number in deck of cards.\n Example :\n Input: red\n Output: probability of red color in deck of cards 50%\n Input: 1\n Output: probability of 1 in deck of cards 7.69%\n Input: 2\n Output: probability of 2 in deck of cards 7.69%\"\"\"", "entry_point": "card", "canonical_solution":"deck = {\"red\": [\"Hearts\", \"Diamonds\"], \"black\": [\"Spades\", \"Clubs\"]}\nnumbers = list(map(str, range(1, 11))) + [\"Jack\", \"Queen\", \"King\", \"Ace\"]\n\nif color_or_number.isdigit() and 1 <= int(color_or_number) <= 10:\n number_prob = (4 / 52) * 100\n return f\"Probability of {color_or_number} in deck of cards: {number_prob:.2f}%\"\nelif color_or_number.isdigit():\n return \"Invalid input. Please enter a number between 1 and 10.\"\nelif color_or_number.lower() in deck:\n color_prob = (1/2) * 100\n return f\"Probability of {color_or_number.lower()} color in deck of cards: {color_prob:.2f}%\"\nelse:\n return \"Invalid input. Please enter a valid color or number.\"", "test": "METADATA = {\n 'author': 'ay',\n 'dataset': 'test'\n}\n\ndef check(candidate):\n assert candidate(\"red\") == \"Probability of red color in deck of cards: 50.00%\"\n assert candidate(\"1\") == \"Probability of 1 in deck of cards: 7.69%\"\n assert candidate(\"2\") == \"Probability of 2 in deck of cards: 7.69%\"\n assert candidate(\"black\") == \"Probability of black color in deck of cards: 50.00%\""} {"task_id":"PythonSaga/30", "prompt":"from typing import List\ndef TakeInput(marks: List[float], firstName: str, lastName: str, Class: str):\n \"\"\"my teacher gave me ine statement which looks like this:\n HomeWork(12,17,16,15.5,14,firstName='James', lastName='Bond', Class='7th' )\n Here 12,17,16,15.5,14 are marks scored by me in each subject. and firstName, lastName, Class are my personal details.\n She want me to write function HomeWork which take the given arguments and returns, and asked me to use args and kwargs.\n along with average marks scored by me in all subjects\n Output: \n Average Marks: 14.9\n firstName is James\n lastName is Bond\n Class is 7th\n Take input from user for marks and personal details in function TakeInput() and pass the arguments to HomeWork() function.\n Example:\n Input: [12,17,16,15.5,14], firstName='James', lastName='Bond', Class='7th'\n Output: [14.9, 'James', 'Bond', '7th']\n Input: [10,12,13,14,15], firstName='John', lastName='Doe', Class='8th'\n Output: [12.8, 'John', 'Doe', '8th']\"", "entry_point": "TakeInput", "canonical_solution":"def HomeWork(*marks, **details):\n average_marks = sum(marks) / len(marks)\n result = [average_marks]\n \n for value in details.values():\n result.append(value)\n \n return result\n\ndef TakeInput(marks: List[float], firstName: str, lastName: str, Class: str):\n return HomeWork(*marks, firstName=firstName, lastName=lastName, Class=Class)", "test": "METADATA = {\n 'author': 'ay',\n 'dataset': 'test'\n}\n\ndef check(candidate):\n assert candidate([12, 17, 16, 15.5, 14], firstName='James', lastName='Bond', Class='7th') == [14.9, 'James', 'Bond', '7th']\n assert candidate([10, 12, 13, 14, 15], firstName='John', lastName='Doe', Class='8th') == [12.8, 'John', 'Doe', '8th']\n assert candidate([0, 12, 13, -1, 15], firstName='Rik', lastName='ho', Class='11th') == [7.8, 'Rik', 'ho', '11th']\n assert candidate([170, 22, 55, -20, -90], firstName='Modi', lastName='Ji', Class='8th') == [27.4, 'Modi', 'Ji', '8th']"} {"task_id":"PythonSaga/31", "prompt":"import math\n\ndef Multiple_ques(frac: str, num: int, pal: str = None, string: str = None, prime: str = None, num2: int = None):\n \"\"\"I have 3 students, each ask me different questions. I want to answer them all in one function.\n 1st student always ask me factorial of a number\n 2nd student always ask me to check palindrome of a string\n 3rd student always ask me to check if a number is prime or not\n but it is not necessary that each of them will always ask me a question.\n So write me a function which will take a question and a number as input and return the answer.\n Take input from user for question and number and return the answer.\n Example:\n Input: \"factorial\", 5, \"palindrome\", \"madam\", \"prime\", 7\n Output: [\"The factorial of 5 is 120\", \"The string madam is a palindrome\", \"7 is a prime number\"]\n Input: \"factorial\", 5, \"palindrome\", \"madam\"\n Output: [\"The factorial of 5 is 120\", \"The string madam is a palindrome\"]\n Input: \"factorial\", 5, \"prime\", 7\n Output: [\"The factorial of 5 is 120\", \"7 is a prime number\"]\n \"\"\"\n" , "entry_point": "Multiple_ques", "canonical_solution":"def factorial(num):\n return math.factorial(num)\n\ndef is_palindrome(string):\n return string == string[::-1]\n\ndef is_prime(num):\n if num < 2:\n return False\n for i in range(2, int(math.sqrt(num)) + 1):\n if num % i == 0:\n return False\n return True\n\ndef Multiple_ques(frac: str=None, num: int=None, pal: str = None, string: str = None, prime: str = None, num2: int = None):\n answers = []\n\n if frac == \"factorial\":\n answers.append(f\"The factorial of {num} is {factorial(num)}\")\n \n if pal == \"palindrome\" and string is not None:\n answers.append(f\"The string {string} is {'a' if is_palindrome(string) else 'not a'} palindrome\")\n \n if prime == \"prime\" and num2 is not None:\n answers.append(f\"{num2} {'is' if is_prime(num2) else 'is not'} a prime number\")\n\n return answers", "test": "METADATA = {\n 'author': 'ay',\n 'dataset': 'test'\n}\n\n\ndef check(candidate):\n assert candidate(\"factorial\", 5, \"palindrome\", \"madam\", \"prime\", 7) == [\n \"The factorial of 5 is 120\",\n \"The string madam is a palindrome\",\n \"7 is a prime number\"\n ]\n assert candidate(\"factorial\", 5, \"palindrome\", \"madam\") == [\n \"The factorial of 5 is 120\",\n \"The string madam is a palindrome\"\n ]\n assert candidate(\"factorial\", 5, \"prime\", 7) == [\n \"The factorial of 5 is 120\",\n \"7 is a prime number\"\n ]"} {"task_id":"PythonSaga/32", "prompt":"def numbers(num:int):\n \"\"\"my teacher gave me so a list of numbers and asked me to convert it alpabetic words.\n example: 123 -> one hundred twenty three\n 456 -> four hundred fifty six\n 1001 -> one thousand one\n Fortunately, I have a list of numbers which are between 1 to 9999.\n Write a function to convert the numbers to words. \n If number is between 1 to 100 write one function and if it is between 100 to 9999 write another function.\n Take the input from the user and call the function accordingly.\n Example:\n 123 -> one hundred twenty three\n 456 -> four hundred fifty six\n 8989 -> eight thousand nine hundred eighty nine\"\"\"\n", "entry_point": "numbers", "canonical_solution":"", "test": "METADATA = {\n 'author': 'ay',\n 'dataset': 'test'\n}\n\n\ndef check(candidate):\n assert candidate(123) == \"one hundred twenty three\"\n assert candidate(456) == \"four hundred fifty six\"\n assert candidate(8989) == \"eight thousand nine hundred eighty nine\"\n assert candidate(1001) == \"one thousand one\""} {"task_id":"PythonSaga/33", "prompt":"from datetime import datetime\n\ndef date_subtract(date: str, days: int):\n \"\"\"My friend says he can tell any date in past given the days we want to subtract to the current date.\n I also want to have this super power. Can you help me to write a function which takes a date and the number of days to subtract and return the date in the past.\n Maximum number of days to subtract is 10000. and tell whether that year is a leap year or not.\n Take the current date as input in the format: YYYY-MM-DD and the number of days to subtract from the user and return the date in the past along with whether that year is a leap year or not.\n Example:\n Input: 2020-02-29, 365\n Output: 2019-02-28, 2019 is not a leap year\n Input: 2023-12-16, 1\n Output: 2023-12-15, 2023 is not a leap year\n \"\"\"\n", "entry_point": "date_subtract", "canonical_solution":"", "test": "METADATA = {\n 'author': 'ay',\n 'dataset': 'test'\n}\n\n\ndef check(candidate):\n assert candidate(\"2020-02-29\", 365) == (\"2019-03-01\", \"2019 is not a leap year\")\n assert candidate(\"2023-12-16\", 1) == (\"2023-12-15\", \"2023 is not a leap year\")\n assert candidate(\"2022-01-01\", 10000) == (\"1994-08-16\", \"1997 is not a leap year\")\n assert candidate(\"2000-02-29\", 7300) == (\"1980-03-05\", \"1980 is a leap year\")"} {"task_id":"PythonSaga/34", "prompt":"import math\n\ndef InputFunc(shape: str, action: str, *args):\n \"\"\"Let's say I'm working with some school student and I want to teach him about different geometric shapes. \n I have few shapes i.e cube, cuboid, sphere, cylinder and cone.\n Write a code that asks user to enter the name of the shape.\n then ask whether user want to calculate surface area or volume of the shape.\n Accordingly ask dimensions of the shape and calculate the surface area or volume of the shape.\n for example: if user enters cube and surface area, then ask for side of cube and calculate surface area of cube.\n if user enters cone and volume, then ask for radius and height of cone and calculate volume of cone.\n Here are guidelines to write a code:\n create individual functions for each shape.\n Take input from user for shape , surface area or volume and dimensions of the shape and return the result up to 2 decimal places.\n Example:\n Input: \"cube\", \"surface area\", 5\n Output: 150\n Input: \"cone\", \"volume\", 5, 10 # Radius followed by height\n Output: 261.8\"\"\"\n", "entry_point": "InputFunc", "canonical_solution":"import math\n\ndef InputFunc(shape: str, action: str, *args):\n shape = shape.lower()\n action = action.lower()\n\n if shape == \"cube\":\n if action == \"surface area\":\n return cube_surface_area(*args)\n elif action == \"volume\":\n return cube_volume(*args)\n \n elif shape == \"cuboid\":\n if action == \"surface area\":\n return cuboid_surface_area(*args)\n elif action == \"volume\":\n return cuboid_volume(*args)\n \n elif shape == \"sphere\":\n if action == \"surface area\":\n return sphere_surface_area(*args)\n elif action == \"volume\":\n return sphere_volume(*args)\n \n elif shape == \"cylinder\":\n if action == \"surface area\":\n return cylinder_surface_area(*args)\n elif action == \"volume\":\n return cylinder_volume(*args)\n \n elif shape == \"cone\":\n if action == \"surface area\":\n return cone_surface_area(*args)\n elif action == \"volume\":\n return cone_volume(*args)\n\n return \"Invalid shape or action\"", "test": "METADATA = {\n 'author': 'ay',\n 'dataset': 'test'\n}\n\ndef check(candidate):\n assert candidate(\"cube\", \"surface area\", 5) == 150.0\n assert candidate(\"cone\", \"volume\", 5, 10) == 261.8 #\n assert candidate(\"cuboid\", \"surface area\", 3, 4, 5) == 94.0\n assert candidate(\"sphere\", \"volume\", 2) == 33.51\n assert candidate(\"cylinder\", \"surface area\", 3, 6) == 150.8"} {"task_id":"PythonSaga/35", "prompt":"import math\nfrom typing import List\n\ndef operation(work: List[str]) -> float:\n \"\"\"Nowadays, I'm working a lot in maths and I want to calculate exp and log of a number a lot.\n Write a function that asks the operation to be performed and the number on which the operation is to be performed.\n There can be multiple entries for operation.\n Try to use the math library for this.\n Take input from the user and return the result up to 2 decimal places.\n Example:\n Input: ['exp', 10]\n Output: 22026.47\n Input: ['log', 10, 100]\n Output: 2\"\"\"\n", "entry_point": "operation", "canonical_solution":"if len(work) < 2:\n return \"Insufficient input. Please provide the operation and at least one number.\"\n\noperation_type = work[0].lower()\n\nif operation_type not in ['exp', 'log']:\n return \"Invalid operation. Please choose 'exp' or 'log'.\"\n\nif operation_type == 'exp' and len(work) == 2:\n # Calculate exponential\n result = math.exp(work[1])\nelif operation_type == 'log' and len(work) == 3:\n # Calculate logarithm\n base, x = work[1], work[2]\n result = math.log(x, base)\nelse:\n return \"Invalid input. Please provide the correct number of arguments for the selected operation.\"\n\nreturn round(result, 2)", "test": "METADATA = {\n\n 'author': 'ay',\n 'dataset': 'test'\n}\n\n\ndef check(candidate):\n assert candidate(['exp', 10]) == 22026.47\n assert candidate(['log', 10, 100]) == 2.0\n assert candidate(['exp', -1]) == 0.37\n assert candidate(['log', 2, 10001]) == 9.97"} {"task_id":"PythonSaga/36", "prompt":"import pickle\n\nfrom typing import List\n\ndef database(data: List[List[str]]) -> dict:\n \"\"\"Take entry from the user\n Key: Ankit\n name: Ankit Yadav\n age: 21\n city: Delhi\n Similarly take input from other users\n And store the information in a dictionary.\n later create a database dictionary and store all the information in that dictionary.\n with the key as the user name and value as a dictionary containing information about the user.\n later create a dbfile and store the dictionary in that file using binary mode\n Use the pickle module to store and retrieve the data.\n Finally, print the data from the database.\n Example:\n Input: [['Ankit', 'Ankit Yadav', '21', 'Delhi'], ['Amit', 'Amit Kumar', '21', 'Delhi']]\n Output: {'Ankit': {'name': 'Ankit Yadav', 'age': 21, 'city': 'Delhi'}, 'Amit': {'name': 'Amit Kumar', 'age': 21, 'city': 'Delhi'}}\"\"\"\n", "entry_point": "database", "canonical_solution":"db_dict = {}\n\n# Iterate through input data and create dictionary entries\nfor entry in data:\n if len(entry) == 4:\n username, name, age, city = entry\n db_dict[username] = {'name': name, 'age': int(age), 'city': city}\n else:\n print(f\"Invalid entry: {entry}. Each user entry should have exactly 4 elements.\")\n\n# Store the dictionary in a binary file using pickle\nwith open('dbfile.pkl', 'wb') as file:\n pickle.dump(db_dict, file)\n\nreturn db_dict", "test": "METADATA = {\n 'author': 'ay',\n 'dataset': 'test'\n}\n\n\ndef check(candidate):\n input_1 = [['Ank', 'Ank Ya', '21', 'Delhi'], ['Amit', 'Amit Kumar', '21', 'Delhi']]\n result_1 = candidate(input_1)\n assert result_1 == {'Ank': {'name': 'Ank Ya', 'age': 21, 'city': 'Delhi'},\n 'Amit': {'name': 'Amit Kumar', 'age': 21, 'city': 'Delhi'}}\n\n input_2 = [['John', 'John Doe', '25', 'New York'], ['Mary', 'Mary Johnson', '30', 'Los Angeles']]\n result_2 = candidate(input_2)\n assert result_2 == {'John': {'name': 'John Doe', 'age': 25, 'city': 'New York'},\n 'Mary': {'name': 'Mary Johnson', 'age': 30, 'city': 'Los Angeles'}}\n\n input_4 = [['Alice', 'Alice Smith', '28', 'London'], ['Bob', 'Bob Brown', '32', 'Paris', 'ExtraField']]\n result_4 = candidate(input_4)\n assert result_4 == {'Alice': {'name': 'Alice Smith', 'age': 28, 'city': 'London'},\n 'Bob': {'name': 'Bob Brown', 'age': 32, 'city': 'Paris'}}"} {"task_id":"PythonSaga/37", "prompt":"import re\n\ndef password_generator(password: str) -> str:\n \"\"\"I want to write a function to create a password using the following rules:\n At least 1 letter between [a-z]\n At least 1 number between [0-9]\n At least 1 letter between [A-Z]\n At least 1 character from [$#@]\n Minimum length of transaction password: 8\n Also write a function to check if the password is valid or not using regular expressions.\n Example :\n Input : \"Geek12#\"\n Output : Invalid Password!\n Input : \"Geek12#@\"\n Output : Valid Password\n Input : \"Annnnnnnnnn\"\n Output : Invalid Password!\"\"\"\n", "entry_point": "password_generator", "canonical_solution":"# Check if the password meets the required criteria\nif len(password) < 8:\n return \"Invalid Password!\"\n\nif not re.search(\"[a-z]\", password):\n return \"Invalid Password!\"\n\nif not re.search(\"[0-9]\", password):\n return \"Invalid Password!\"\n\nif not re.search(\"[A-Z]\", password):\n return \"Invalid Password!\"\n\nif not re.search(\"[$#@]\", password):\n return \"Invalid Password!\"\n\nreturn \"Valid Password\"", "test": "METADATA = {\n 'author': 'ay',\n 'dataset': 'test'\n}\n\n\ndef check(candidate):\n assert candidate(\"Geek12#\") == \"Invalid Password!\"\n assert candidate(\"Geek12#@\") == \"Valid Password\"\n assert candidate(\"Annnnnnnnnn\") == \"Invalid Password!\"\n assert candidate(\"StrongPwd123#\") == \"Valid Password\"\n assert candidate(\"abc123\") == \"Invalid Password!\""} {"task_id":"PythonSaga/38", "prompt":"import datetime\nfrom typing import List\ndef calculate_interest(input_list: List) -> str:\n \"\"\"i have to calculate interest on a given amount on per day basis.\n Write a functions which takes amount, rate of interest , starting date and end date as input and returns the interest amount and number of days.\n Use datetime module to calculate the number of days.\n Example:\n Input: [10000, 5, \"2020-01-01\", \"2020-01-10\"]\n Output: Interest amount is 5000.0 and number of days is 10\n Input: [100, 10, \"2020-01-01\", \"2020-01-30\"]\n Output: Interest amount is 300.0 and number of days is 30\"\"\"\n", "entry_point": "calculate_interest", "canonical_solution":"try:\n # Extract input values\n amount, rate_of_interest, start_date_str, end_date_str = input_list\n\n # Convert date strings to datetime objects\n start_date = datetime.strptime(start_date_str, \"%Y-%m-%d\")\n end_date = datetime.strptime(end_date_str, \"%Y-%m-%d\")\n\n # Calculate the number of days\n num_days = (end_date - start_date).days + 1\n\n # Calculate interest amount\n interest_amount = (amount * rate_of_interest / 100) * (num_days)\n\n return f\"Interest amount is {interest_amount:.2f} and number of days is {num_days}\"\n\nexcept ValueError:\n return \"Invalid date format. Please use YYYY-MM-DD.\"\nexcept Exception as e:\n return f\"Error: {str(e)}\"", "test": "METADATA = {\n 'author': 'ay',\n 'dataset': 'test'\n}\n\n\ndef check(candidate):\n assert candidate([10000, 5, \"2020-01-01\", \"2020-01-10\"]) == \"Interest amount is 500.00 and number of days is 10\"\n assert candidate([100, 10, \"2020-01-01\", \"2020-01-30\"]) == \"Interest amount is 300.00 and number of days is 30\"\n assert candidate([5000, 8, \"2022-03-15\", \"2022-04-15\"]) == \"Interest amount is 12800.00 and number of days is 32\"\n assert candidate([1500, 12, \"2021-08-01\", \"2021-08-10\"]) == \"Interest amount is 1800.00 and number of days is 10\""} {"task_id":"PythonSaga/39", "prompt":"from typing import List\nimport statistics\ndef calculate_stats(input_list: List) -> List:\n \"\"\"I want to see the magic of statistics.\n Write a code to take n number from user and return following statistics.\n 1. mean\n 2. harmonic mean\n 3. median\n 4. Low median\n 5. high median\n 6. Median grouped\n 7. mode\n 8. pvariance\n 9. variance\n 10. pstdev\n 11. stdev\n Use statistics module for this. return upto 2 decimal places.\n Example:\n Input: [1,2,3,4,5]\n Output: [3.0, 2.19, 3, 2, 4, 3.0, 1, 2.5, 2.5, 1.58, 1.58]\"\"\"\n", "entry_point": "calculate_stats", "canonical_solution":"try:\n # Calculate various statistics using the statistics module\n mean = round(statistics.mean(input_list), 2)\n harmonic_mean = round(statistics.harmonic_mean(input_list), 2)\n median = round(statistics.median(input_list), 2)\n low_median = round(statistics.median_low(input_list), 2)\n high_median = round(statistics.median_high(input_list), 2)\n median_grouped = round(statistics.median_grouped(input_list), 2)\n mode = round(statistics.mode(input_list), 2)\n pvariance = round(statistics.pvariance(input_list), 2)\n variance = round(statistics.variance(input_list), 2)\n pstdev = round(statistics.pstdev(input_list), 2)\n stdev = round(statistics.stdev(input_list), 2)\n\n # Return the calculated statistics\n return [mean, harmonic_mean, median, low_median, high_median, median_grouped, mode, pvariance, variance, pstdev, stdev]\n\nexcept Exception as e:\n return f\"Error: {str(e)}\"", "test": "METADATA = {\n 'author': 'ay',\n 'dataset': 'test'\n}\n\n\ndef check(candidate):\n assert candidate([1, 2, 3, 4, 5]) == [3.0, 2.19, 3, 2, 4, 3.0, 1, 2.5, 2.5, 1.58, 1.58]\n assert candidate([10, 20, 30, 40, 50]) == [30, 21.9, 30, 30, 30, 30.0, 10, 200, 250, 14.14, 15.81]\n assert candidate([2, 4, 6, 8, 10]) == [6, 4.38, 6, 6, 6, 6.0, 2, 8, 10, 2.83, 3.16]\n assert candidate([5, 15, 25, 35, 45]) == [25, 13.99, 25, 25, 25, 25.0, 5, 200, 250, 14.14, 15.81]"} {"task_id":"PythonSaga/40", "prompt":"def peter_picked(input_string: str) -> bool:\n \"\"\"User wants to give a long string, Find whether word Peter and picked came equally number of times or not\n If yes, print \"True\", else print \"False\"\n Take string as input from user\n example:\n Input: \"Peter picked a peck of pickled peppers. A peck of pickled peppers Peter picked. \n If Peter picked a peck of pickled peppers, Where's the peck of pickled peppers Peter picked?\"\n Output: True\n Input: \"Peter Piper picked a peck of pickled peppers. A peck of pickled peppers Peter Piper picked.\n Out: False\"\"\"\n", "entry_point": "peter_picked", "canonical_solution":"# Convert the input string to lowercase for case-insensitive comparison\nlower_input = input_string.lower()\n\n# Count the occurrences of \"peter\" and \"picked\"\ncount_peter = lower_input.count(\"peter\")\ncount_picked = lower_input.count(\"picked\")\n\n# Check if the counts are equal\nreturn count_peter == count_picked", "test": "METADATA = {\n 'author': 'ay',\n 'dataset': 'test'\n}\n\ndef check(candidate):\n assert candidate(\"Peter picked a peck of pickled peppers. A peck of pickled peppers Peter picked. If Peter picked a peck of pickled peppers, Where's the peck of pickled peppers Peter picked?\") == True\n assert candidate(\"Peter Piper picked a peck of pickled peppers. A peck of pickled peppers Peter Piper picked.\") == True\n assert candidate(\"Peter picked a peck of pickled peppers, and then Peter picked some more.\") == True\n assert candidate(\"Picked peppers Peter picked, but Pet didn't pick any more peppers.\") == False"} {"task_id":"PythonSaga/41", "prompt":"from typing import List\n\ndef student_marks(input_list: List[List[str]]) -> List[str]:\n \"\"\"\n Given a list of some students in a list and their corresponding marks in another list. The task is to do some operations as described below:\n a. i key value: Inserts key and value in the dictionary, and print 'Inserted'.\n b. d key: Delete the entry for a given key and print 'Deleted' if the key to be deleted is present, else print '-1'.\n c. key: Print marks of a given key in a statement as \"Marks of student name is : marks\".\n Take input from user and perform the operations accordingly.\n\n Example:\n Input: [[i, anil, 20], [i, ram, 30], [d, ankit], [p, ram]]\n Output: ['Inserted', 'Inserted', 'Deleted', 'Marks of ram is : 30']\n Input: [[i,jhon, 1],[c, jack],[p, jhon]]\n Output: ['Inserted', '-1', 'Marks of jhon is : 1'] \"\"\"\n", "entry_point": "student_marks", "canonical_solution":"student_dict = {}\nresult = []\n\nfor operation, *args in input_list:\n if operation == 'i':\n key, value = args\n student_dict[key] = int(value)\n result.append('Inserted')\n elif operation == 'd':\n key, = args\n if key in student_dict:\n del student_dict[key]\n result.append('Deleted')\n else:\n result.append('-1')\n elif operation == 'p':\n key, = args\n if key in student_dict:\n result.append(f'Marks of {key} is : {student_dict[key]}')\n else:\n result.append('-1')\n\nreturn result", "test": "METADATA = {\n 'author': 'ay',\n 'dataset': 'test'\n}\n\ndef check(candidate):\n input_1 = [['i', 'anil', '20'], ['i', 'ram', '30'], ['d', 'anil'], ['p', 'ram']]\n assert candidate(input_1) == ['Inserted', 'Inserted', 'Deleted', 'Marks of ram is : 30']\n input_2 = [['i', 'jhon', '1'], ['c', 'jack'], ['p', 'jhon']]\n assert candidate(input_2) == ['Inserted', '-1', 'Marks of jhon is : 1']\n input_3 = [['i', 'alice', '25'], ['i', 'bob', '35'], ['i', 'alice', '40'], ['p', 'bob'], ['d', 'charlie'], ['p', 'charlie']]\n assert candidate(input_3) == ['Inserted', 'Inserted', 'Inserted', 'Marks of bob is : 35', '-1', '-1']\n input_4 = [['i', 'amy', '50'], ['i', 'dan', '60'], ['d', 'amy'], ['p', 'amy']]\n assert candidate(input_4) == ['Inserted', 'Inserted', 'Deleted', '-1']"} {"task_id":"PythonSaga/42", "prompt":"from typing import List\ndef common_elements(input_list: List[List[int]]) -> List[List[int]]:\n \"\"\"Given some elements in two sets a and b, \n the task is to find the elements common in two sets, elements in both the sets, elements that are only in set a, not in b.\n Take input from user for two sets in form of list and print the output in form of list.\n Example: \n Input: [[1, 2, 3, 4, 5], [2, 3, 4, 5, 6]]\n Output: [2, 3, 4, 5], [1, 2, 3, 4, 5, 6], [1]\n Input: [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]]\n Output: [[],[1,2,3,4,5,6,7,8,9,10],[1,2,3,4,5]]\"\"\"\n", "entry_point": "common_elements", "canonical_solution":"set_a, set_b = set(input_list[0]), set(input_list[1])\n\ncommon_in_both = list(set_a.intersection(set_b))\nelements_in_both = list(set_a.union(set_b))\nelements_only_in_a = list(set_a.difference(set_b))\n\nreturn [common_in_both, elements_in_both, elements_only_in_a]", "test": "METADATA = {\n 'author': 'ay',\n 'dataset': 'test'\n}\n \ndef check(candidate):\n input_1 = [[1, 2, 3, 4, 5], [2, 3, 4, 5, 6]]\n assert candidate(input_1) == [[2, 3, 4, 5], [1, 2, 3, 4, 5, 6], [1]]\n input_2 = [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]]\n assert candidate(input_2) == [[], [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], [1, 2, 3, 4, 5]]\n input_3 = [[3, 6, 9, 12], [2, 4, 6, 8, 10, 12]]\n assert candidate(input_3) == [[6, 12], [2, 3, 4, 6, 8, 9, 10, 12], [3, 9]]\n input_4 = [[5, 10, 15, 20], [25, 30, 35, 40]]\n assert candidate(input_4) == [[], [5, 10, 15, 20, 25, 30, 35, 40], [5, 10, 15, 20]]\n"} {"task_id":"PythonSaga/43", "prompt":"from typing import List\ndef triangle(input_string: str) -> List[str]:\n \"\"\"Given a string of a constant length, print a triangle out of it. The triangle should start with the given string \n and keeps shrinking downwards by removing one character from the last of the string. \n The spaces on the right side of the triangle should be replaced with ' character.\n Take string as input from the user, return output as list of strings.\n Example:\n Input: 'Hello'\n Output: ['Hello', \"Hell'\", \"Hel''\", \"He'''\", \"H''''\"]\n Input: 'World'\n Output: ['World', \"Worl'\", \"Wor''\", \"Wo'''\", \"W''''\"]\"\"\"\n", "entry_point": "triangle", "canonical_solution":"length = len(input_string)\nresult = []\nfor i in range(length, 0, -1):\n triangle_line = input_string[:i].ljust(length, \"'\")\n result.append(triangle_line)\nreturn result", "test": "METADATA = {\n 'author': 'ay',\n 'dataset': 'test'\n}\n\n\ndef check(candidate):\n input_1 = 'Hello'\n assert candidate(input_1) == ['Hello', \"Hell'\", \"Hel''\", \"He'''\", \"H''''\"]\n input_2 = 'World'\n assert candidate(input_2) == ['World', \"Worl'\", \"Wor''\", \"Wo'''\", \"W''''\"]\n input_3 = 'Python'\n assert candidate(input_3) == ['Python', \"Pytho'\", \"Pyth''\", \"Pyt'''\", \"Py''''\", \"P'''''\"]\n input_4 = 'Triangle'\n assert candidate(input_4) == ['Triangle', \"Triangl'\", \"Triang''\", \"Trian'''\", \"Tria''''\", \"Tri'''''\", \"Tr''''''\", \"T''''''']"} {"task_id":"PythonSaga/44", "prompt":"from typing import List\ndef Y_pattern(N: int) -> List[str]:\n \"\"\"Print a Y shaped pattern from '(',')' and '|' in N number of lines.\n Note:\n 1. N is even.\n 2. All the strings in the string array which you will return is of length N, \n so add the spaces wherever required, so that the length of every string becomes N.\n Take N as input from the user. and return the list of strings.\n Example:\n Input: 6\n Output: ['\\ /', ' \\ /', ' \\/ ', ' | ', ' | ', ' | ']\n Input: 8\n Output: ['\\ /', ' \\ /', ' \\ /', ' \\/ ', ' | ', ' | ', ' | ', ' | ']\"\"\"\n", "entry_point": "Y_pattern", "canonical_solution":"", "test": "METADATA = {\n 'author': 'ay',\n 'dataset': 'test'\n}\n\ndef check(candidate):\n # Test Case 1\n input_1 = 6\n assert candidate(input_1) == ['\\ /', ' \\ / ', ' \\/ ', ' | ', ' | ', ' | ']\n\n # Test Case 2\n input_2 = 8\n assert candidate(input_2) == ['\\ /', ' \\ / ', ' \\ / ', ' \\/ ', ' | ', ' | ', ' | ', ' | ']\n\n # Test Case 3\n input_3 = 4\n assert candidate(input_3) == ['\\ /', ' \\/ ', ' | ', ' | ']\n\n # Test Case 4\n input_4 = 10\n assert candidate(input_4) == ['\\ /', ' \\ / ', ' \\ / ', ' \\ / ', ' \\/ ', ' | ', ' | ', ' | ', ' | ', ' | ']"} {"task_id":"PythonSaga/45", "prompt":"from typing import List\ndef encrypt(n: int, lines: List[str], shift: int) -> List[str]:\n \"\"\"You are assigned the task of developing a Python program that enables users to input multiple text strings. \n These input strings will be written to a file named 'user_input.txt.' After gathering all the input lines in the file, \n your program should extract the first two characters from the beginning of each paragraph and encrypt them using the Caesar cipher method. \n In Caesar cipher you have to just shift the character by the given shift value.\n for example : your string is 'Abc' and shift value is 2 then A->C, b->d and c->e. final encrypted string will be 'Cde'.\n You have to take two user input first is n line of string (each line you have to write in file name 'user_input.txt')\n , and second is integer shift (number of shift).\n Input will be in format of list of string and integer.\n Output will be encrypted string.\n Example:\n Input: 3, ['The restoring of the board is for two weeks.', 'Board officials said Silva was due to return to work.', 'Silva was due to return to work.'],4\n Output: ['The file is created with name user_input.txt', 'The encrypted string is: XlFsWm']\"\"\"\n", "entry_point": "encrypt", "canonical_solution":"with open('user_input.txt', 'w') as file:\n file.write('\\n'.join(lines))\n\n# Read the contents of the file\nwith open('user_input.txt', 'r') as file:\n contents = file.read()\n\n# Encrypt the first two characters of each paragraph using Caesar cipher\nencrypted_lines = []\nfor paragraph in contents.split('\\n'):\n if len(paragraph) >= 2:\n encrypted_paragraph = ''.join([\n chr((ord(char) - ord('A' if char.isupper() else 'a') + shift) % 26 + ord('A' if char.isupper() else 'a'))\n if char.isalpha() else char\n for char in paragraph[:2]\n ])\n encrypted_lines.append(encrypted_paragraph)\n\n# Add additional information to the result list\nresult = [\n f'The file is created with name user_input.txt',\n f'The encrypted string is: {\"\".join(encrypted_lines)}'\n]\n\nreturn result", "test": "METADATA = {\n 'author': 'ay',\n 'dataset': 'test'\n}\n\ndef check(candidate):\n # Test Case 1\n n_1 = 3\n lines_1 = [\n \"The restoring of the board is for two weeks.\",\n \"Board officials said Silva was due to return to work.\",\n \"Silva was due to return to work.\"\n ]\n shift_1 = 4\n assert candidate(n_1, lines_1, shift_1) == [\n 'The file is created with name user_input.txt',\n 'The encrypted string is: XlFsWm'\n ]\n\n # Test Case 2\n n_2 = 2\n lines_2 = [\n \"Sample input line one.\",\n \"Second sample input line.\"\n ]\n shift_2 = 2\n assert candidate(n_2, lines_2, shift_2) == [\n 'The file is created with name user_input.txt',\n 'The encrypted string is: UcUg'\n ]\n\n # Test Case 3\n n_3 = 4\n lines_3 = [\n \"Testing with multiple lines.\",\n \"Another line for testing.\",\n \"Third line to check functionality.\",\n \"Last line in this test.\"\n ]\n shift_3 = 3\n assert candidate(n_3, lines_3, shift_3) == [\n 'The file is created with name user_input.txt',\n 'The encrypted string is: WhDqWkOd'\n ]\n\n # Test Case 4\n n_4 = 2\n lines_4 = [\n \"AbCdeFgHiJklMnOpQrStUvWxYz\",\n \"XYZabcDEFGHIJKLMNOPQRSTUVW\"\n ]\n shift_4 = 5\n assert candidate(n_4, lines_4, shift_4) == [\n 'The file is created with name user_input.txt',\n 'The encrypted string is: FgCd'\n ]"} {"task_id":"PythonSaga/46", "prompt":"from typing import List\ndef count_words(lines: List[str]) -> str:\n \"\"\"Your task is to create a Python program that allows users to input multiple text strings. \n These input strings will be written to a file named 'user_input.txt.' After saving all the input lines in the file, \n your program should count the number of words in the file. In this version, a word is defined as a sequence of characters \n separated by spaces, and punctuation marks and symbols are included in the word count.\n Take input from user and reuturn the count of words in the input along with the file name\n Input will be in list of strings\n Example:\n Input: ['Hello i am programmer. I like python. I Love India .']\n Output: Number of words in the file user_input.txt is 11\n\n Input: ['All in the village were happy. They got a new TV !!!']\n Output: Number of words in the file user_input.txt is 12\"\"\"\n", "entry_point": "count_words", "canonical_solution":"with open('user_input.txt', 'w') as file:\n file.write('\\n'.join(lines))\n\n# Read the contents of the file\nwith open('user_input.txt', 'r') as file:\n contents = file.read()\n\n# Count the number of words in the file\nwords = contents.split()\nword_count = len(words)\n\nreturn f'Number of words in the file user_input.txt is {word_count}'", "test": "METADATA = {\n 'author': 'ay',\n 'dataset': 'test'\n}\n\n\ndef check(candidate):\n # Test Case 1\n input_1 = ['Hello i am programmer. I like python. I Love India .']\n assert candidate(input_1) == 'Number of words in the file user_input.txt is 11'\n\n # Test Case 2\n input_2 = ['All in the village were happy. They got a new TV !!!']\n assert candidate(input_2) == 'Number of words in the file user_input.txt is 12'\n\n # Test Case 3\n input_3 = ['This is a simple test case with a few words.']\n assert candidate(input_3) == 'Number of words in the file user_input.txt is 10'\n\n # Test Case 4\n input_4 = ['123 456 789']\n assert candidate(input_4) == 'Number of words in the file user_input.txt is 3'"} {"task_id":"PythonSaga/47", "prompt":"from typing import List\ndef count_words(n:int,lines: List[str],k:str) -> List[str]:\n \"\"\"Write a Python program that processes a series of text inputs and analyzes them for words containing a specific number of lowercase consonants.\n You have to return list of unique words that satisfy the given condition.\n For Example :- file content is 'Hello I am Jone' and k=2 then final answer list should be ['Hello'] Because only word 'Hello' contains 2 lowercase consonant.\n Accepts the user input for the number of lines and allows the user to input strings for the specified number of lines. The program should write these strings \n to a file named 'user_input.txt' \n Reads the contents of 'user_input.txt' analyzes each word, and outputs a list of words that contain exactly k lowercase consonants.\n Input would be in form of list of strings and k is an integer.\n Example:\n Input: 3, ['Hello I am Jone.', 'I like programming.', 'IIT Gandhinagar.'], 2\n Output: ['Hello', 'like']\n Input: 2, ['out of all the places in the world', 'i love india'], 2\n Output: ['out', 'all', 'the', 'love', 'india']\"\"\"\n", "entry_point": "count_words", "canonical_solution":"# Write user input lines to the file\nwith open('user_input.txt', 'w') as file:\n file.write('\\n'.join(lines))\n\n# Read the contents of the file\nwith open('user_input.txt', 'r') as file:\n contents = file.read()\n\n# Process each word and filter based on the number of lowercase consonants\nwords = contents.split()\nvalid_words = [word for word in words if sum(1 for char in word if char.islower() and char not in 'aeiou') == k]\n\nreturn valid_words", "test": "METADATA = {\n 'author': 'ay',\n 'dataset': 'test'\n}\n\ndef check(candidate):\n # Test Case 1\n n_1 = 3\n lines_1 = ['Hello I am Jone.', 'I like programming.', 'IIT Gandhinagar.']\n k_1 = 2\n assert candidate(n_1, lines_1, k_1) == ['Hello', 'like']\n\n # Test Case 2\n n_2 = 2\n lines_2 = ['out of all the places in the world', 'i love india']\n k_2 = 2\n assert candidate(n_2, lines_2, k_2) == ['out', 'all', 'the', 'love', 'india']\n\n # Test Case 3\n n_3 = 3\n lines_3 = ['Pytho programming is fun.', 'AI and machine learning.', 'OpenAI is innovative.']\n k_3 = 3\n assert candidate(n_3, lines_3, k_3) == ['Pytho']\n\n # Test Case 4\n n_4 = 2\n lines_4 = ['Testing with some random words.', 'Check for various situations.']\n k_4 = 1\n assert candidate(n_4, lines_4, k_4) == ['some', 'for']"} {"task_id":"PythonSaga/48", "prompt":"from typing import List\nfrom typing import Dict\n\ndef merge_data(data: List[List[str]]) -> List[Dict[str, str]]:\n \"\"\"You are tasked with processing student data provided by user.\n The file contains multiple entries for different subjects of each students, including Id, Student Name, Subject, and Marks.\n Write a Python program that reads the data from from input and merges it based on the following rules:\n For each unique student (identified by Roll number), consolidate their information. Combine the subjects and calculate the total \n marks for each student, avoiding duplicate subjects.\n After processing the data, save the file with name is students_data.txt with the formatted student information. The output should display the formatted contents of the updated file.\n Take input in form of list of list of strings. and return the list of dictionary.\n Example:\n Input: [[103, 'Maria', 'Physics', 50], [102, 'Hina', 'Math', 30], [104, 'Alex', 'Chemistry', 45], [101, 'Santosh', 'Biology', 20], [104, 'Alex', 'History', 38], [103, 'Maria', 'Chemistry', 35], [101, 'Santosh', 'Biology', 20], [101, 'Santosh', 'Biology', 20], [104, 'Alex', 'Chemistry', 45], [104, 'Alex', 'History', 38]]\n Output: file saved is students_data.txt, [{'Id':103,'Name': Maria,'Subject':[' Physics', ' Chemistry'],'TotalMarks': 85}, {'Id':102,'Name': Hina,'Subject':[' Math'],'TotalMarks': 30}, {'Id':104,'Name': Alex,'Subject':[' Chemistry', ' History'],'TotalMarks': 83}, {'Id':101,'Name': Santosh,'Subject':[' Biology'],'TotalMarks': 20}]\n \"\"\"", "entry_point": "merge_data", "canonical_solution":"student_dict = {}\n\n# Process the data and merge information for each student\nfor entry in data:\n roll_number, name, subject, marks = entry\n roll_number = int(roll_number)\n\n if roll_number not in student_dict:\n student_dict[roll_number] = {'Id': roll_number, 'Name': name, 'Subject': set(), 'TotalMarks': 0}\n\n # Avoid duplicate subjects for the same student\n if subject not in student_dict[roll_number]['Subject']:\n student_dict[roll_number]['Subject'].add(subject)\n student_dict[roll_number]['TotalMarks'] += int(marks)\n\n# Convert the dictionary values to a list of dictionaries\nresult = list(student_dict.values())\n\n# Save the file with formatted student information\nwith open('students_data.txt', 'w') as file:\n for student_info in result:\n file.write(f\"{student_info}\\n\")\n\nreturn result", "test": "METADATA = {\n 'author': 'ay',\n 'dataset': 'test'\n}\n\ndef check(candidate):\n # Test Case 2\n input_2 = [\n [101, 'John', 'Math', 75],\n [102, 'Jane', 'Physics', 90],\n [103, 'Bob', 'Chemistry', 80],\n [101, 'John', 'Biology', 60],\n [102, 'Jane', 'Math', 85],\n [103, 'Bob', 'Physics', 92]\n ]\n assert candidate(input_2) == [\n {'Id': 101, 'Name': 'John', 'Subject': {' Math', ' Biology'}, 'TotalMarks': 135},\n {'Id': 102, 'Name': 'Jane', 'Subject': {' Physics', ' Math'}, 'TotalMarks': 175},\n {'Id': 103, 'Name': 'Bob', 'Subject': {' Chemistry', ' Physics'}, 'TotalMarks': 172}\n ]\n\n # Test Case 3\n input_3 = [\n [201, 'Alice', 'English', 85],\n [202, 'Bob', 'History', 78],\n [203, 'Charlie', 'Math', 92],\n [201, 'Alice', 'Biology', 70],\n [202, 'Bob', 'English', 88],\n [203, 'Charlie', 'History', 80]\n ]\n assert candidate(input_3) == [\n {'Id': 201, 'Name': 'Alice', 'Subject': {' English', ' Biology'}, 'TotalMarks': 155},\n {'Id': 202, 'Name': 'Bob', 'Subject': {' History', ' English'}, 'TotalMarks': 166},\n {'Id': 203, 'Name': 'Charlie', 'Subject': {' Math', ' History'}, 'TotalMarks': 172}\n ]\n\n # Test Case 4\n input_4 = [\n [301, 'David', 'Physics', 95],\n [302, 'Eva', 'Chemistry', 88],\n [303, 'Frank', 'Biology', 75],\n [301, 'David', 'Math', 85],\n [302, 'Eva', 'Math', 92],\n [303, 'Frank', 'Physics', 80]\n ]\n assert candidate(input_4) == [\n {'Id': 301, 'Name': 'David', 'Subject': {' Physics', ' Math'}, 'TotalMarks': 180},\n {'Id': 302, 'Name': 'Eva', 'Subject': {' Chemistry', ' Math'}, 'TotalMarks': 180},\n {'Id': 303, 'Name': 'Frank', 'Subject': {' Biology', ' Physics'}, 'TotalMarks': 155}\n ]"} {"task_id":"PythonSaga/49", "prompt":"from typing import List, Dict\n\ndef word_frequency(n:int,lines: List[str], k: int) -> Dict[str, int]:\n \"\"\"Write a Python program for managing word frequency in a text file. \n The program should first prompt the user to input a specified number of lines, and these lines are then saved to a text file named text_file.txt \n The user is then prompted to input an integer representing the frequency threshold (k). Subsequently, the program reads the contents of this file, \n creating a dictionary that tracks the frequency of each word. \n The program should remove words from the file that occur more than k times and update the file accordingly. \n Finally, the program displays the initial word count dictionary and the total number of words in the updated file.\n Input will be in form of a list of strings, where each string represents a line of text.\n Output will be a dictionary containing the frequency of each word in the file, and the total number of words in the updated file.\n Example:\n Input: 3,[\"Hello can you help me\",\"you are doing well. How can I help you.\",\"can you help me ? I think you dont want to help me\"],2\n Output: {'Hello': 1, 'can': 3, 'you': 4, 'help': 4, 'me': 3, 'are': 1, 'doing': 1, 'well.': 1, 'How': 1, 'I': 2, 'you.': 1, '?': 1, 'think': 1, 'dont': 1, 'want': 1, 'to': 1},13\n Input: 4,[\"Hello how are you\",\"What is updates\",\"how you will do this work\",\"you have any idea\"],2\n Output: {'Hello': 1, 'how': 2, 'are': 1, 'you': 3, 'What': 1, 'is': 1, 'updates': 1, 'will': 1, 'do': 1, 'this': 1, 'work': 1, 'have': 1, 'any': 1, 'idea': 1},14\"\"\"\n", "entry_point": "word_frequency", "canonical_solution":"", "test": "METADATA = {'author': 'ay', 'dataset': 'test'}\n\n\ndef check(candidate):\n # Test Case 1\n input_1 = 3, [\"Hello can you help me\", \"you are doing well. How can I help you.\", \"can you help me ? I think you dont want to help me\"], 2\n assert candidate(*input_1) == (\n {'Hello': 1, 'can': 3, 'you': 4, 'help': 4, 'me': 3, 'are': 1, 'doing': 1, 'well.': 1, 'How': 1, 'I': 2, 'you.': 1, '?': 1, 'think': 1, 'dont': 1, 'want': 1, 'to': 1},\n 13\n )\n\n # Test Case 2\n input_2 = 4, [\"Hello how are you\", \"What is updates\", \"how you will do this work\", \"you have any idea\"], 2\n assert candidate(*input_2) == (\n {'Hello': 1, 'how': 2, 'are': 1, 'you': 3, 'What': 1, 'is': 1, 'updates': 1, 'will': 1, 'do': 1, 'this': 1, 'work': 1, 'have': 1, 'any': 1, 'idea': 1},\n 14\n )\n\n # Test Case 3\n input_3 = 3, [\"Python is a powerful language\", \"Python is widely used for data science\", \"Python has a large community\"], 1\n assert candidate(*input_3) == (\n {'Python': 3, 'is': 2, 'a': 2, 'powerful': 1, 'language': 1, 'widely': 1, 'used': 1, 'for': 1, 'data': 1, 'science': 1, 'has': 1, 'large': 1, 'community': 1},\n 10\n )"} { "task_id": "PythonSaga/50","prompt":"def infix_to_postfix_and_prefix(expression:str) -> (str,str):\n \"\"\"My teacher gave me an mathematical equation and she wants me to convert it to postfix notation and prefix notation. \n She said I have to use stack to do that, but I have cricket match to play. So please write a program for me to do that. \n Take expression as input from user in form of string and print postfix and prefix notation of it in string format.\n Example: \n Input: Enter expression: 2+3*4 \n Output: Postfix: 234*+ \n Prefix: +2*34 \n Input: Enter expression: ((a^b)+c) \n Output: Postfix: ab^c+ \n Prefix: +^abc \"\"\"\n","entry_point":"infix_to_postfix_and_prefix","canonical_solution":"def is_operator(char):\n return char in \"+-*/^\"\n\ndef get_precedence(operator):\n precedence = {'+': 1, '-': 1, '*': 2, '/': 2, '^': 3}\n return precedence.get(operator, 0)\n\ndef infix_to_postfix(infix_expr):\n postfix = []\n stack = []\n\n for char in infix_expr:\n if char.isalnum():\n postfix.append(char)\n elif char == '(': \n stack.append(char)\n elif char == ')':\n while stack and stack[-1] != '(': \n postfix.append(stack.pop())\n stack.pop()\n else:\n while stack and get_precedence(stack[-1]) >= get_precedence(char):\n postfix.append(stack.pop())\n stack.append(char)\n\n while stack:\n postfix.append(stack.pop())\n\n return ''.join(postfix)\n\ndef infix_to_prefix(infix_expr):\n prefix = []\n stack = []\n\n for char in infix_expr[::-1]:\n if char.isalnum():\n prefix.append(char)\n elif char == ')':\n stack.append(char)\n elif char == '(': \n while stack and stack[-1] != ')':\n prefix.append(stack.pop())\n stack.pop()\n else:\n while stack and get_precedence(stack[-1]) > get_precedence(char):\n prefix.append(stack.pop())\n stack.append(char)\n\n while stack:\n prefix.append(stack.pop())\n\n return ''.join(prefix[::-1])\n\n# Remove spaces from the expression\nexpression = ''.join(expression.split())\n\n# Call the helper functions\npostfix_result = infix_to_postfix(expression)\nprefix_result = infix_to_prefix(expression)\n\nreturn postfix_result, prefix_result","test":"METADATA = {\n 'author': 'ay',\n 'dataset': 'test'\n}\n\ndef check(candidate):\n assert candidate(\"2+3*4\") == ('234*+', '+2*34')\n assert candidate(\"((a^b)+c)\") == ('ab^c+', '+^abc')\n assert candidate(\"a+b*c-d/e^f\") == ('abc*+def^/-', '-+a*bc/d^ef')\n assert candidate(\"(A*B)+(C/D)\") == ('AB*CD/+', '+*AB/CD')"} { "task_id": "PythonSaga/51","prompt":"def remove_three_similar_characters(string: str) -> str:\n \"\"\"My uncle want to check my knowledge about python. He said to code me a program that will take a string as input from user\n and will remove three of similar characters from the string. He also said that The three characters should be of adjacent elements and \n after removing a three the remaining string is joined together. You can use stack to solve this problem.\n Example: \n Input: aaabbaaccd \n Output: bbaaccd \n Input: aaa \n Output: \"\"\"\n","entry_point":"remove_three_similar_characters","canonical_solution":"if not string:\n return \"Empty String\"\n\nstack = []\n\nfor char in string:\n # Check if the stack is not empty and the current character matches the top of the stack\n if stack and char == stack[-1][0]:\n # Increment the count of the top element in the stack\n stack[-1][1] += 1\n\n # Check if the count reaches 3, pop the element from the stack\n if stack[-1][1] == 3:\n stack.pop()\n else:\n # If the current character is different, push it onto the stack with count 1\n stack.append([char, 1])\n\n# Reconstruct the string from the stack\nresult = ''.join(char * count for char, count in stack)\n\nreturn result","test":"METADATA = {\n 'author': 'ay',\n 'dataset': 'test'\n}\n\ndef check(candidate):\n assert candidate(\"aaabbaaccd\") == \"bbaaccd\"\n assert candidate(\"aaa\") == \"\"\n assert candidate(\"abcde\") == \"abcde\"\n assert candidate(\"aaaabbbaaccd\") == \"ccd\""} { "task_id": "PythonSaga/52","prompt":"def same_expression(postfix: str, prefix: str) -> str:\n \"\"\"My friend found a expression which my friend said is postfix expression. \n But my other friend also have one equation which is he said is prefix expression. \n To find if both belongs to same expression or not. I need to convert both to infix expression. \n Write a program to convert both to infix expression. And check if both are same or not. \n If both are same print \"Both are same\" else print \"Both are not same\". \n Take input from user. \n Example: \n Input: Enter postfix expression: 23*5+ \n Enter prefix expression: +*235 \n Output: Both are same \n Input: Enter postfix expression: 23^5+ \n Enter prefix expression: +^236 \n Output: Both are not same \"\"\"\n","entry_point":"same_expression","canonical_solution":"def postfix_to_infix(postfix):\n stack = []\n for char in postfix:\n if char.isalnum(): # Operand\n stack.append(char)\n else: # Operator\n operand2 = stack.pop()\n operand1 = stack.pop()\n stack.append(f'({operand1}{char}{operand2})')\n return stack.pop()\n\ndef prefix_to_infix(prefix):\n stack = []\n for char in reversed(prefix):\n if char.isalnum(): # Operand\n stack.append(char)\n else: # Operator\n operand1 = stack.pop()\n operand2 = stack.pop()\n stack.append(f'({operand1}{char}{operand2})')\n return stack.pop()\n\ndef same_expression(postfix, prefix):\n infix_postfix = postfix_to_infix(postfix)\n infix_prefix = prefix_to_infix(prefix)\n return \"Both are same\" if infix_postfix == infix_prefix else \"Both are not same\"","test":"METADATA = {\n 'author': 'ay',\n 'dataset': 'test'\n}\n\ndef check(candidate):\n assert candidate(\"245/53-5^4^*+\", \"+2*/45^^-5354\") == \"Both are same\"\n assert candidate(\"ABD*+AD^+*\", \"++A*BD^AD\") == \"Both are same\"\n assert candidate(\"245/535^4^*+\", \"+2*/45^^-5354\") == \"Both are not same\"\n assert candidate(\"ABD*+AD^*+\", \"++A*BD^AD\") == \"Both are not same\""} { "task_id": "PythonSaga/53","prompt":"from typing import List\ndef poem_stack(n:int, actions:List[str]) -> str:\n \"\"\"Google came for interview in my college and asked me to design a game of remebmerence. \n They said I have a book of poems and initially i'm on index page. \n From there I can visit any poem or come back to previously visited poem. \n The task is to design a data structure and implement the functionality of visiting a poem and coming back to previously visited poem. \n The following functionalities should be implemented: \n 1. Go(poem) # poem can be name of poem\n 2. Next() # Go to next poem that we came back from\n 3. Previous(n) # Go to n poems back that you have seen before\n 4. Enter Over when you are done. \n Take actions as input from user and print the current poem we are on. Initially we are on index page.\n Try to use stack data structure to implement this.\n Example: \n\n Input: 9,[Go(\"Owl and the Pussycat\"), Go(\"The Road Not Taken\"), Previous(2), Next(), Go(\"Humpty Dumpty\"), Next(), Go(\"House that Jack Built\"), Previous(1), Over]\n Output: You are on the poem: Humpty Dumpty\n\n Input: 4,[Go(\"Owl and the Pussycat\"), Go(\"The Road Not Taken\"), Previous(3), Over]\n Output: You are on the poem: Index Page\"\"\"\n","entry_point":"poem_stack","canonical_solution":"class PoemStackGame:\n def __init__(self):\n self.history_stack = [\"Index Page\"] # Initialize with the Index Page\n self.forward_stack = []\n\n def go(self, poem: str):\n self.history_stack.append(poem)\n self.forward_stack.clear() # Clear forward history since we are visiting a new poem\n\n def next(self):\n if self.forward_stack:\n self.history_stack.append(self.forward_stack.pop())\n\n def previous(self, n: int):\n while n > 0 and len(self.history_stack) > 1: # Ensure we don't go beyond the Index Page\n self.forward_stack.append(self.history_stack.pop())\n n -= 1\n\n def current_poem(self):\n return self.history_stack[-1]\n\ndef poem_stack(n: int, actions: List[str]) -> str:\n game = PoemStackGame()\n for action in actions:\n if action.startswith(\"Go\"):\n _, poem = action.split('(\"')\n poem = poem.rstrip('\")')\n game.go(poem)\n elif action == \"Next()\":\n game.next()\n elif action.startswith(\"Previous\"):\n _, steps = action.split(\"(\")\n steps = int(steps.rstrip(\")\"))\n game.previous(steps)\n elif action == \"Over\":\n break\n\n return f\"You are on the poem: {game.current_poem()}\"","test":"METADATA = {\n 'author': 'ay',\n 'dataset': 'test'\n}\n\ndef check(candidate):\n assert candidate(6, [\"Go('Poem 1')\", \"Go('Poem 2')\", \"Next()\", \"Previous(1)\", \"Next()\", \"Over\"]) == \"You are on the poem: Poem 2\"\n assert candidate(5, [\"Go('Poem A')\", \"Previous(3)\", \"Next()\", \"Go('Poem B')\", \"Over\"]) == \"You are on the poem: Poem B\"\n assert candidate(8, [\"Go('Poem X')\", \"Next()\", \"Go('Poem Y')\", \"Previous(2)\", \"Go('Poem Z')\", \"Next()\", \"Go('Poem W')\", \"Over\"]) == \"You are on the poem: Poem W\"\n assert candidate(3, [\"Go('Poem Alpha')\", \"Previous(2)\", \"Over\"]) == \"You are on the poem: Index Page\""} { "task_id": "PythonSaga/54","prompt":"def book_stack(n:int, collection_a:list, collection_b:list) -> bool:\n \"\"\"You are an avid reader with two collections of unique books, labeled A and B, each containing N books. \n Your task is to determine whether the arrangement of books in collection B can be obtained from collection A. \n Both collections are placed in seperate shelves, and once you pick book from collection A, you cannot place it back in collection A. \n Either you can use one box for putting it down or arrange it in collection B. \n Take Collection A and Collection B as input from user and return True if Collection B can be obtained from Collection A using a set of \n bookshelves and operations mimicking a stack with boxes. Else return False. \n Example 1: \n Input: 5, [1, 2, 3, 4, 5], [3, 2, 1, 4, 5]\n Output: True\n Input: 5, [1, 2, 3, 4, 5], [5, 4, 3, 1, 2]\n Output: False\"\"\"\n","entry_point":"book_stack","canonical_solution":"stack = [] # Represents the box\na_pointer, b_pointer = 0, 0 # Pointers for collection A and B\n\nwhile b_pointer < n:\n # Move books from collection A to the stack until we find the next book needed for collection B\n while a_pointer < n and (not stack or stack[-1] != collection_b[b_pointer]):\n stack.append(collection_a[a_pointer])\n a_pointer += 1\n \n # If the top book on the stack is the next book needed for collection B, move it from the stack to collection B\n if stack and stack[-1] == collection_b[b_pointer]:\n stack.pop()\n b_pointer += 1\n else:\n # The next book needed for collection B is not on top of the stack, so the arrangement is not possible\n return False\n\n# If all books in collection B are correctly placed, the arrangement is possible\nreturn True","test":"METADATA = {\n 'author': 'ay',\n 'dataset': 'test'\n}\n\ndef check(candidate):\n assert candidate(5, [1, 2, 3, 4, 5], [3, 2, 1, 4, 5]) == True\n assert candidate(5, [1, 2, 3, 4, 5], [5, 4, 3, 1, 2]) == False\n assert candidate(4, [10, 20, 30, 40], [20, 10, 40, 30]) == True\n assert candidate(3, [7, 6, 5], [6, 5, 7]) == True"} { "task_id": "PythonSaga/55","prompt":"from typing import List\ndef reverse_book_order(n: int, books: list) -> str:\n \"\"\"Imagine you have a bookshelf filled with books, each labeled with a number, and a sticky note indicating the next book's location. \n This organized system is your Linked List, with the first book indicating the Head Pointer. \n In the quest to rearrange your bookshelf, write a code to reverse the order of the books. \n Treat each book as a node, complete with its label (data) and the sticky note (pointer) to the next book. Your goal is to have the Head Pointer \n now point to the last book, creating a reversed order. \n Imagine you're rearranging your bookshelf in real life and translate this into a coding spell. \n Take list of books as input from user and print the reversed list of books. \n Example: \n\n Input: 5,[1,2,3,4,5]\n Output: 5<--4<--3<--2<--1\n\n Input: 4,[A,C,D,E]\n Output: E<--D<--C<--A\"\"\"\n","entry_point":"reverse_book_order","canonical_solution":"class Node:\n def __init__(self, value):\n self.value = value\n self.next = None\n\nclass LinkedList:\n def __init__(self):\n self.head = None\n\n def append(self, value):\n if not self.head:\n self.head = Node(value)\n else:\n current = self.head\n while current.next:\n current = current.next\n current.next = Node(value)\n\n def reverse(self):\n prev = None\n current = self.head\n while current:\n next_node = current.next\n current.next = prev\n prev = current\n current = next_node\n self.head = prev\n\n def __str__(self):\n result = []\n current = self.head\n while current:\n result.append(str(current.value))\n current = current.next\n return '<--'.join(result)\n\ndef reverse_book_order(n: int, books: List[str]) -> str:\n book_list = LinkedList()\n for book in books:\n book_list.append(book)\n \n book_list.reverse()\n return str(book_list)","test":"def check(candidate):\n assert candidate(6,[10, 20, 30, 40, 50, 60]) == \"60<--50<--40<--30<--20<--10\"\n assert candidate(3,['X', 'Y', 'Z']) == \"Z<--Y<--X\"\n assert candidate(1,['SingleBook']) == \"SingleBook\"\n assert candidate(0,[]) == \"\""} { "task_id": "PythonSaga/56","prompt":"from typing import List\ndef students_line(n: int, ages: list) -> int:\n \"\"\"Given a line of students with ages represented by the Linked List, \n write a program to determine the minimum number of steps required to organize the students in non-decreasing order of age. \n In each step, rearrange the line to ensure that no student of younger age stands after an older one. \n Take the input from the user for the number of students and their ages. \n Example: \n Input: 11,[7,5,6,6,9,5,8,13,10,7,13]\n Output: 3\n Input: 5,[6,7,9,11,13]\n Output: 0\"\"\"\n","entry_point":"students_line","canonical_solution":"# Create a list of tuples where each tuple is (age, original_index)\nindexed_ages = list(enumerate(ages))\n# Sort the list by age\nindexed_ages.sort(key=lambda x: x[1])\n\nsteps = 0\nvisited = [False] * n # Keep track of visited nodes to avoid recounting\n\nfor i in range(n):\n # If the student is already in the correct position or visited\n if visited[i] or indexed_ages[i][0] == i:\n continue\n\n # Find the number of nodes in this cycle\n cycle_size = 0\n j = i\n while not visited[j]:\n visited[j] = True\n j = indexed_ages[j][0] # Move to the next node in the cycle\n cycle_size += 1\n\n # Add the number of steps needed for this cycle (cycle_size - 1)\n if cycle_size > 0:\n steps += cycle_size - 1\n\nreturn steps","test":"METADATA = {\n 'author': 'ay',\n 'dataset': 'test'\n}\n\ndef check(candidate):\n assert candidate(11, [7, 5, 6, 6, 9, 5, 8, 13, 10, 7, 13]) == 12\n assert candidate(5, [6, 7, 9, 11, 13]) == 0\n assert candidate(7, [10, 8, 6, 12, 15, 13, 11]) == 8\n assert candidate(6, [20, 18, 15, 21, 19, 22]) == 7"} { "task_id": "PythonSaga/57","prompt":"from typing import List\ndef buildings_height(n: int, heights: list) -> list:\n \"\"\"Imagine a society with buildings of varying heights, each represented by a node in a linked list. The heights are as follows: \n H1 -> H2 -> H3 -> H4 -> H5 -> and so on \n For each building in the society, find the height of the next taller building. \n Take linked list as input from user and print the output as shown below. \n Example:\n Input: 5,[4,9,6,5,7]\n Output: [9,0,7,7,0] \n\n Input: 7,[5,3,2,9,4,6,1]\n Output: [9,9,9,0,6,0,0]\"\"\"\n","entry_point":"buildings_height","canonical_solution":"# Initialize the result list with 0s, as default for buildings with no taller building to the right\nresult = [0 for _ in range(n)]\nstack = [] # Use a list as a stack to hold indices of the buildings\n\nfor i in range(n):\n # While stack is not empty and the current building is taller than the building at the index at the top of the stack\n while stack and heights[i] > heights[stack[-1]]:\n index = stack.pop() # Pop the index of the shorter building\n result[index] = heights[i] # Update the result for that building\n stack.append(i) # Push the current index onto the stack\n\n# No need to explicitly set remaining buildings in stack to 0, as result is initialized with 0s\n\nreturn result","test":"METADATA = {\n 'author': 'ay',\n 'dataset': 'test'\n}\n\ndef check(candidate):\n assert candidate(5, [4, 9, 6, 5, 7]) == [9, 0, 7, 7, 0]\n assert candidate(7, [5, 3, 2, 9, 4, 6, 1]) == [9, 9, 9, 0, 6, 0, 0]\n assert candidate(4, [10, 5, 8, 12]) == [12, 8, 12, 0]\n assert candidate(6, [2, 5, 7, 4, 3, 1]) == [5, 7, 0, 0, 0, 0]\n assert candidate(3, [1, 2, 3]) == [2, 3, 0]"} { "task_id": "PythonSaga/58","prompt":"from typing import List, Dict\ndef diamond_mine(n: int, diamonds: Dict[int, List[int]]) -> List[int]:\n \"\"\"Imagine you are the overseer of a diamond mine where diamonds are arranged in a unique structure. \n The mine is organized into levels, and each level represents a linked list of diamonds, sorted in ascending order. \n Each diamond node has two pointers: a next pointer to the next diamond in the same level and a bottom pointer to a linked list where this diamond is the head. \n Given a mine with diamonds arranged as follows: \n d1 -> d2 -> d3 -> d4 \n | | | | \n v v v v \n d5 d6 d7 d8 \n | | | | \n v v v v \n d9 d10 d11 \n | | | \n v v \n d12 d12 \n Your task is to write a function that takes diamond mine such that all diamonds appear in a single level while maintaining the sorted order. \n The flattened list should be printed using the bottom pointer instead of the next pointer.   \n Take Input from user and return the sorted list. \n Example: \n Input: 3,{4: [1, 2, 3, 4], 3: [5, None, 7, 8], 2: [9, None, 11, None]}\n Output: 1 2 3 4 5 7 8 9 11\n Input: 3,{5: [10, 11, 12, 13, 14], 4: [15, 16, 17, None, 18], 3: [19, 20, None, None, 21]}\n Output: 10 11 12 13 14 15 16 17 18 19 20 21\"\"\"\n","entry_point":"diamond_mine","canonical_solution":"","test":"METADATA = {\n 'author': 'ay',\n 'dataset': 'test'\n}\n\ndef check(candidate):\n assert candidate(3, {4: [1, 2, 3, 4], 3: [5, None, 7, 8], 2: [9, None, 11, None]}) == [1, 2, 3, 4, 5, 7, 8, 9, 11]\n assert candidate(3, {5: [10, 11, 12, 13, 14], 4: [15, 16, 17, None, 18], 3: [19, 20, None, None, 21]}) == [10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21]"} { "task_id": "PythonSaga/59","prompt":"from typing import List\ndef sitting_arrangment(n:int, roll_numbers: List[int]) -> List[int]:\n \"\"\"In a class there are n number of students. Each student have roll number R1, R2 to Rn. \n We are conducting exam and we want sitting order such that they don't cheat. \n Make them sit in this way: R1->Rn, R2->Rn-1, R3->Rn-2 and so on. \n Take a linked list of students roll number as input from user and return The sitting order. \n Example: \n Input: 11,[1, 4, 6, 8, 10, 13, 15, 19, 22, 27, 33]\n Output: [1, 33, 4, 27, 6, 22, 8, 19, 10, 15, 13]\"\"\"\n","entry_point":"sitting_arrangment","canonical_solution":"seating_order = []\n\nfor i in range(n // 2):\n seating_order.append(roll_numbers[i])\n seating_order.append(roll_numbers[n - 1 - i])\n\nif n % 2 != 0:\n seating_order.append(roll_numbers[n // 2])\n\nreturn seating_order","test":"METADATA = {\n 'author': 'ay',\n 'dataset': 'test'\n}\n\ndef check(candidate):\n assert candidate(11, [1, 4, 6, 8, 10, 13, 15, 19, 22, 27, 33]) == [1, 33, 4, 27, 6, 22, 8, 19, 10, 15, 13]\n assert candidate(10, [2, 5, 8, 11, 14, 17, 20, 23, 26, 29]) == [2, 29, 5, 26, 8, 23, 11, 20, 14, 17]\n assert candidate(6, [100, 200, 300, 400, 500, 600]) == [100, 600, 200, 500, 300, 400]\n assert candidate(7, [3, 6, 9, 12, 15, 18, 21]) == [3, 21, 6, 18, 9, 15, 12]"} { "task_id": "PythonSaga/60","prompt":"from typing import List, Tuple\n\ndef bead_remove(bead_count: int, bead_numbers: List[int], remove_beads: List[int]) -> Tuple[List[int], int, int]:\n \"\"\"My aunt has favourite bracelets where each bead points to next bead. But it's getting loose for her. So she decided to remove some beads from end. \n Each bead has a number on it. She wants to remove beeds with numbers in decreasing order. \n Write a program to help her to remove beads from end, imagine bracelet as a linked list where last bead is connected to first bead. \n Take input from user for number of beads and numbers on each bead, and Which bead she wants to remove. Use linked list to solve this problem. \n Return the linked list after removing beads and the first and last bead number.\n Example: \n Input: 11,[1,2,3,4,5,6,7,8,9,10,11],[5,10,11]\n Output: [1,2,3,4,6,7,8,9], 1, 9\n Input: 10,[1,2,3,4,5,6,7,8,9,10],[2,4,6,8,10]\n Output: [1,3,5,7,9], 1, 9\"\"\"","entry_point":"bead_remove","canonical_solution":"from typing import List, Tuple\n\nclass BeadNode:\n def __init__(self, number):\n self.number = number\n self.next = None\n\ndef bead_remove(bead_count: int, bead_numbers: List[int], remove_beads: List[int]) -> Tuple[List[int], int, int]:\n # Create a linked list from the input bead_numbers\n beads = None\n current = None\n for number in reversed(bead_numbers):\n node = BeadNode(number)\n node.next = current\n current = node\n beads = current\n\n # Iterate through the linked list to remove beads specified in remove_beads\n current = beads\n prev = None\n while current:\n if current.number in remove_beads:\n if prev:\n prev.next = current.next\n else:\n beads = current.next\n else:\n prev = current\n current = current.next\n\n # Find the first and last bead number\n current = beads\n first_bead = last_bead = None\n while current:\n if first_bead is None:\n first_bead = current.number\n last_bead = current.number\n current = current.next\n\n # Convert linked list to list\n result = []\n current = beads\n while current:\n result.append(current.number)\n current = current.next\n\n return result, first_bead, last_bead","test":"METADATA = {\n 'author': 'ay',\n 'dataset': 'test'\n}\n\n\ndef check(candidate):\n input1 = (11, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11], [5, 10, 11])\n output1 = candidate(*input1)\n assert output1 == ([1, 2, 3, 4, 6, 7, 8, 9], 1, 9)\n\n input2 = (10, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], [2, 4, 6, 8, 10])\n output2 = candidate(*input2)\n assert output2 == ([1, 3, 5, 7, 9], 1, 9)\n\n input3 = (8, [10, 20, 30, 40, 50, 60, 70, 80], [20, 50, 60, 70, 80])\n output3 = candidate(*input3)\n assert output3 == ([10, 30, 40], 10, 40)\n\n input4 = (6, [5, 10, 15, 20, 25, 30], [10, 20, 25])\n output4 = candidate(*input4)\n assert output4 == ([5, 15, 30], 5, 30)"} { "task_id": "PythonSaga/61","prompt":"from typing import List\ndef chemistry_ele(elements: List[str], i: int, j: int) -> List[str]:\n \"\"\"I have some chemistry experiments to do where I have long chain of different elements. \n Each element is linked with next and previous element. To do next experiment I want to reverse some portion of chain. \n So take Input from user as a string of elements and reverse the portion of chain from index i to j. \n Use doubly linked list to implement this. \n Example: \n\n Input: [O, K, H, Li, Be, B, C, N, O, F, Ne] ,2, 4\n Output: [O, k, Be, Li, H, B, C, N, O, F, Ne]\n\n Input: [O, K, H, Li, Be, B, C, N, O, F, Ne] ,0, 3\n Output: [Li, H, K, O, Be, B, C, N, O, F, Ne]\"\"\"\n","entry_point":"chemistry_ele","canonical_solution":"","test":"METADATA = {\n 'author': 'ay',\n 'dataset': 'test'\n}\n\n\ndef check(candidate):\n input1 = (['O', 'K', 'H', 'Li', 'Be', 'B', 'C', 'N', 'O', 'F', 'Ne'], 2, 4)\n output1 = candidate(*input1)\n assert output1 == ['O', 'K', 'Be', 'Li', 'H', 'B', 'C', 'N', 'O', 'F', 'Ne']\n\n input2 = (['O', 'K', 'H', 'Li', 'Be', 'B', 'C', 'N', 'O', 'F', 'Ne'], 0, 3)\n output2 = candidate(*input2)\n assert output2 == ['Li', 'H', 'K', 'O', 'Be', 'B', 'C', 'N', 'O', 'F', 'Ne']\n\n input3 = (['Na', 'Mg', 'Al', 'Si', 'P', 'S', 'Cl', 'Ar'], 1, 5)\n output3 = candidate(*input3)\n assert output3 == ['Na', 'S', 'P', 'Si', 'Al', 'Mg', 'Cl', 'Ar']\n\n input4 = (['H', 'He', 'Li', 'Be', 'B', 'C', 'N', 'O', 'F', 'Ne'], 3, 8)\n output4 = candidate(*input4)\n assert output4 == ['H', 'He', 'Li', 'F', 'O', 'N', 'C', 'B', 'Be', 'Ne']"} { "task_id": "PythonSaga/62","prompt":"from typing import List\n\ndef eight_shape(garland1: List[str], garland2: List[str], common_bead: str) -> List[str]:\n \"\"\"I have 2 garlands of beads of different sizes. each bead has different alphabets on it. and no two bead has same alphabet in any garland only one bead is common. \n I want to be creative because i'm bored. I want to create figure like digit 8 such that there is a bead in the middle of the figure and \n the figure is made up of beads from both the garlands. \n Also when i read alphabet I start from common bead and them move in upper garland in anti-clockwise and then come back to commmon bead and move to \n lower garland and then move in clockwise manner and come back to common bead. In this was I will read common bead thrice. \n So take input from user as alphabets on beads of both garlands, common bead and print alphabets in order mentioned above. \n Use Linked List to solve this problem. \n Example: \n Input: [A, B, C, D, E, F, G, H], [I, J, K, B, L, M], B\n Output: [B, C, D, E, F, G, H, A, B, L, M, I, J, K, B]\"\"\"\n","entry_point":"eight_shape","canonical_solution":"","test":"METADATA = {'author': 'ay', 'dataset': 'test'}\n\ndef check(candidate):\n input1 = (['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'], ['I', 'J', 'K', 'B', 'L', 'M'], 'B')\n output1 = candidate(*input1)\n assert output1 == ['B', 'C', 'D', 'E', 'F', 'G', 'H', 'A', 'B', 'L', 'M', 'I', 'J', 'K', 'B']\n\n input2 = (['X', 'Y', 'Z'], ['A', 'B', 'C', 'X'], 'X')\n output2 = candidate(*input2)\n assert output2 == ['X', 'Y', 'Z', 'X', 'A', 'B', 'C', 'X']\n\n input3 = (['1', '2', '3', '4'], ['9', '10', '2', '11', '12'], '2')\n output3 = candidate(*input3)\n assert output3 == ['2', '3', '4', '1', '2', '11', '12', '9', '10', '2']"} { "task_id": "PythonSaga/63","prompt":"from typing import List\n\ndef subset_linked_list(arr: List[float], threshold: float) -> List[List[int]]:\n \"\"\"I have circular linked list of some numbers. My teacher gave me one number and asked to find all possible subset of digits \n from the circular linked list whose sum is greater than the given number. \n Take linked list as input from user and print all possible subsets whose sum is greater than the given number. \n Example: \n Input: [1,2,3,1], 3\n Output: [[1, 2, 3, 1], [1, 2, 3], [1, 2, 1], [1, 3, 1], [1, 3], [2, 3, 1], [2, 3], [3, 1]]\n Input: [1,2,3,1], 4\n Output: [[1, 2, 3, 1], [1, 2, 3], [1, 3, 1], [2, 3, 1], [2, 3]]\"\"\"\n","entry_point":"subset_linked_list","canonical_solution":"","test":"METADATA = {'author': 'ay', 'dataset': 'test'}\n\ndef check(candidate):\n input1 = [1, 2, 3, 1]\n threshold1 = 3\n output1 = candidate(input1, threshold1)\n assert output1 == [[1, 2, 3, 1], [1, 2, 3], [1, 2, 1], [1, 3, 1], [1, 3], [2, 3, 1], [2, 3], [3, 1]]\n\n input2 = [1, 2, 3, 1]\n threshold2 = 4\n output2 = candidate(input2, threshold2)\n assert output2 == [[1, 2, 3, 1], [1, 2, 3], [1, 3, 1], [2, 3, 1], [2, 3]]\n\n input3 = [4, 2, 7, 3]\n threshold3 = 9\n output3 = candidate(input3, threshold3)\n assert output3 == [[4, 2, 7, 3], [4, 2, 7], [4, 7, 3], [4, 7], [2, 7, 3], [7, 3]]\n \n input4 = [10, 5, 2, 8, 7]\n threshold4 = 15\n output4 = candidate(input4, threshold4)\n assert output4 == [[10, 5, 2, 8, 7], [10, 5, 2, 8], [10, 5, 2, 7], [10, 5, 2], [10, 5, 8, 7], [10, 5, 8], [10, 5, 7], [10, 2, 8, 7], [10, 2, 8], [10, 2, 7], [10, 8, 7], [10, 8], [10, 7], [5, 2, 8, 7], [5, 8, 7], [2, 8, 7]]"} { "task_id": "PythonSaga/64","prompt":"from typing import List\n\ndef plaindrom(arr: List[str]) -> List[str]:\n \"\"\"I have a circular doubly linked list of alphabets. \n Write a program to check if these alphabets form a palindrome and print the word. \n Use the doubly linked list created in the previous question. \n Take the input from the user. and return the output as Palindrome or Not a Palindrome and the word.\n Example: \n Input: [A, D, A, R]\n Output: ['Palindrome', 'The word is RADAR']\n Input: [T, I, N, N, I]\n Output: ['Palindrome', 'The word is NITIN']\n Input: [H, E, L, L, O]\n Output: ['Not a Palindrome', 'The list does not form a palindrome word.']\"\"\"\n","entry_point":"plaindrom","canonical_solution":"","test":"METADATA = {'author': 'ay', 'dataset': 'test'}\n\ndef check(candidate):\n input1 = ['A', 'D', 'A', 'R']\n output1 = candidate(input1)\n assert output1 == ['Palindrome', 'The word is RADAR']\n\n input2 = ['T', 'I', 'N', 'N', 'I']\n output2 = candidate(input2)\n assert output2 == ['Palindrome', 'The word is NITIN']\n\n input3 = ['H', 'E', 'L', 'L', 'O']\n output3 = candidate(input3)\n assert output3 == ['Not a Palindrome', 'The list does not form a palindrome word.']\n\n input4 = ['R', 'E', 'V', 'E']\n output4 = candidate(input4)\n assert output4 == ['Palindrome', 'The word is REVER']"} { "task_id": "PythonSaga/65","prompt":"from queue import Queue\nfrom typing import List\n\ndef stack_using_queue(operations: List[List[int]]) -> List[List[int]]:\n \"\"\"We can implement stack using list. But my uncle told we can also using two queues. \n So, please help me to implement stack using queue. \n Take input from user in form of what operation he wants to perform. \n 1. Push \n 2. Pop \n 3. Display \n\n Example:\n Input: [[1, 1], [1, 2], [1, 3], [3]]\n Output: [[3, 2, 1]]\n Input: [[1, 1], [1, 2], [3], [2], [3]]\n Output: [[2, 1],[1]]\"\"\"\n","entry_point":"stack_using_queue","canonical_solution":"class StackUsingQueues:\n def __init__(self):\n self.main_queue = Queue()\n self.aux_queue = Queue()\n\n def push(self, x: int):\n self.main_queue.put(x)\n\n def pop(self):\n if self.main_queue.empty():\n return \"Stack is empty\"\n \n # Move all elements except the last one to the auxiliary queue\n while self.main_queue.qsize() > 1:\n self.aux_queue.put(self.main_queue.get())\n \n # The last element in the main queue is the top of the stack\n top_element = self.main_queue.get()\n \n # Swap the roles of the main queue and the auxiliary queue\n self.main_queue, self.aux_queue = self.aux_queue, self.main_queue\n \n return top_element\n\n def display(self):\n stack_representation = []\n # Transfer elements to auxiliary queue and build stack representation\n while not self.main_queue.empty():\n element = self.main_queue.get()\n stack_representation.append(element)\n self.aux_queue.put(element)\n \n # Transfer elements back to the main queue\n while not self.aux_queue.empty():\n self.main_queue.put(self.aux_queue.get())\n \n return stack_representation[::-1] # Reverse to represent the stack order\n\ndef stack_using_queue(operations: List[List[int]]) -> List[List[int]]:\n stack = StackUsingQueues()\n result = []\n\n for operation in operations:\n if operation[0] == 1: # Push operation\n stack.push(operation[1])\n elif operation[0] == 2: # Pop operation\n stack.pop()\n elif operation[0] == 3: # Display operation\n result.append(stack.display())\n\n return result","test":"METADATA = {'author': 'ay', 'dataset': 'test'}\n\ndef check(candidate):\n assert candidate([[1, 1], [1, 2], [1, 3], [3]]) == [[3, 2, 1]]\n assert candidate([[1, 1], [1, 2], [3], [2], [3]]) == [[2, 1], [1]]\n assert candidate([[1, 5], [1, 10], [1, 15], [2], [3]]) == [[10, 5]]\n assert candidate([[1, 3], [1, 6],[3], [2], [1, 9], [3]]) == [[6, 3], [9, 3]]"} { "task_id": "PythonSaga/66","prompt":"from typing import List\n\ndef skyline(street: List[int]) -> int:\n \"\"\"Imagine you have a city skyline represented by an array of skyscraper heights. The heights are given in the array street[]. \n The task is to determine how much sunlight can be captured between the buildings when the sun is at its peak. \n Take street[] as input from the user. \n Print the total sunlight that can be captured between the buildings. \n Example: \n Input: [4, 0, 4]\n Output: 4\n Input: [3, 4, 3, 5, 4, 3, 4, 6, 5, 4, 5, 4]\n Output: 6\"\"\"\n","entry_point":"skyline","canonical_solution":"total_sunlight = 0\nn = len(street)\n\n# Arrays to store the maximum height to the left and right of each building\nleft_max = [0] * n\nright_max = [0] * n\n\n# Fill left_max array\nleft_max[0] = street[0]\nfor i in range(1, n):\n left_max[i] = max(left_max[i-1], street[i])\n\n# Fill right_max array\nright_max[n-1] = street[n-1]\nfor i in range(n-2, -1, -1):\n right_max[i] = max(right_max[i+1], street[i])\n\n# Calculate total sunlight captured\nfor i in range(n):\n # Sunlight on current building is the difference between its height and the height of the shadow\ncast by the taller buildings on its left or right, whichever is shorter.\n total_sunlight += min(left_max[i], right_max[i]) - street[i]\n\nreturn total_sunlight","test":"METADATA = {'author': 'ay', 'dataset': 'test'}\n\ndef check(candidate):\n assert candidate([4, 0, 4]) == 4\n assert candidate([3, 4, 3, 5, 4, 3, 4, 6, 5, 4, 5, 4]) == 9\n assert candidate([1, 2, 3, 4, 5]) == 0\n assert candidate([10, 5, 15, 2, 8, 12, 7]) == 19"} { "task_id": "PythonSaga/67","prompt":"from typing import List\n\ndef deck(queries: List[List[str]]) -> List[int]:\n \"\"\"You have been given a special deck, represented as a double-ended queue (deque), \n and a set of queries to perform operations on this deck. The deck supports four types of operations: \n 1. Insert at Rear (ins_rear x): Use the 'Insert Rear' operation to add data x to the rear of the deck. \n 2. Insert at Front (ins_fr x): Use the 'Insert Front' operation to add data x to the front of the deck. \n 3. Delete Front (del_fr): Use the 'Delete Front' operation to remove the front element from the deck. If the deck is empty, no action is taken. \n 4. Delete Rear (del_rear): Use the 'Delete Rear' operation to remove the rear element from the deck. If the deck is empty, no action is taken. \n Take input from the user; the number of queries, and the queries themselves, and print the output for each query and final deck. \n Implement the above deque using a doubly linked list. \n\n Example: \n\n Input: [['ins_rear', 5], ['ins_fr', 10], ['del_fr'], ['del_rear'], ['ins_fr', 15], ['ins_rear', 20]]\n Output: [15, 20]\"\"\"\n","entry_point":"deck","canonical_solution":"class Node:\n def __init__(self, value):\n self.value = value\n self.next = None\n self.prev = None\n\nclass Deck:\n def __init__(self):\n self.front = None\n self.rear = None\n\n def ins_rear(self, x):\n new_node = Node(x)\n if not self.rear: # Empty deck\n self.front = self.rear = new_node\n else:\n self.rear.next = new_node\n new_node.prev = self.rear\n self.rear = new_node\n\n def ins_fr(self, x):\n new_node = Node(x)\n if not self.front: # Empty deck\n self.front = self.rear = new_node\n else:\n self.front.prev = new_node\n new_node.next = self.front\n self.front = new_node\n\n def del_fr(self):\n if self.front:\n if self.front == self.rear: # Only one element\n self.front = self.rear = None\n else:\n self.front = self.front.next\n self.front.prev = None\n\n def del_rear(self):\n if self.rear:\n if self.front == self.rear: # Only one element\n self.front = self.rear = None\n else:\n self.rear = self.rear.prev\n self.rear.next = None\n\n def get_deck(self):\n current = self.front\n result = []\n while current:\n result.append(current.value)\n current = current.next\n return result\n\ndef deck(queries: List[List[str]]) -> List[int]:\n d = Deck()\n for query in queries:\n operation, *args = query\n if operation == \"ins_rear\":\n d.ins_rear(*args)\n elif operation == \"ins_fr\":\n d.ins_fr(*args)\n elif operation == \"del_fr\":\n d.del_fr()\n elif operation == \"del_rear\":\n d.del_rear()\n return d.get_deck()","test":"METADATA = {'author': 'ay', 'dataset': 'test'}\n\ndef check(candidate):\n assert candidate([['ins_rear', 5], ['ins_fr', 10], ['del_fr'], ['del_rear'], ['ins_fr', 15], ['ins_rear', 20]]) == [15, 20]\n assert candidate([['ins_rear', 1], ['ins_rear', 2], ['ins_rear', 3], ['del_fr'], ['ins_fr', 4], ['del_rear']]) == [4, 2]\n assert candidate([['ins_rear', 10], ['ins_fr', 5], ['del_fr'], ['ins_rear', 15], ['del_rear']]) == [10]\n assert candidate([['ins_rear', 5], ['ins_fr', 3], ['ins_rear', 8], ['ins_fr', 2], ['del_rear'], ['del_fr']]) == [3, 5]"} { "task_id": "PythonSaga/68","prompt":"from collections import deque\nfrom typing import List\n\ndef delete_element(deque: List[int], index: int) -> List[int]:\n \"\"\"I came to know that I can implement deque using collections module. \n But now I want to learn how to delete elements from deque. \n Write 4 functions to delete elements from deque. \n 1. to remove element from a specific index \n 2. to remove element in a range of index, start (inclusive) to end (exclusive). \n 3. to remove element from both ends. \n 4. to remove all elements from deque. \n Take input from the user to create deque and a set of operations to perform on deque. Return deque after performing all operations. \n EXAMPLE:\n Input: [1, 2, 3, 4, 5],[3]\n Output: [2, 3, 4]\n Input: [1, 2, 3, 4, 5],[4]\n Output: []\n Input: [1, 2, 3, 4, 5],[2,1,3] # 2 is action code for remove element in range, 1 is start index and 3 is end index\n Output: [1, 4, 5]\"\"\"\n","entry_point":"delete_element","canonical_solution":"","test":"METADATA = {'author': 'ay', 'dataset': 'test'}\n\ndef check(candidate):\n assert candidate([1, 2, 3, 4, 5], [3]) == [2, 3, 4]\n assert candidate([1, 2, 3, 4, 5], [4]) == []\n assert candidate([1, 2, 3, 4, 5], [2, 1, 3]) == [1, 4, 5]\n assert candidate([10, 20, 30, 40, 50], [1]) == [10, 20, 40, 50]"} { "task_id": "PythonSaga/69","prompt":"from collections import deque\nfrom typing import List\n\ndef office_party(n:int, snacks_preference:List[List[str]]) -> int:\n \"\"\"Imagine an office party scenario where there are n people in the office, and an equal number of food packets are available. \n The food packets come in two types: French fries (represented by '|') and pizza (represented by '*'). \n All employees form a queue, and the food packets are stacked on a table. At each step, the person at the front of the queue \n has the option to take the top food packet from the stack. The preferences of the individuals are as follows: \n If a person prefers the food type on the top of the stack, they take it and leave the queue. \n If the person does not prefer the food type on the top of the stack, they leave it and move to the end of the queue. \n This process continues until none of the people in the queue want to take the top food packet, and they become unable to eat. \n You are given two arrays, employees and foodPackets, where foodPackets[i] is the type of the i​​​​th food packet on the \n table (i = 0 is the top of the stack), and employees[j] is the preference of the j​​​​​​th person in the initial queue \n (j = 0 is the front of the queue). Your task is to determine the number of people who are unable to eat. \n Take input from the user for the number of employees and food packets. \n Take foodpackets[] as input from the user. \n Take employees[] as input from the user. \n Example:\n Input: 4,[['*', '|', '*', '|'],['|', '|', '*', '*']] # 4 is the number of employees, [['*', '|', '*', '|'],['|', '|', '*', '*']] is food packets and food preference of employees\n Output: 0\n Input: 6,[['|', '|', '|', '*', '*', '|'],['|', '*', '*', '*', '|', '|']] # 6 is the number of employees, [['|', '|', '|', '*', '*', '|'],['|', '*', '*', '*', '|', '|']] is food packets and food preference of employees\n Output: 3\"\"\"\n","entry_point":"office_party","canonical_solution":"","test":"METADATA = {'author': 'ay', 'dataset': 'test'}\n\ndef check(candidate):\n assert candidate(4, [['*', '|', '*', '|'], ['|', '|', '*', '*']]) == 0\n assert candidate(6, [['|', '|', '|', '*', '*', '|'], ['|', '*', '*', '*', '|', '|']]) == 3"} { "task_id": "PythonSaga/70","prompt":"import re\n\nfrom typing import List\n\ndef mobile_number(text: str) -> List[str]:\n \"\"\"I have a paragraph which contain lots of phone numbers and different numbers.\n\nyour task is to use regular expression to extract all the phone numbers and numbers from the paragraph.\n\nTake a paragraph as input from the user and print all the phone numbers and numbers from the paragraph.\n\nExample:\n\nInput: \"Hello my Number is 12304589 and my friend's number is 987654321\"\n\nOutput: [\"12304589\", \"987654321\"]\"\"\"","entry_point":"mobile_number","canonical_solution":"pattern = r'\\d+' # Regular expression pattern to match numbers\nnumbers = re.findall(pattern, text) # Find all matches of numbers in the text\nreturn numbers","test":"METADATA = {\n\n'author': 'ay',\n\n'dataset': 'test'\n\n}\n\n\n\n\n\ndef check(candidate):\n\n assert candidate(\"Hello my Number is 12304589 and my friend's number is 987654321\") == ['12304589', '987654321']\n\n assert candidate(\"No numbers in this text\") == []\n\n assert candidate(\"123on456 789\") == ['123', '456', '789']\n\n assert candidate(\"The quick brown fox jumps over the lazy dog\") == []"} { "task_id": "PythonSaga/71","prompt":"import re\n\ndef space_needed(text: str) -> str:\n \"\"\"I was distracted while typing my assignment and forgot to put space after words.\n\nRead a paragragraph and add space before every word which starts with capital letter.\n\nAnd also if it is a number, add \":\" followed by space before number.\n\nTake input from user and print the output.\n\nExample:\n\nInput: \"IamStudyingInBdsfrom24hrs.\"\n\nOutput: \"Iam Studying In Bdsfrom: 24hrs.\"\n\nInput: \"ThisIsMyFirstAssignmentof22ndBatch.\"\n\nOutput: \"This Is My First Assignmentof: 22nd Batch.\"\"\"\"","entry_point":"space_needed","canonical_solution":"# Add space before words starting with a capital letter\ntext_with_spaces = re.sub(r\"(? str:\n \"\"\"I met an accountant who has some text material in which he has days and dates.\n\nBut now to coap up with the new technology he wants to convert all the dates into a standard format.\n\nThe standard format is DD-MM-YYYY. But the problem is dates in his text is in 2 different format.\n\n1. YYYY-MM-DD and 2. DD-YYYY-MM. So you have to convert all the dates into standard format.\n\nAnd also if day is return in abbrivation [Mon, Tue, Wed, Thu, Fri, Sat, Sun] then you have to convert\n\nit into full form [Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday].\n\nTake a text as input and return the text with all the dates and days in standard format.\n\nExample:\n\n\n\nInput: \"On 2023-01-15, we had a meeting.\n\nThe financial report for the month was presented.\n\nOn Thu, 2023-01-18, the board discussed the budget.\n\n2023-02-20 is the deadline for submitting expense reports.\n\nPlease submit them by then. We also have a meeting scheduled for Wed, 2023-03-22. \"\n\n\n\nOutput: \"On 15-01-2023, we had a meeting.\n\nThe financial report for the month was presented.\n\nOn Thursday, 18-01-2023, the board discussed the budget.\n\n20-02-2023 is the deadline for submitting expense reports.\n\nPlease submit them by then. We also have a meeting scheduled for Wednesday, 22-03-2023. \"\n\"\"\"\n", "entry_point":"date_format","canonical_solution":"text = re.sub(r\"(\\d{4})-(\\d{2})-(\\d{2})\", r\"\\3-\\2-\\1\", text)\ntext = re.sub(r\"(\\d{2})-(\\d{4})-(\\d{2})\", r\"\\1-\\3-\\2\", text)\n\ndays_dict = {\n \"Mon\": \"Monday\",\n \"Tue\": \"Tuesday\", \n \"Wed\": \"Wednesday\",\n \"Thu\": \"Thursday\",\n \"Fri\": \"Friday\",\n \"Sat\": \"Saturday\",\n \"Sun\": \"Sunday\"\n}\nfor day in days_dict:\n text = text.replace(day, days_dict[day])\n \nreturn text","test":"METADATA = {\n\n'author': 'ay',\n\n'dataset': 'test'\n\n}\n\n\n\n\ndef check(candidate):\n\n text1 = \"On 2023-01-15, we had a meeting. The financial report for the month was presented.\"\n expected1 = \"On 15-01-2023, we had a meeting. The financial report for the month was presented.\"\n assert candidate(text1) == expected1\n\n\n text2 = \"On Thu, 2023-01-18, the board discussed the budget. 2023-02-20 is the deadline for submitting expense reports.\"\n expected2 = \"On Thursday, 18-01-2023, the board discussed the budget. 20-02-2023 is the deadline for submitting expense reports.\"\n assert candidate(text2) == expected2\n\n\n text3 = \"Please submit them by then. We also have a meeting scheduled for Wed, 2023-03-22.\"\n expected3 = \"Please submit them by then. We also have a meeting scheduled for Wednesday, 22-03-2023.\"\n assert candidate(text3) == expected3\n\n\n text4 = \"The last date for registration is 15-2023-02. Classes will start from 01-2023-06.\"\n expected4 = \"The last date for registration is 15-02-2023. Classes will start from 01-06-2023.\"\n assert candidate(text4) == expected4"} { "task_id": "PythonSaga/73","prompt":"from typing import List, Tuple\n\ndef vowels(text: str) -> Tuple[bool, List[List[str]]]:\n \"\"\"Write a Python program that takes a string with some words. For two consecutive words in the string,\n\ncheck whether the first word ends with a vowel and the next word begins with a vowel.\n\nIf the program meets the condition, return true, otherwise false. Only one space is allowed between the words.\n\nTake input from user and return true if the condition is met, otherwise false, also return two words which met the condition\n\nExample:\n\nInput: \"Python PHP\"\n\nOutput: (False, [])\n\nInput: \"These exercises can be used for practice.\"\n\nOutput: (True, [['These','exercises'], ['be', 'used']])\"\"\"", "entry_point":"vowels","canonical_solution":"text = text.lower()\nwords = text.split(\" \")\nvowels = \"aeiou\"\nresult = []\n\nfor i in range(len(words)-1):\n word1 = words[i]\n word2 = words[i+1]\n \n if word1[-1] in vowels and word2[0] in vowels:\n result.append([word1, word2])\n\nif result:\n return True, result\nelse:\n return False, []","test":"METADATA = {\n\n'author': 'ay',\n\n'dataset': 'test'\n\n}\n\n\n\n\ndef test(candidate):\n\n text1 = \"Python PHP\"\n expected_output1 = (False, [])\n assert candidate(text1) == expected_output1\n\n\n text2 = \"These exercises can be used for practice.\"\n expected_output2 = (True, [['These','exercises'], ['be', 'used']])\n assert candidate(text2) == expected_output2\n\n\n text3 = \"cats and dogs are common pets\"\n expected_output3 = (False, [])\n assert candidate(text3) == expected_output3\n\n\n text4 = \"abcde efgh hijkl mnopq rstu vwxyz\"\n expected_output4 = (True, [['abcde', 'efgh']])\n assert candidate(text4) == expected_output4"} { "task_id": "PythonSaga/74","prompt":"import re\n\ndef find_urls(text: str) -> str:\n \"\"\"My boss gave me work to find all the urls in the given text and print them.\n\nWrite a code which take text as input from user and print all the urls in the text.\n\nNote: url should start with https:// or http:// and can end with any thing like .com, .in, .org etc. where there is \".\" before the ending part.\n\nBut if url is not ending properly then it should not print that url.\n\n\n\nExample:\n\n\n\nInput:\"Check out the latest news on https://www.example.com. You can also visit our blog at http://bloexample for more information.\"\n\nOutput: \"https://www.example.com \"\n\nInput:\"For more details, visit https://www.example.com and http://test.com\"\n\nOutput: \"https://www.example.com, http://test.com\"\n\n\"\"\"", "entry_point":"find_urls","canonical_solution":"urls = re.findall(r'(https?://[^ ]*)\\.', text)\nreturn ' '.join(urls)","test":"METADATA = {\n\n'author': 'ay',\n\n'dataset': 'test'\n\n}\n\n\n\n\ndef test(candidate):\n\n text1 = \"For more details, visit https://www.example.com and http://test.com\"\n expected_output1 = \"https://www.example.com, http://test.com\"\n assert candidate(text1) == expected_output1\n\n\n text2 = \"You can find us at https://www.mywebsite.com or http://127\"\n expected_output2 = \"https://www.mywebsite.com\"\n assert candidate(text2) == expected_output2\n\n\n text3 = \"Visit https://test.org or http://test.com.\"\n expected_output3 = \"https://test.org, http://test.com\"\n assert candidate(text3) == expected_output3\n\n\n text4 = \"No urls to find in this text\"\n expected_output4 = \"\"\n assert candidate(text4) == expected_output4"} { "task_id": "PythonSaga/75","prompt":"from collections import defaultdict\nfrom typing import List, Dict\ndef hash_table(seq:List)-> Dict:\n\"\"\"In local school games students who won there names were noted in sequence of there winning\nBut if person won more than once his name will be repeated in sequence so that he can be declared as man of the match\nTake input from user and print the name of the person who won maximum number of times followed by the number of times he won followed by second person and so on.\nYou can use hash table to solve this problem\nExample:\nInput: [A,B,C,A,B,A,Z,A,A,F,S,S,C,F,S,A]\nOutput: {'A':6, 'S':3, 'F':2, 'C':2, 'B':2, 'Z':1}\"\"\"\n", "entry_point":"hash_table","canonical_solution":"table = defaultdict(int)\n\nfor name in seq:\n table[name] += 1\n \nsorted_table = dict(sorted(table.items(), key=lambda x: x[1], reverse=True))\nreturn sorted_table","test":"METADATA = {\n'author': 'ay',\n'dataset': 'test'\n}\n\n\ndef check(candidate):\n assert candidate(['X', 'Y', 'Z', 'X', 'X', 'Z']) == {'X': 3, 'Z': 2, 'Y': 1}\n assert candidate(['A', 'A', 'A', 'A', 'A', 'A']) == {'A': 6}\n assert candidate(['Dog', 'Cat', 'Bird', 'Dog', 'Cat', 'Dog']) == {'Dog': 3, 'Cat': 2, 'Bird': 1}\n"} { "task_id": "PythonSaga/76","prompt":"from typing import List, Tuple, Optional\ndef hash_function(n:int, entries:List[List[str,int]]) -> List:\n\"\"\"My teacher taught us hashing in class today and its advanced version that is open addressing.\nHe gave us task to implement it in python. With following functions:\n1. Insert\n2. Search\n3. Delete\n4. Display\nTake input from user about the size of hash table and and action to perform otherwise exit.\n\nExample:\n\nInput: 5,[[insert,5],[insert,10],[insert,15],[display],[search,10],[delete,10],[display]]\nOutput: [[5,10,15,None,None], 1,[5,None,15,None,None]]\"\"\"\n", "entry_point":"hash_function","canonical_solution":"from typing import List, Tuple, Optional\n\nclass HashTable:\n def __init__(self, size: int):\n self.size = size\n self.table = [None] * size\n\n def hash(self, key: int) -> int:\n return key % self.size\n\n def insert(self, key: int):\n index = self.hash(key)\n while self.table[index] is not None:\n index = (index + 1) % self.size\n self.table[index] = key\n\n def search(self, key: int) -> bool:\n index = self.hash(key)\n start_index = index\n while self.table[index] is not None:\n if self.table[index] == key:\n return True\n index = (index + 1) % self.size\n if index == start_index:\n break\n return False\n\n def delete(self, key: int):\n index = self.hash(key)\n start_index = index\n while self.table[index] is not None:\n if self.table[index] == key:\n self.table[index] = None\n return True\n index = (index + 1) % self.size\n if index == start_index:\n break\n return False\n\n def display(self) -> List[Optional[int]]:\n return self.table\n\ndef hash_function(n: int, entries: List[List[str]]) -> List:\n hash_table = HashTable(n)\n result = []\n\n for entry in entries:\n if len(entry) == 1:\n operation = entry[0]\n else:\n operation, value = entry\n\n if operation == 'insert':\n hash_table.insert(value)\n elif operation == 'delete':\n hash_table.delete(value)\n elif operation == 'search':\n found = hash_table.search(value)\n result.append(1 if found else 0)\n elif operation == 'display':\n result.append(hash_table.display())\n\n return result","test":"METADATA = {\n'author': 'ay',\n'dataset': 'test'\n}\n\n\ndef check(candidate):\n assert candidate(3, [['insert', 1], ['insert', 4], ['display']]) == [[None, 1, 4]]\n assert candidate(5, [['insert', 10], ['insert', 20], ['insert', 30], ['search', 20]]) == [1]\n assert candidate(4, [['insert', 8], ['insert', 12], ['delete', 8], ['display']]) == [[None, 12, None, None]]\n assert candidate(6, [['insert', 11], ['insert', 22], ['insert', 33], ['delete', 22], ['search', 22], ['display']]) == [-1, [None, None, None, 33, None, 11]]\n"} { "task_id": "PythonSaga/77","prompt":"from typing import List, Tuple, Optional\ndef sum_pair(entries:List[int], target:int) -> List[Tuple[int,int]]:\n\"\"\"I have very simple problem that I'm unable to solve and need your help in.\nI have a number and I want to know is there any pair of numbers in the list whose sum is equal to the given number.\nBut the twist is I have to do it using hashing.\nTake list of numbers from user and the number to be checked and return the pair of numbers whose sum is equal to the given number otherwise return -1.\nExample:\nInput: [1,2,3,4,5,6,7,8,9,10],11\nOutput: [(1,10), (2,9) ,(3,8), (4,7), (5,6) ]\n\nExample:\nInput: [-1,33,2,-33,99,101,-2,0],0\nOutput: [(-33,33), (-2,2)]\n\"\"\"\n", "entry_point":"sum_pair","canonical_solution":"seen = set()\npairs = set()\n\nfor number in entries:\n complement = target - number\n if complement in seen:\n pairs.add((min(number, complement), max(number, complement)))\n seen.add(number)\n\nif not pairs:\n return -1\n\nreturn list(pairs)","test":"METADATA = {\n'author': 'ay',\n'dataset': 'test'\n}\n\n\ndef check(candidate):\n assert candidate([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 11) == [(1, 10), (2, 9), (3, 8), (4, 7), (5, 6)]\n assert candidate([-1, 33, 2, -33, 99, 101, -2, 0], 0) == [(-33, 33), (-2, 2)]\n assert candidate([10, 20, -10, -20], 0) == [(-20, 20), (-10, 10)]\n assert candidate([1, 3, 5, 7], 10) == []\n"} { "task_id": "PythonSaga/78","prompt":"from typing import List, Optional\ndef balanced_substring(string:str, k:int) -> List[str]:\n\"\"\"My teacher said we have to find balanced subtrings in a string.\nA string is balanced if:\n1. Number of vowels and consonants are equal\n2. ((Number of vowels)*(Number of consonants))%k == 0\nYou can use hashing to solve this problem.\nTake input of string and k from user and return balanced substrings if any else return empty list.\n\nExample:\n\nInput: string = \"xioyz\", k = 2\nOutput: ['ioyz', 'xioy']\nInput: string = \"ixxi\", k=1\nOutput: ['ixxi', 'ix', 'xi']\"\"\"\n", "entry_point":"balanced_substring", "canonical_solution":"vowels = set('aeiouAEIOU')\nresult = []\n\nfor i in range(len(string)):\n for j in range(i+1, len(string) + 1):\n substring = string[i:j]\n vowel_count = sum(1 for char in substring if char in vowels)\n consonant_count = len(substring) - vowel_count\n\n if vowel_count == consonant_count and (vowel_count * consonant_count) % k == 0:\n result.append(substring)\n\nreturn result if result else -1","test":"METADATA = {\n'author': 'ay',\n'dataset': 'test'\n}\n\n\ndef check(candidate):\n assert candidate(\"xioyz\", 2) == ['xioy', 'ioyz']\n assert candidate(\"ixxi\", 1) == ['ix', 'ixxi', 'xi']\n assert candidate(\"abcde\", 3) == []\n"} { "task_id": "PythonSaga/79","prompt":"from typing import List\ndef minTime(val: List[int]) -> int:\n \"\"\"At each unit of time, we perform the following operation on the list\n For every index i in the range [0, n - 1], replace val[i] with either val[i], val[(i - 1 + n) % n], or val[(i + 1) % n].\n Note that all the elements get replaced simultaneously.\n Return the minimum number of units of times we need to make all elements in the list val equal.\n Take input of list from user and print the minimum number of units of times we need to make all elements in the list val equal.\n Example 1 \n Input: [1,2,1,2]\n Output: 1\n Input: [2,1,3,3,2]\n Output: 2\n Input: [3,3,3,3]\n Output: 0\"\"\" ","entry_point":"minTime","canonical_solution":"# Check if all elements are equal\nif len(set(val)) == 1:\n return 0\n\n# Check for an alternating pattern\nif all(val[i] != val[i + 1] for i in range(len(val) - 1)) and val[0] != val[-1]:\n return 1\n\n# Implement logic for the general case\n# Placeholder for the general case logic\n# This part needs a more detailed implementation based on specific rules or patterns\n\n# As a placeholder, return 2 for the general case\n# This needs to be replaced with actual logic\nreturn 2","test":"\nMETADATA = {\n 'author': 'ay',\n 'dataset': 'test'\n}\n\n\ndef check(candidate):\n assert candidate([1, 2, 1, 2]) == 1\n assert candidate([2, 1, 3, 3, 2]) == 2\n assert candidate([3, 3, 3, 3]) == 0"} { "task_id": "PythonSaga/80","prompt":"from typing import List\n\ndef floor_ceil(arr:List, x:int)->List:\n \"\"\"I have a sorted list of numbers and number x and the task given to me is to find the ceil and floor of x in the list. \n The floor of x is the largest number in the list which is smaller than or equal to x, \n and the ceil of x is the smallest number in the list which is greater than or equal to x. \n But the challenge is to solve this problem in O(logn) time complexity. \n Take input list and x from the user and print the floor and ceil of x in the list if any. \n Example: \n Input: [1,2,3,4,5,6,7,8,9,10],11\n Output: [10,None]\n\n Input: [11, 14, 23, 45, 56, 67, 78, 89, 90],11\n Output: [11,11]\"\"\"\n","entry_point":"floor_ceil","canonical_solution":"n = len(arr)\nfloor, ceil = None, None\nlow, high = 0, n - 1\n\nwhile low <= high:\n mid = (low + high) // 2\n\n if arr[mid] == x:\n return [x, x]\n elif arr[mid] < x:\n floor = arr[mid]\n low = mid + 1\n else:\n ceil = arr[mid]\n high = mid - 1\n\nreturn [floor, ceil]","test":"METADATA = {'author': 'ay', 'dataset': 'test'}\n\ndef check(candidate):\n assert candidate([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 11) == [10, None]\n assert candidate([11, 14, 23, 45, 56, 67, 78, 89, 90], 11) == [11, 14]\n assert candidate([1, 2, 8, 10, 10, 12, 19], 5) == [2, 8]\n assert candidate([2, 8, 10, 10, 12, 19], 11) == [10, 12]"} { "task_id": "PythonSaga/81","prompt":"from typing import List\n\ndef chef(box:int, eggs:List, chefs:int)->int:\n \"\"\"In a restaurant, there are N boxes of eggs, each containing a different number of eggs. \n The boxes are arranged in sorted order based on the number of eggs in each box. \n Now, the restaurant has received an order and the owner has to distribute these N boxes among M chefs for breaking the eggs. \n The goal is to assign the boxes to chefs in such a way that the maximum number of eggs assigned to any chef is minimized. \n Each chef is tasked with breaking eggs from a consecutive range of boxes.\n Take input from the user for the number of boxes and the number of eggs in those and the number of chefs.\n Try to do in O(logn) time complexity. \n Example: \n Input: 4,[12,34,67,90],2\n Output: 113\"\"\"\n","entry_point":"chef","canonical_solution":"def chef(box: int, eggs: List[int], chefs: int) -> int:\n def is_valid(mid, eggs, chefs):\n count = 0\n current_sum = 0\n\n for egg in eggs:\n current_sum += egg\n if current_sum > mid:\n count += 1\n current_sum = egg\n\n count += 1 # Include the last batch\n\n return count <= chefs\n\n low, high = max(eggs), sum(eggs)\n result = high\n\n while low <= high:\n mid = (low + high) // 2\n\n if is_valid(mid, eggs, chefs):\n result = mid\n high = mid - 1\n else:\n low = mid + 1\n\n return result","test":"METADATA = {'author': 'ay', 'dataset': 'test'}\n\ndef check(candidate):\n assert candidate(4, [12, 34, 67, 90], 2) == 113\n assert candidate(6, [10, 20, 30, 40, 50, 60], 3) == 90\n assert candidate(5, [5, 10, 15, 20, 25], 2) == 45\n assert candidate(3, [1, 2, 3], 1) == 6"} { "task_id": "PythonSaga/82","prompt":"from typing import List\n\ndef stones(sizes: List[int], target: int) -> List[int]:\n \"\"\"Imagine you are in a store to find stones for your backyard garden.\n The store has an unsorted row of N stones, each labeled with a non-negative integer representing its size.\n Your goal is to select a continuous set of stones (subarray) from this row in such a way that the sum of their sizes matches a given target value S.\n You need to return two elements, left and right,\n representing the indexes of the selected subarray.\n If no such subarray exists, return an array consisting of element [-1].\n Take input from the user for the size of stones in the row and target value S. Try to do it in O(n) time complexity.\n Example 1: # Indexing starts from 1\n Input: [1, 2, 3, 7, 5], 12\n Output: [2, 4] \"\"\"\n","entry_point":"stones","canonical_solution":"left, right = 0, 0\ncurrent_sum = 0\n\nwhile right < len(sizes):\n current_sum += sizes[right]\n\n while current_sum > target:\n current_sum -= sizes[left]\n left += 1\n\n if current_sum == target:\n return [left + 1, right + 1]\n\n right += 1\n\nreturn [-1]","test":"METADATA = {'author': 'ay', 'dataset': 'test'}\n\ndef check(candidate):\n assert candidate([1, 2, 3, 7, 5], 12) == [2, 4]\n assert candidate([10, 2, 3, 1, 7], 15) == [1, 3]\n assert candidate([1, 2, 3, 4, 5], 11) == [-1]"} { "task_id": "PythonSaga/83","prompt":"from typing import List\ndef ride(ages: List) -> int:\n \"\"\"Imagine you are operating a ride for kids at a fair, and each kid is assigned a distinct age. \n The kids are standing in a line, represented by an integer list ages, where the value at each position corresponds to the age of the kid. \n You can perform the following operations until the line is empty: \n If the first kid in the line has the smallest age, let them ride and remove them from the line. \n Otherwise, move the first kid to the end of the line. \n The task is to determine the number of operations it takes to make the line empty, ensuring that kids with the smallest ages get the first priority to ride. \n Take a list ages input from the user and print the number of operations it takes to make the line empty. \n Example 1:\n Input: [3,4,1]\n Output: 5\n Input: [1,2,4,3]\n Output: 5\"\"\"\n","entry_point":"ride","canonical_solution":"sorted_ages = sorted(ages)\noperations = 0\n\nwhile ages:\n if ages[0] == sorted_ages[0]:\n ages.pop(0)\n sorted_ages.pop(0)\n operations += 1\n else:\n ages.append(ages.pop(0))\n operations += 1\n\nreturn operations","test":"METADATA = {\n 'author': 'ay',\n 'dataset': 'test'\n}\n\ndef check(candidate):\n assert candidate([3, 4, 1]) == 5\n assert candidate([1, 2, 4, 3]) == 5\n assert candidate([5, 2, 1, 6, 4, 3]) == 16\n assert candidate([1, 2, 3, 4, 5]) == 5"} { "task_id": "PythonSaga/84","prompt":"from typing import List, Tuple\n\ndef stupid_pair(nums: List) -> int:\n \"\"\"Given an integer array nums, return the number of Stupid pairs in the array. \n A Stupid pair is a pair (i, j) where: i > 2 * j and index of i < index of j. \n Take a list of integers as input and return the number of reverse pairs in the list. \n Example 1: \n Input: [1,3,2,3,1]\n Output: 2\n Input: [2,4,3,5,1]\n Output: 3\"\"\"\n","entry_point":"stupid_pair","canonical_solution":"def stupid_pair(nums: List[int]) -> int:\n def merge_and_count(left: List[int], right: List[int]) -> Tuple[List[int], int]:\n merged = []\n count = 0\n i, j = 0, 0\n\n while i < len(left) and j < len(right):\n if left[i] > 2 * right[j]:\n count += len(left) - i\n j += 1\n else:\n i += 1\n\n i, j = 0, 0\n\n while i < len(left) and j < len(right):\n if left[i] <= right[j]:\n merged.append(left[i])\n i += 1\n else:\n merged.append(right[j])\n j += 1\n\n merged += left[i:]\n merged += right[j:]\n\n return merged, count\n\n def merge_sort_and_count(nums: List[int]) -> Tuple[List[int], int]:\n if len(nums) <= 1:\n return nums, 0\n\n mid = len(nums) // 2\n left, count_left = merge_sort_and_count(nums[:mid])\n right, count_right = merge_sort_and_count(nums[mid:])\n merged, count_merge = merge_and_count(left, right)\n\n return merged, count_left + count_right + count_merge\n\n _, count = merge_sort_and_count(nums)\n return count","test":"METADATA = {\n 'author': 'ay',\n 'dataset': 'test'\n}\n\ndef check(candidate):\n assert candidate([1, 3, 2, 3, 1]) == 2\n assert candidate([2, 4, 3, 5, 1]) == 3\n assert candidate([5, 4, 3, 2, 1]) == 4\n assert candidate([1, 2, 3, 4, 5]) == 0"} { "task_id": "PythonSaga/85","prompt":"from typing import List\n\ndef shoes_missing(table1: List[int], table2: List[int]) -> List[List[int]]:\n \"\"\"You are given two tables, table1 and table2, representing shelves of a shoe store where shoes of different sizes are arranged. \n Each table is sorted in ascending order of shoe sizes. Your task is to implement a functions: \n 1. which will merge the two tables into one, \n 2. which will keep only those shoes that are available in both tables, \n 3. which will keep only those shoes that are available in unique on both tables., \n Take input from user for the size of the shoes and display the result accordingly. \n Input [1, 4, 7, 9, 11] [2, 4, 4, 7, 8, 11, 12]\n Output [[1, 2, 4, 4, 4, 7, 7, 8, 9, 11, 11, 12] ,[4, 7, 11], [1, 2, 8, 9, 12]]\"\"\"\n","entry_point":"shoes_missing","canonical_solution":"def merge_tables(table1: List[int], table2: List[int]) -> List[int]:\n return sorted(table1 + table2)\n\ndef find_common_elements(table1: List[int], table2: List[int]) -> List[int]:\n common = []\n for size in set(table1):\n if size in table2:\n common.append(size)\n return sorted(common)\n\ndef find_unique_elements(table1: List[int], table2: List[int]) -> List[int]:\n unique = []\n for size in merge_tables(table1, table2):\n if size in table1 and size not in table2 or size in table2 and size not in table1:\n unique.append(size)\n return unique\n\ndef shoes_missing(table1: List[int], table2: List[int]) -> List[List[int]]:\n merged_table = merge_tables(table1, table2)\n common_elements = find_common_elements(table1, table2)\n unique_elements = find_unique_elements(table1, table2)\n return [merged_table, common_elements, unique_elements]","test":"METADATA = {\n 'author': 'ay',\n 'dataset': 'test'\n}\n\ndef check(candidate):\n assert candidate([1, 4, 7, 9, 11], [2, 4, 4, 7, 8, 11, 12]) == [[1, 2, 4, 4, 4, 7, 7, 8, 9, 11, 11, 12], [4, 7, 11], [1, 2, 8, 9, 12]]\n assert candidate([5, 8, 10, 12, 15], [2, 7, 10, 12, 14, 16]) == [[2, 5, 7, 8, 10, 10, 12, 12, 14, 15, 16], [10, 12], [2, 5, 7, 8, 14, 15, 16]]\n assert candidate([1, 2, 3, 4, 5], [6, 7, 8, 9, 10]) == [[1, 2, 3, 4, 5, 6, 7, 8, 9, 10], [], [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]]\n assert candidate([10, 20, 30], [40, 50, 60, 70]) == [[10, 20, 30, 40, 50, 60, 70], [], [10, 20, 30, 40, 50, 60, 70]]\n assert candidate([], [1, 2, 3, 4, 5]) == [[1, 2, 3, 4, 5], [], [1, 2, 3, 4, 5]]"} { "task_id": "PythonSaga/86","prompt":"from typing import List\n\ndef quick_sort_hoare_partitioning(nums: List[int]) -> List[List[int]]:\n \"\"\"My teacher taught that there are various ways to sort a list. and quick sort is one of them. \n She asked us to do some research about quick sort and implement it in python but in a different way. \n One is using Lumoto partitioning and the other is using Hoare partitioning. \n Please help me to implement the Hoare partitioning in python. \n Take input from the user and sort the list using Hoare partitioning and Lumoto partitioning. \n Example: \n Input: [3, 9, 1, 7, 22, 0, 1]\n Output: [[0, 1, 1, 3, 7, 9, 22], [0, 1, 1, 3, 7, 9, 22]]\"\"\"\n","entry_point":"quick_sort_hoare_partitioning","canonical_solution":"def hoare_partition(nums: List[int], low: int, high: int) -> int:\n pivot = nums[low]\n i = low - 1\n j = high + 1\n while True:\n # Move the left index to the right at least once and while the element at\n # the left index is less than the pivot\n i += 1\n while nums[i] < pivot:\n i += 1\n\n # Move the right index to the left at least once and while the element at\n # the right index is greater than the pivot\n j -= 1\n while nums[j] > pivot:\n j -= 1\n\n # If the indices have crossed, return\n if i >= j:\n return j\n\n # Swap the elements at the left and right indices\n nums[i], nums[j] = nums[j], nums[i]\n\ndef quick_sort_hoare(nums: List[int], low: int, high: int):\n if low < high:\n # Partition the array\n pivot = hoare_partition(nums, low, high)\n # Sort the two halves\n quick_sort_hoare(nums, low, pivot)\n quick_sort_hoare(nums, pivot + 1, high)\n\ndef quick_sort_hoare_partitioning(nums: List[int]) -> List[List[int]]:\n sorted_nums_hoare = nums[:]\n quick_sort_hoare(sorted_nums_hoare, 0, len(sorted_nums_hoare) - 1)\n return [sorted_nums_hoare]","test":"METADATA = {\n 'author': 'ay',\n 'dataset': 'test'\n}\n\ndef check(candidate):\n assert candidate([3, 9, 1, 7, 22, 0, 1]) == [[0, 1, 1, 3, 7, 9, 22],[0, 1, 1, 3, 7, 9, 22]]\n assert candidate([5, 2, 8, 4, 1, 9, 3]) == [[1, 2, 3, 4, 5, 8, 9],[1, 2, 3, 4, 5, 8, 9] ]\n assert candidate([10, 7, 15, 3, 8, 12, 6]) == [[3, 6, 7, 8, 10, 12, 15], [3, 6, 7, 8, 10, 12, 15]]\n assert candidate([6, 3, 2, 10, 1, 5, 7, 8]) == [[1, 2, 3, 5, 6, 7, 8, 10], [1, 2, 3, 5, 6, 7, 8, 10]]"} { "task_id": "PythonSaga/87","prompt":"from typing import List\n\ndef chemicals(grp: int, pairs: List[List[int]]) -> int:\n \"\"\"The director of your laboratory is planning to conduct some experiments. \n However, they want to ensure that the selected chemicals are from different groups. \n You will be given a list of pairs of chemical IDs. Each pair is composed of chemicals from the same group. \n Determine how many pairs of chemicals from different groups they can choose from. \n Take input for the number of pairs of chemicals and pairs of chemicals from user and return the number of pairs of chemicals from different groups. \n\n Example: \n Input: 3, [[1, 2], [3, 4], [1, 5]]\n Output: 6\n Input: 2, [[1, 2], [2, 3]]\n Output: 0\"\"\"\n","entry_point":"chemicals","canonical_solution":"def find(parent, i):\n if parent[i] == i:\n return i\n parent[i] = find(parent, parent[i]) # Path compression\n return parent[i]\n\ndef union(parent, rank, x, y):\n xroot = find(parent, x)\n yroot = find(parent, y)\n if xroot != yroot: # Merge only if x and y are not already in the same set\n if rank[xroot] < rank[yroot]:\n parent[xroot] = yroot\n elif rank[xroot] > rank[yroot]:\n parent[yroot] = xroot\n else:\n parent[yroot] = xroot\n rank[xroot] += 1\n\ndef chemicals(grp: int, pairs: List[List[int]]) -> int:\n # Map chemical IDs to consecutive indices\n id_map = {}\n next_id = 1\n for pair in pairs:\n for chem in pair:\n if chem not in id_map:\n id_map[chem] = next_id\n next_id += 1\n\n parent = [i for i in range(next_id)]\n rank = [0] * next_id\n\n # Union step\n for pair in pairs:\n a, b = pair\n union(parent, rank, id_map[a], id_map[b])\n\n # Count step\n group_count = {}\n for i in range(1, next_id):\n root = find(parent, i)\n if root not in group_count:\n group_count[root] = 1\n else:\n group_count[root] += 1\n\n # Calculate step\n total = sum(group_count.values())\n result = 0\n for count in group_count.values():\n total -= count\n result += count * total\n\n return result","test":"METADATA = {\n 'author': 'ay',\n 'dataset': 'test'\n}\n\ndef check(candidate):\n assert candidate(3, [[1, 2], [3, 4], [1, 5]]) == 6\n assert candidate(2, [[1, 2], [2, 3]]) == 0\n assert candidate(4, [[1, 2], [3, 4], [2, 3], [4, 5]]) == 0\n assert candidate(1, [[1, 2], [2, 3], [5, 4], [4, 5]]) == 10"} { "task_id": "PythonSaga/88","prompt":"from typing import List\n\ndef ship(ships: int, arrival_departure: List[List[int]]) -> int:\n \"\"\"Given arrival and departure times of all ships that arrive at a seaport, \n find the minimum number of berths required for the seaport so that no ship is kept waiting. \n Consider that all the ships arrive and depart on the same day. \n Arrival and departure times can never be the same for a ship, but it's possible for the arrival time \n of one ship to be equal to the departure time of another ship. At any given instance of time, the same berth \n cannot be used for both the departure of a ship and the arrival of another ship. In such cases, different berths are needed. \n Note: Time intervals are in the 24-hour format(HHMM) , where the first two characters represent hour (between 00 to 23 ) and the \n last two characters represent minutes (this may be > 59). \n Take input from the user for the number of ships, arrival and departure times of each ship. and return the minimum number of berths required. \n Example 1: \n Input: 3, [[1000, 1030], [1004, 1130], [1130, 1200]]\n Output: 2\"\"\"\n","entry_point":"ship","canonical_solution":"events = []\n\nfor ship_info in arrival_departure:\n arrival, departure = ship_info\n events.append((arrival, 1)) # 1 represents arrival\n events.append((departure, -1)) # -1 represents departure\n\nevents.sort()\n\ncurrent_berths = 0\nmax_berths_required = 0\n\nfor event_time, event_type in events:\n current_berths += event_type\n max_berths_required = max(max_berths_required, current_berths)\n\nreturn max_berths_required","test":"METADATA = {\n 'author': 'ay',\n 'dataset': 'test'\n}\n\ndef check(candidate):\n assert candidate(3, [[1000, 1030], [1004, 1130], [1130, 1200]]) == 2\n assert candidate(4, [[900, 930], [930, 1000], [945, 1100], [1100, 1130]]) == 2\n assert candidate(5, [[1000, 1030], [1030, 1100], [1045, 1130], [1115, 1200], [1130, 1200]]) == 2"} { "task_id": "PythonSaga/89","prompt":"from typing import List\n\ndef alloy(strengths: List[int]) -> int:\n \"\"\"We are working in laboratory to create alloy with maximum strength. \n We are given list of strength of different elements. Using those elements we have to create alloy. \n maximal strength is defined as nums[i0] * nums[i1] * nums[i2] * ... * nums[iK​], where the strength of elements of indices i0, i1, i2, ... , ik. \n We have to find the maximum strength of alloy that we can create. \n Take input from user in form of list and print the maximum strength of alloy that we can create. \n Example 1: \n Input: [3, -1, -5, 2, 5, -9]\n Output: 1350\n Input: [-4, -5, -4]\n Output: 20\"\"\"\n","entry_point":"alloy","canonical_solution":"","test":"METADATA = {\n 'author': 'ay',\n 'dataset': 'test'\n}\n\ndef check(candidate):\n assert candidate([3, -1, -5, 2, 5, -9]) == 1350\n assert candidate([-4, -5, -4]) == 20\n assert candidate([2, -3, -2, 4, -1, -6, 1, 3]) == 864\n assert candidate([1,-2,3,-4,0,5]) == 120"} { "task_id": "PythonSaga/90","prompt":"import math \ndef rankOfPermutation(strg: str) -> int:\n \"\"\"Take a string as input from user and print its rank among all the possible permutations sorted lexicographically. \n Example: \n Input: 'acb'\n Output: 2\n Input: 'abc'\n Output: 1\n Input: 'string'\n Output: 598\"\"\"\n","entry_point":"rankOfPermutation","canonical_solution":"n = len(strg)\nrank = 1\n\nfor i in range(n):\n smaller_count = 0\n\n for j in range(i + 1, n):\n if strg[j] < strg[i]:\n smaller_count += 1\n\n rank += smaller_count * math.factorial(n - i - 1)\n\nreturn rank","test":"METADATA = {\n 'author': 'ay',\n 'dataset': 'test'\n}\n\ndef check(candidate):\n assert candidate('acb') == 2\n assert candidate('abc') == 1\n assert candidate('string') == 598\n assert candidate('cba') == 6"} { "task_id": "PythonSaga/91","prompt":"from typing import List\n\ndef longestStretch(arr: List[str]) -> int:\n \"\"\"Let's say you attend a car show where cars of different brands are showcased in a row. \n Find the length of the longest stretch where no two cars are of the same brand. \n Take the input from the user for the brands of the cars in the order they are placed in the row. \n Print the length of the longest stretch where no two cars are of the same brand. \n\n Example: \n Input: ['A', 'B', 'D', 'E', 'F', 'G', 'A', 'B', 'E', 'F']\n Output: 6\n Input: ['B', 'B', 'B', 'A', 'C', 'B']\n Output: 3\"\"\"\n","entry_point":"longestStretch","canonical_solution":"char_index_map = {} # To store the last index where each car brand was seen\nstart = 0 # Start index of the current stretch\nmax_length = 0 # Length of the longest stretch without repeating car brands\n\nfor end in range(len(arr)):\n if arr[end] in char_index_map and char_index_map[arr[end]] >= start:\n # If the car brand is repeated, update the start index\n start = char_index_map[arr[end]] + 1\n\n char_index_map[arr[end]] = end # Update the last index of the car brand\n max_length = max(max_length, end - start + 1) # Update the maximum length\n\nreturn max_length","test":"METADATA = {\n 'author': 'ay',\n 'dataset': 'test'\n}\n\ndef check(candidate):\n assert candidate(['A', 'B', 'D', 'E', 'F', 'G', 'A', 'B', 'E', 'F']) == 6\n assert candidate(['B', 'B', 'B', 'A', 'C', 'B']) == 3\n assert candidate(['A', 'A', 'B', 'B', 'C', 'C', 'D', 'E', 'F']) == 4\n assert candidate(['A', 'B', 'A', 'C', 'A', 'D', 'A', 'E', 'A']) == 2"} { "task_id": "PythonSaga/92","prompt":"def cookies_matter(n: int, m: int, tray1: str, tray2: str) -> str:\n \"\"\"Let's say I have row of cookie of different types in two trays arranged in a row \n I want to find smallest window in tray 1 that contains all the cookies in tray 2( including duplicates). \n Return '-NULL-' if no such window exists. In case there are multiple such windows of same length, return the one with the least starting index. \n Take input from user for number of cookies in tray 1 and tray 2. Then take input for cookies brand name starting letter for tray 1 and 2 in form of one string. \n Then take input for cookies brand name starting letter for tray 2 in form of one string. \n\n Example: \n Input: 11,3, 'zoomlazapzo', 'oza' # 11 cookies in tray 1, 3 cookies in tray 2, cookies brand name starting letter for tray 1: zoomlazapzo, cookies brand name starting letter for tray 2: oza\n Output: apzo\n\n Input: 14,3, 'timetopractice', 'toe' # 14 cookies in tray 1, 3 cookies in tray 2, cookies brand name starting letter for tray 1: timetopractice, cookies brand name starting letter for tray 2: toe\n Output: eto\"\"\"\n","entry_point":"cookies_matter","canonical_solution":"if n < m or not tray1 or not tray2:\n return \"-NULL-\"\n\nchar_count_tray2 = {}\nfor char in tray2:\n char_count_tray2[char] = char_count_tray2.get(char, 0) + 1\n\nchar_count_current_window = {}\nrequired_count = len(char_count_tray2)\n\nleft, right = 0, 0\nmin_length = float('inf')\nmin_window_start = 0\n\nwhile right < n:\n char_right = tray1[right]\n char_count_current_window[char_right] = char_count_current_window.get(char_right, 0) + 1\n\n if char_right in char_count_tray2 and char_count_current_window[char_right] == char_count_tray2[char_right]:\n required_count -= 1\n\n while required_count == 0:\n if right - left < min_length:\n min_length = right - left\n min_window_start = left\n\n char_left = tray1[left]\n char_count_current_window[char_left] -= 1\n\n if char_left in char_count_tray2 and char_count_current_window[char_left] < char_count_tray2[char_left]:\n required_count += 1\n\n left += 1\n\n right += 1\n\nif min_length == float('inf'):\n return \"-NULL-\"\nelse:\n return tray1[min_window_start:min_window_start + min_length + 1]","test":"METADATA = {\n 'author': 'ay',\n 'dataset': 'test'\n}\n\ndef check(candidate):\n assert candidate(11, 3, 'zoomlazapzo', 'oza') == 'apzo'\n assert candidate(14, 3, 'timetopractice', 'toe') == 'eto'\n assert candidate(5, 2, 'abcbc', 'bc') == 'bc'\n assert candidate(13, 5, 'Itsgettinghot', 'thing') == 'tingh'"} { "task_id": "PythonSaga/93","prompt":"def strong_pass(password: str) -> int:\n \"\"\"A strong password meets following conditions: \n 1. It has at least 6 characters and at most 20 characters. \n 2. It contains at least one lowercase letter, at least one uppercase letter, and at least one digit. \n 3. It does not contain three repeating characters in a row (abxxxcA0 is weak but abxxcxA0 is strong). \n Given a string password, return the minimum number of steps required to make password strong. if password is already strong, return 0. \n\n In one step, you can: \n a. Insert one character to password, \n b. Delete one character from password, or \n c. Replace one character of password with another character. \n Take string input from user and return the minimum number of steps required to make password strong \n\n Example 1: \n Input: 'b'\n Output: 5\n Input: 'aA0'\n Output: 3\"\"\"\n ","entry_point":"strong_pass","canonical_solution":"# Condition 1: Length between 6 and 20\nn = len(password)\nsteps = 0\n\n# Condition 2: At least one lowercase, one uppercase, and one digit\nhas_lowercase = any(char.islower() for char in password)\nhas_uppercase = any(char.isupper() for char in password)\nhas_digit = any(char.isdigit() for char in password)\n\n# Count of missing character types\nmissing_types_count = 3 - (has_lowercase + has_uppercase + has_digit)\n\n# If the length is less than 6, add the difference to the steps\nif n < 6:\n steps += max(0, 6 - n)\n\n# If the length is more than 20, add the difference to the steps\nelif n > 20:\n extra_chars = max(0, n - 20)\n steps += extra_chars\n\n# Condition 3: Check for repeating characters\nfor i in range(2, n):\n if password[i] == password[i - 1] == password[i - 2]:\n steps += 1\n\n# Choose the maximum between missing character types and steps\nreturn max(missing_types_count, steps)","test":"METADATA = {\n 'author': 'ay',\n 'dataset': 'test'\n}\n\ndef check(candidate):\n assert candidate('b') == 5\n assert candidate('aA0') == 3\n assert candidate('aaaaAA12345') == 2\n assert candidate('abcdefghijABCDEFGHIJ12345') == 5"} { "task_id": "PythonSaga/94","prompt":"def overlap_substring(s: str) -> str:\n \"\"\"Given a string s, find and return any substring of s that occurs two or more times, allowing for overlapping occurrences. \n The goal is to return a duplicated substring with the maximum length. \n If no such duplicated substring exists, the output should be an 'EMPTY' string. \n Take input from user and print the output. \n\n Example 1: \n Input: 'banana'\n Output: 'ana'\n Input: 'abcdcdbacd'\n Output: 'cd'\"\"\"\n n = len(s)\n result = 'EMPTY'\n for i in range(n):\n for j in range(i + 1, n):\n if s[i:j] in s[j:]:\n if len(s[i:j]) > len(result):\n result = s[i:j]\n return result","entry_point":"overlap_substring","canonical_solution":"length = len(s)\nresult = \"\"\n\nfor i in range(length):\n for j in range(i + 1, length):\n substring = s[i:j]\n if substring in s[j:]:\n if len(substring) > len(result):\n result = substring\n\nreturn result if result else \"EMPTY\"","test":"METADATA = {\n 'author': 'ay',\n 'dataset': 'test'\n}\n\ndef check(candidate):\n assert candidate('banana') == 'ana'\n assert candidate('abcdcdbacd') == 'cd'\n assert candidate('abcdefg') == 'EMPTY'\n assert candidate('ababcabab') == 'abab'"} { "task_id": "PythonSaga/95","prompt":"from typing import List\n\ndef find_two_odd_occuring_numbers(numbers: List[int]) -> List[int]:\n \"\"\"I have am unsorted list of numbers. In that list other than two numbers all other numbers have occured even number of times. \n Find those two numbers in O(n) time ( you can use bit manipulation for this) \n Take input from user and print the output. Use bit manipulation to solve this problem.\n\n Example: \n Input: [11, 22, 33, 11, 11, 22, 11, 44]\n Output:[33, 44]\n\n Input: [10, 11]\n Output:[10, 11]\"\"\"\n","entry_point":"find_two_odd_occuring_numbers","canonical_solution":"# Step 1: Find XOR of all elements\nxor_result = 0\nfor num in numbers:\n xor_result ^= num\n\n# Step 2: Find the rightmost set bit\nrightmost_set_bit = xor_result & -xor_result\n\n# Step 3: Divide the list into two sublists\ngroup1, group2 = 0, 0\nfor num in numbers:\n if num & rightmost_set_bit:\n group1 ^= num\n else:\n group2 ^= num\n\nreturn [group1, group2]","test":"METADATA = {\n 'author': 'ay',\n 'dataset': 'test'\n}\n\ndef check(candidate):\n assert set(candidate([11, 22, 33, 11, 11, 22, 11, 44])) == [33, 44]\n assert set(candidate([10, 11])) == [11, 10]\n assert set(candidate([1, 1, 2, 2, 3, 4, 4, 5])) == [3, 5]\n assert set(candidate([5, 5, 7, 7, 9, 9, 11, 11, 13, 13, 15,0])) == [15, 0]"} { "task_id": "PythonSaga/96","prompt":"from typing import List\n\ndef find_max_and_or(numbers: List[int]) -> List[int]:\n \"\"\"My teacher gave me list of numbers and asked me to find \n 'maximum AND value 'and 'maximum OR value' generated by any pair of numbers. Try to use bit manipulation to solve this problem. \n Take input from user and find the maximum and value and maximum or value generated by any pair of numbers. \n Expected Time Complexity: O(N * log M), where M is the maximum element of the array. \n\n Example: \n Input: [4, 8, 12, 16]\n Output: [8, 28] # Maximum AND value = 8, Maximum OR value = 28\n Input: [4, 8, 16, 2]\n Output: [0, 24] # Maximum AND value = 0, Maximum OR value = 24\"\"\"\n","entry_point":"find_max_and_or","canonical_solution":"max_num = max(numbers)\nmax_and, max_or = 0, 0\n\n# Calculate maximum OR value by ORing all numbers\nfor num in numbers:\n max_or |= num\n\n# Iterate over each bit position\nfor bit in range(max_num.bit_length(), -1, -1):\n # Filter numbers that have the current bit set\n candidates = [num for num in numbers if num & (1 << bit)]\n \n # If at least two numbers have this bit set, update max_and\n if len(candidates) >= 2:\n max_and |= (1 << bit)\n # Update the numbers list to only include these candidates\n # as further bits set will only be found within these numbers\n numbers = candidates\n\nreturn [max_and, max_or]","test":"METADATA = {\n 'author': 'ay',\n 'dataset': 'test'\n}\n\ndef check(candidate):\n assert candidate([4, 8, 12, 16]) == [8, 28]\n assert candidate([4, 8, 16, 2]) == [0, 24]\n assert candidate([7, 15, 22, 19]) == [18, 23]\n assert candidate([3, 5, 10, 15]) == [10, 15]"} { "task_id": "PythonSaga/97","prompt":"def set_bits(n:int) -> int:\n \"\"\"Today in class we were taught that we can written any number in form of 0 and 1. \n My tutor asked me to find number of set bits are present in a number from 1 to n( both inclusive). \n Take a input from user and print the number of set bits in that number. \n\n Example: \n Input: 4\n Output: 5\n Input: 17\n Output: 35\"\"\"\n","entry_point":"set_bits","canonical_solution":"def count_set_bits(n: int) -> int:\n count = 0\n\n while n:\n n &= (n - 1)\n count += 1\n\n return count\n\ndef set_bits(n: int) -> int:\n total_set_bits = 0\n\n for i in range(1, n + 1):\n total_set_bits += count_set_bits(i)\n\n return total_set_bits","test":"METADATA = {\n 'author': 'ay',\n 'dataset': 'test'\n}\n\ndef check(candidate):\n assert candidate(4) == 5\n assert candidate(17) == 35\n assert candidate(10) == 17\n assert candidate(7) == 12"} { "task_id": "PythonSaga/98","prompt":"def quotient(dividend:int, divisor:int) -> int:\n \"\"\"My teacher gave me divident and divisor and asked me to find quotient. But the condition is that \n I have to divide two integers without using multiplication, division, and mod operator. \n Take input from user and print the quotient. The The integer division should truncate toward zero, which means losing its fractional part. \n For example, 9.343 would be truncated to 9, and -1.335 would be truncated to -1. \n\n Example 1: \n Input:10,3 # 10 is the dividend and 3 is the divisor\n Output:3 # 3 is the quotient\n Input:7,-3\n Output:-2\"\"\"\n","entry_point":"quotient","canonical_solution":"# Determine the sign of the quotient\nsign = -1 if (dividend < 0) ^ (divisor < 0) else 1\n\n# Take the absolute values of dividend and divisor\ndividend = abs(dividend)\ndivisor = abs(divisor)\n\nquotient_result = 0\n\n# Bitwise division\nwhile dividend >= divisor:\n dividend -= divisor\n quotient_result += 1\n\nreturn sign * quotient_result","test":"METADATA = {\n 'author': 'ay',\n 'dataset': 'test'\n}\n\ndef check(candidate):\n assert candidate(10, 3) == 3\n assert candidate(7, -3) == -2\n assert candidate(-20, 4) == -5\n assert candidate(15, 2) == 7"} { "task_id": "PythonSaga/99","prompt":"from typing import List\n\ndef good_subset(arr: List[int]) -> int:\n \"\"\"I found one interesting question help me to solve this problem. I have a list of numbers and I want to find all the subsets of this list which are amazing. \n A group of numbers is said amazing if its product can be represented as a product of one or more distinct prime numbers. \n Take input from user and print total number of different amazing subsets of the given list. Return the final output modulo 10^9+7. \n Example: \n Input: [1,2,3,4]\n Output: 6 # 6 good subsets\n Input: [4,2,3,15]\n Output: 5 \"\"\"\n","entry_point":"good_subset","canonical_solution":"MOD = 10**9 + 7\nmax_val = max(arr)\n\n# Sieve of Eratosthenes to find primes up to max_val\nprime = [True for _ in range(max_val + 1)]\np = 2\nwhile (p * p <= max_val):\n if (prime[p] == True):\n for i in range(p * p, max_val + 1, p):\n prime[i] = False\n p += 1\n\nprimes = [p for p in range(2, max_val + 1) if prime[p]]\n\n# Dynamic programming array\ndp = [0] * (1 << len(primes))\ndp[0] = 1 # Empty subset\n\nfor num in arr:\n if num == 1: # Special case for 1\n for i in range(len(dp)):\n dp[i] = (dp[i] * 2) % MOD\n continue\n \n # Find prime factors of num and update dp array\n mask = 0\n for i, p in enumerate(primes):\n if num % p == 0:\n count = 0\n while num % p == 0:\n num //= p\n count += 1\n if count > 1: # Skip if p^2 divides num\n mask = 0\n break\n mask |= 1 << i\n \n if mask > 0:\n for i in range(len(dp) - 1, -1, -1):\n if dp[i] > 0 and (i & mask) == 0:\n dp[i | mask] = (dp[i | mask] + dp[i]) % MOD\n\nreturn (sum(dp) - 1) % MOD # Exclude empty subset","test":"METADATA = {\n 'author': 'ay',\n 'dataset': 'test'\n}\n\ndef check(candidate):\n assert candidate([1, 2, 3, 4]) == 6\n assert candidate([4, 2, 3, 15]) == 5"} { "task_id": "PythonSaga/100","prompt":"from typing import List, Tuple, Dict, Any, Callable, Optional\n\ndef input_func(user: str, house_value: int, income: int, vehicle_value: int) -> dict:\n \"\"\"Create a class named tax, with following functions: \n 1. LandTax: calculate the land tax of a house i.e 2% of the house value \n 2. IncomeTax: calculate the income tax of a person i.e 10% of the income \n 3. vehicleTax: calculate the vehicle tax of a vehicle i.e 5% of the vehicle value \n Take input from user for house value, income and vehicle value and print the tax for each of them. \n Along with this also take name of the person and print the name of the person before printing the tax. \n Example: \n Input: Jhon, {house value: 500000, income: 1000000, vehicle value: 100000}\n Output: {house tax: 10000, income tax: 100000, vehicle tax: 5000}\"\"\"\n","entry_point":"input_func","canonical_solution":"class Tax:\n def __init__(self, user):\n self.user = user\n\n def LandTax(self, house_value):\n return {'house tax': house_value * 0.02}\n\n def IncomeTax(self, income):\n return {'income tax': income * 0.1}\n\n def VehicleTax(self, vehicle_value):\n return {'vehicle tax': vehicle_value * 0.05}\n\nperson_tax = Tax(user)\nresult = {\n **person_tax.LandTax(house_value),\n **person_tax.IncomeTax(income),\n **person_tax.VehicleTax(vehicle_value)\n}\n\nreturn result","test":"METADATA = {\n 'author': 'ay',\n 'dataset': 'test'\n}\n\n\ndef check(candidate):\n assert candidate(\"Alice\", 300000, 80000, 75000) == {'house tax': 6000, 'income tax': 8000, 'vehicle tax': 3750}\n assert candidate(\"Bob\", 450000, 120000, 60000) == {'house tax': 9000, 'income tax': 12000, 'vehicle tax': 3000}\n assert candidate(\"Charlie\", 600000, 150000, 90000) == {'house tax': 12000, 'income tax': 15000, 'vehicle tax': 4500}\n assert candidate(\"David\", 350000, 90000, 80000) == {'house tax': 7000, 'income tax': 9000, 'vehicle tax': 4000}"} { "task_id": "PythonSaga/101","prompt":"from typing import List, Tuple, Dict, Any, Callable, Optional\n\ndef input_func2(eqn: str) -> str:\n \"\"\"I want to check whether the equation given by user is balanced or not in form of \n paranthesis and operators. Make a class named check_balance and conduct the test. \n There are four operators: +, -, *, / \n There are few paranthesis: (,{,[,],},) \n Take input from user and return \"Balanced\" or \"Not Balanced\" accordingly. \n Example:\n\n Input: (a+b)*c \n Output: Balanced \n\n Input: (a+b)*c) \n Output: Not Balanced \n\n Input: (a+b)c \n Output: Not Balanced \"\"\"\n","entry_point":"input_func2","canonical_solution":"class CheckBalance:\n def __init__(self, eqn: str):\n self.eqn = eqn\n self.stack = []\n self.pairs = {')': '(', '}': '{', ']': '['}\n\n def is_balanced(self) -> str:\n last = '' # Keep track of the last character processed\n for char in self.eqn:\n if char in '({[':\n # Check for operand followed by '(' without an operator in between\n if last.isalnum():\n return 'Not Balanced'\n self.stack.append(char)\n elif char in ')}]':\n if not self.stack or self.stack[-1] != self.pairs[char]:\n return 'Not Balanced'\n self.stack.pop()\n elif char.isalnum() and last in ')]}':\n # Check for ')' followed by an operand without an operator in between\n return 'Not Balanced'\n last = char # Update the last character processed\n\n # Check for any unmatched opening parentheses\n if self.stack:\n return 'Not Balanced'\n return 'Balanced'\n\ndef input_func2(eqn: str) -> str:\n checker = CheckBalance(eqn)\n return checker.is_balanced()","test":"METADATA = {\n 'author': 'ay',\n 'dataset': 'test'\n}\n\ndef check(candidate):\n assert candidate(\"(a+b)*c\") == \"Balanced\"\n assert candidate(\"(a+b)*c)\") == \"Not Balanced\"\n assert candidate(\"(a+b)c\") == \"Not Balanced\"\n assert candidate(\"(a+b)*[c-d]/{e+f}\") == \"Balanced\""} { "task_id": "PythonSaga/102","prompt":"from typing import List, Tuple, Dict, Any, Callable, Optional\n\ndef input_func3(lst1: List[int], lst2: List[int]) -> Tuple[List[int], str]:\n \"\"\"Write a Python program that overloads the operator + and > \n for a Orders class. \n Take input from the user for the 2 orders in form of list \n and print the merged list of both orders and also print the order \n with maximum amount. \n\n Example: \n Input: [1,2,3,4,5,6], [10,20,30]\n Output: ([1,2,3,4,5,6,10,20,30], \"Order 2 > Order 1\")\"\"\"\n","entry_point":"input_func3","canonical_solution":"class Orders:\n def __init__(self, order_list: List[int]):\n self.order_list = order_list\n\n def __add__(self, other):\n merged_list = self.order_list + other.order_list\n return Orders(merged_list)\n\n def __gt__(self, other):\n total_amount_self = sum(self.order_list)\n total_amount_other = sum(other.order_list)\n\n if total_amount_self > total_amount_other:\n return f\"Order 1 > Order 2\"\n elif total_amount_self < total_amount_other:\n return f\"Order 2 > Order 1\"\n else:\n return \"Order 1 = Order 2\"\n\ndef input_func3(lst1: List[int], lst2: List[int]) -> Tuple[List[int], str]:\n order1 = Orders(lst1)\n order2 = Orders(lst2)\n\n merged_order = order1 + order2\n comparison_result = order1 > order2\n\n return merged_order.order_list, comparison_result","test":"METADATA = {\n 'author': 'ay',\n 'dataset': 'test'\n}\n\ndef check(candidate):\n assert candidate([1, 2, 3, 4, 5, 6], [10, 20, 30]) == ([1, 2, 3, 4, 5, 6, 10, 20, 30], \"Order 2 > Order 1\")\n assert candidate([5, 10, 15], [2, 7, 12]) == ([5, 10, 15, 2, 7, 12], \"Order 1 > Order 2\")\n assert candidate([1, 2, 3], [4, 5, 6]) == ([1, 2, 3, 4, 5, 6], \"Order 2 > Order 1\")\n assert candidate([], [10, 20, 30]) == ([10, 20, 30], \"Order 2 > Order 1\")"} { "task_id": "PythonSaga/103","prompt":"from typing import List, Tuple, Dict, Any, Callable, Optional\n\ndef input_func4(animal: str) -> str:\n \"\"\"I want to teach my nephew about sound and type of different animals \n Create one class animal which displays name of animal input by user. \n Create 4 classes: \n 1. Dog, type of animal: mammal, sound: bark \n 2. Cat, type of animal: mammal, sound: meow \n 3. Duck , type of animal: bird, sound: quack \n 4. snake, type of animal: reptile, sound: hiss \n Take input from user and display the name of animal and its type and sound. \n Try to use inheritance to reduce the number of lines of code. \n\n Example: \n Input: \"dog\"\n Output: \"Name of animal is dog, it belongs to mammal family and it barks.\"\n Input: \"snake\"\n Output: \"Name of animal is snake, it belongs to reptile family and it hisses.\"\"\"\n","entry_point":"input_func4","canonical_solution":"class Animal:\n def __init__(self, name: str, animal_type: str, sound: str):\n self.name = name\n self.animal_type = animal_type\n self.sound = sound\n\n def display_info(self) -> str:\n return f\"Name of animal is {self.name}, it belongs to {self.animal_type} family and it {self.sound}.\"\n\nclass Dog(Animal):\n def __init__(self, name: str):\n super().__init__(name, \"mammal\", \"barks\")\n\nclass Cat(Animal):\n def __init__(self, name: str):\n super().__init__(name, \"mammal\", \"meows\")\n\nclass Duck(Animal):\n def __init__(self, name: str):\n super().__init__(name, \"bird\", \"quacks\")\n\nclass Snake(Animal):\n def __init__(self, name: str):\n super().__init__(name, \"reptile\", \"hisses\")\n\ndef input_func4(animal: str) -> str:\n animal_class = None\n if animal.lower() == \"dog\":\n animal_class = Dog(animal)\n elif animal.lower() == \"cat\":\n animal_class = Cat(animal)\n elif animal.lower() == \"duck\":\n animal_class = Duck(animal)\n elif animal.lower() == \"snake\":\n animal_class = Snake(animal)\n\n if animal_class:\n return animal_class.display_info()\n else:\n return \"Unknown animal.\"","test":"METADATA = {\n 'author': 'ay',\n 'dataset': 'test'\n}\n\ndef check(candidate):\n assert candidate(\"dog\") == \"Name of animal is dog, it belongs to mammal family and it barks.\"\n assert candidate(\"cat\") == \"Name of animal is cat, it belongs to mammal family and it meows.\"\n assert candidate(\"duck\") == \"Name of animal is duck, it belongs to bird family and it quacks.\"\n assert candidate(\"snake\") == \"Name of animal is snake, it belongs to reptile family and it hisses.\""} { "task_id": "PythonSaga/104","prompt":"from typing import List, Tuple, Dict, Any, Callable, Optional\n\ndef input_func5(dir: List[List[str, int]]) -> int:\n \"\"\"I want to know how far I'm from origin if I move certain distance in certain direction \n Direction can be N,S,E,W and distance can be any positive integer \n Create class Distance that returns the distance from origin \n Also create other classes named North, South, East, West that inherit from Distance \n Take input from the user in the form of Direction and Distance until the user enters 'stop' \n Return the distance from origin \n Example: \n Input: [[N,5],[E,3],[S,5],[stop]]\n Output: 3\n Input: [[N,5],[N,7],[S,5],[stop]]\n Output: 7\"\"\"\n","entry_point":"input_func5","canonical_solution":"class Distance:\n def __init__(self):\n self.x = 0 # East-West position\n self.y = 0 # North-South position\n\n def update_position(self, distance: int, direction: str):\n if direction == 'N':\n self.y += distance\n elif direction == 'S':\n self.y -= distance\n elif direction == 'E':\n self.x += distance\n elif direction == 'W':\n self.x -= distance\n\n def get_distance_from_origin(self) -> int:\n # Manhattan distance from the origin\n return abs(self.x) + abs(self.y)\n\ndef input_func5(dir: List[Tuple[str, int]]) -> int:\n distance_obj = Distance()\n for command in dir:\n if command[0].lower() == 'stop': # Using lower() to make it case-insensitive\n break\n direction, dist = command\n distance_obj.update_position(dist, direction)\n \n return distance_obj.get_distance_from_origin()","test":"METADATA = {\n 'author': 'ay',\n 'dataset': 'test'\n}\n\ndef check(candidate):\n assert candidate([['N', 5], ['E', 3], ['S', 5], ['stop']]) == 3\n assert candidate([['N', 5], ['N', 7], ['S', 5], ['stop']]) == 7\n assert candidate([['E', 10], ['W', 5], ['N', 3], ['S', 3], ['stop']]) == 5\n assert candidate([['E', 8], ['W', 4], ['S', 3], ['stop']]) == 5"} { "task_id": "PythonSaga/105","prompt":"from typing import List\n\ndef mirror_matrix(n: int, matrix: List[List[int]]) -> List[List[int]]:\n \"\"\"User wants to give a 2-D array of order N x N, print a matrix that is the mirror of the given tree across the diagonal. \n We need to print the result in such a way that swaps the values of the triangle above the diagonal with the values of the triangle below it like a mirror image swap. \n Take the value of n from the user and take n rows of input from the user and Print the 2-D array obtained in a matrix layout. \n Example: \n Input: 3,[[1,2,4],[5,9,0],[3,1,7]]\n Output: [[1,5,3],[2,9,1],[4,0,7]]\"\"\"\n","entry_point":"mirror_matrix","canonical_solution":"for i in range(n):\n for j in range(i + 1, n):\n # Swap the values across the diagonal\n matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]\n\nreturn matrix","test":"METADATA = {\n 'author': 'ay',\n 'dataset': 'test'\n}\n\ndef check(candidate):\n assert candidate(3, [[1, 2, 4], [5, 9, 0], [3, 1, 7]]) == [[1, 5, 3], [2, 9, 1], [4, 0, 7]]\n assert candidate(2, [[1, 2], [3, 4]]) == [[1, 3], [2, 4]]\n assert candidate(4, [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]) == [[1, 5, 9, 13], [2, 6, 10, 14], [3, 7, 11, 15], [4, 8, 12, 16]]\n assert candidate(3, [[1, 0, 0], [0, 1, 0], [0, 0, 1]]) == [[1, 0, 0], [0, 1, 0], [0, 0, 1]]\n assert candidate(1, [[9]]) == [[9]]"} { "task_id": "PythonSaga/106","prompt":"from typing import List\n\ndef equivalent_matrices(n: int, m: int, matrix1: List[List[int]], matrix2: List[List[int]]) -> int:\n \"\"\"User wants to give two 2-D array of order N x M, print the number of changes required to make M1 equal to M2. \n A change is as: \n 1. Select any one matrix out of two matrices. \n 2. Choose either row/column of the selected matrix. \n 3. Increment every element of the selected row/column by 1. \n Take the value of n and m from the user and take two input matrices from the user. \n Print the number of changes required to make M1 equal to M2. if it is not possible print -1. \n Example: \n Input: 2,2,[[1,1],[1,1]],[[1,2],[3,4]] # Here 2 is n and 2 is m. and then two matrices of order 2*2.\n Output: 3\n\n Input: 2,2,[[1,1],[1,1]],[[1,0],[0,-1]] # Here 2 is n and 2 is m. and then two matrices of order 2*2. \n Output: -1\"\"\"\n","entry_point":"equivalent_matrices","canonical_solution":"","test":"METADATA = {\n 'author': 'ay',\n 'dataset': 'test'\n}\n\ndef check(candidate):\n assert candidate(2, 2, [[1, 1], [1, 1]], [[1, 2], [3, 4]]) == 3\n assert candidate(2, 2, [[1, 1], [1, 1]], [[1, 0], [0, -1]]) == -1\n assert candidate(2, 3, [[1, 1, 1], [2, 2, 2]], [[2, 2, 2], [3, 3, 3]]) == 2\n assert candidate(2, 2, [[1, 2], [3, 4]], [[2, 4], [3, 6]]) == -1"} { "task_id": "PythonSaga/107","prompt":"from typing import List\n\ndef max_prize(n: int, m: int, matrix: List[List[int]]) -> int:\n \"\"\"User wants to give a 2-D array of order N x M, print the maximum prize I can get by selecting any submatrix of any size. \n Take the value of n and m from the user and take n rows of input from the user and Print the maximum prize i.e sum of all the elements of the submatrix. \n Example: \n Input: 4,5,[[1,2,-1,-4,-20],[-8,-3,4,2,1],[3,8,10,1,3],[-4,-1,1,7,-6]] # Here 4 is n and 5 is m. and then matrix of order 4*5.\n Output: 29\"\"\"\n","entry_point":"max_prize","canonical_solution":"def kadane(arr: List[int]) -> int:\n max_ending_here = max_so_far = arr[0]\n for x in arr[1:]:\n max_ending_here = max(x, max_ending_here + x)\n max_so_far = max(max_so_far, max_ending_here)\n return max_so_far\n\ndef max_prize(n: int, m: int, matrix: List[List[int]]) -> int:\n maxSum = float('-inf')\n\n # Row combination loop\n for startRow in range(n):\n temp = [0] * m\n for row in range(startRow, n):\n # Calculate cumulative sum for the current row combination\n for col in range(m):\n temp[col] += matrix[row][col]\n \n # Apply Kadane's algorithm to find max sum for this row combination\n maxSum = max(maxSum, kadane(temp))\n\n return maxSum","test":"METADATA = {\n 'author': 'ay',\n 'dataset': 'test'\n}\n\ndef check(candidate):\n assert candidate(4, 5, [[1, 2, -1, -4, -20], [-8, -3, 4, 2, 1], [3, 8, 10, 1, 3], [-4, -1, 1, 7, -6]]) == 29\n assert candidate(3, 3, [[-1, 2, -3], [4, -5, 6], [-7, 8, -9]]) == 5\n assert candidate(2, 2, [[1, -2], [3, 4]]) == 7\n assert candidate(2, 3, [[1, 2, 3], [-4, 5, 6]]) == 16"} { "task_id": "PythonSaga/108","prompt":"from typing import List\n\ndef longest_path(n: int, m: int, matrix: List[List[int]]) -> int:\n \"\"\"User wants to give a 2-D array of order N x M, print the maximum number of cells that you can visit in the matrix by starting from some cell. \n Take the value of n and m from the user and take n rows of input from the user and Print the maximum number of cells that you can visit in the matrix by starting from some cell. \n Example: \n Input: 2,3,[[3,1,6],[-9,5,7]] # Here 2 is n and 3 is m. and then matrix of order 2*3.\n Output: 4\n\n Input: 2,2,[[4,2],[4,5]] # Here 2 is n and 2 is m. and then matrix of order 2*2.\n Output: 2\"\"\"\n","entry_point":"longest_path","canonical_solution":"def dfs(i, j, n, m, matrix, dp):\n # If dp[i][j] is already computed, return its value\n if dp[i][j] != 0:\n return dp[i][j]\n \n # Possible moves: up, down, left, right\n directions = [(0, 1), (0, -1), (1, 0), (-1, 0)]\n max_path = 1 # Minimum path length starting from cell (i, j) is 1\n \n for di, dj in directions:\n x, y = i + di, j + dj\n # Move to the cell (x, y) if it's within the matrix bounds and has a greater value\n if 0 <= x < n and 0 <= y < m and matrix[x][y] > matrix[i][j]:\n max_path = max(max_path, 1 + dfs(x, y, n, m, matrix, dp))\n \n dp[i][j] = max_path # Memoize the result\n return max_path\n\ndef longest_path(n: int, m: int, matrix: List[List[int]]) -> int:\n dp = [[0 for _ in range(m)] for _ in range(n)] # Initialize the dp matrix\n max_length = 0\n\n for i in range(n):\n for j in range(m):\n max_length = max(max_length, dfs(i, j, n, m, matrix, dp))\n \n return max_length","test":"METADATA = {\n 'author': 'ay',\n 'dataset': 'test'\n}\n\ndef check(candidate):\n assert candidate(2, 3, [[3, 1, 6], [-9, 5, 7]]) == 4\n assert candidate(2, 2, [[4, 2], [4, 5]]) == 2\n assert candidate(3, 3, [[1, 2, 3], [6, 5, 4], [7, 8, 9]]) == 9\n assert candidate(2, 2, [[-1, 6], [5, 3]]) == 2"} { "task_id": "PythonSaga/109","prompt":"from typing import List\n\ndef max_prod(n: int, m: int, matrix: List[List[int]]) -> int:\n \"\"\"You are given an m x n matrix grid. Initially, you are located at the top-left corner (0, 0), and in each step, you can only move right or down in the matrix. \n Among all possible paths starting from the top-left corner (0, 0) and ending in the bottom-right corner (m - 1, n - 1), \n find the path with the maximum non-negative product. The product of a path is the product of all integers in the grid cells visited along the path. \n Return the maximum non-negative product modulo 10^9 + 7. If the maximum product is negative, return -1. \n Take the value of n and m as input from the user and then take the input matrix of size n*m from the user. \n\n Example:\n Input: 3,3,[[1,-2,-3],[-2,-3,-3],[-3,-3,-2]]\n Output: -1\n\n Input: 2,2,[[1,2],[0,-4]]\n Output: 0\"\"\"\n","entry_point":"max_prod","canonical_solution":"","test":"METADATA = {\n 'author': 'ay',\n 'dataset': 'test'\n}\n\ndef check(candidate):\n assert candidate(3, 3, [[1, -2, -3], [-2, -3, -3], [-3, -3, -2]]) == -1\n assert candidate(2, 2, [[1, 2], [0, -4]]) == 0\n assert candidate(2, 3, [[1, 2, 3], [4, 5, -6]]) == -1\n assert candidate(3, 3, [[1, 1, 1], [1, -1, -2], [-1, 1, 1]]) == 2"} { "task_id": "PythonSaga/110","prompt":"from typing import List\n\ndef binary_tree(arr: List[int]) -> bool:\n \"\"\"My uncle gave me a Binary Tree. \n He asked me to Check whether all of its nodes have the value equal to the sum of their child nodes. \n If yes, return True. Otherwise, return False. \n Take input from the user and print the result. \n Example: \n Input: [10,10] # Given in level order traversal\n Output: True\n Input: [1,4,3,5]\n Output: False\"\"\"\n","entry_point":"binary_tree","canonical_solution":"def is_sum_tree(arr, index=0):\n # Base case: if the current node is a leaf or beyond the length of the array, it's considered a sum tree\n if index >= len(arr) or 2 * index + 1 >= len(arr):\n return True\n\n # Calculate the index of left and right children\n left = 2 * index + 1\n right = 2 * index + 2\n\n # Value of left child, 0 if there is no left child\n left_val = arr[left] if left < len(arr) else 0\n\n # Value of right child, 0 if there is no right child\n right_val = arr[right] if right < len(arr) else 0\n\n # Check the sum property for the current node and recursively check for children\n return (arr[index] == left_val + right_val) and is_sum_tree(arr, left) and is_sum_tree(arr, right)\n\ndef binary_tree(arr: List[int]) -> bool:\n # The root is at index 0, start checking from there\n return is_sum_tree(arr)","test":"METADATA = {\n 'author': 'ay',\n 'dataset': 'test'\n}\n\ndef check(candidate):\n assert candidate([10, 10]) == True\n assert candidate([1, 4, 3, 5]) == False\n assert candidate([1, 2, 3, 6, 3, 2, 1]) == False\n assert candidate([12, 9, 3, 6, 3, 2, 1]) == True\n assert candidate([]) == True"} { "task_id": "PythonSaga/111","prompt":"from typing import List\n\ndef floor_ceil(num: int, arr: List[int]) -> List[int]:\n \"\"\"My teacher gave me a binary search tree, and I have to make a function to find the floor and ceil of a number in the tree. \n Take a binary search tree and a number as input from the user and return the floor and ceil of the number. \n Example: \n Input: 3,[8,5,9,2,6,null,10] # Given in level order traversal\n Output: [2,5] # Floor and ceil of 3 in the given bst\"\"\"\n","entry_point":"floor_ceil","canonical_solution":"def find_floor_ceil(arr, num, index=0, floor=None, ceil=None):\n # Base case: if the current index is out of range or the node is None\n if index >= len(arr) or arr[index] is None:\n return floor, ceil\n\n # If the current node's value is equal to num, both floor and ceil are the num itself\n if arr[index] == num:\n return num, num\n\n # Update floor and ceil\n if arr[index] < num:\n floor = arr[index]\n return find_floor_ceil(arr, num, 2 * index + 2, floor, ceil) # Go to the right child\n else:\n ceil = arr[index]\n return find_floor_ceil(arr, num, 2 * index + 1, floor, ceil) # Go to the left child\n\ndef floor_ceil(num, arr):\n return list(find_floor_ceil(arr, num))","test":"METADATA = {\n 'author': 'ay',\n 'dataset': 'test'\n}\n\ndef check(candidate):\n assert candidate(10,[10, 10]) == [10,10]\n assert candidate(2,[1, 4, 3, 5]) == [1,3]\n assert candidate(3,[8, 5, 9, 2, 6, None, 10]) == [2,5]\n assert candidate(1,[8, 5, 9, 2, 6, None, 10]) == [None,2]"} { "task_id": "PythonSaga/112","prompt":"from typing import List\n\ndef merge_bst(arr1: List[int], arr2: List[int]) -> List[int]:\n \"\"\"I have 2 binary search trees, and I want to merge them into one binary search tree. \n Take 2 binary search trees as input from the user, and return an inorder traversal of the binary search tree as output. \n\n Example: \n Input: [3,1,5],[4,2,6] # Given in level order traversal\n Output: [1,2,3,4,5,6]\n Input: [8,2,10,1],[5,3,null,0]\n Output: [0,1,2,3,5,8,10]\"\"\"\n","entry_point":"merge_bst","canonical_solution":"def inorder_from_level_order(arr, index=0, inorder=[]):\n if index >= len(arr) or arr[index] is None:\n return\n # Traverse left subtree\n inorder_from_level_order(arr, 2 * index + 1, inorder)\n # Visit node\n inorder.append(arr[index])\n # Traverse right subtree\n inorder_from_level_order(arr, 2 * index + 2, inorder)\n\ndef merge_inorder_traversals(inorder1, inorder2):\n merged = []\n i = j = 0\n while i < len(inorder1) and j < len(inorder2):\n if inorder1[i] < inorder2[j]:\n merged.append(inorder1[i])\n i += 1\n else:\n merged.append(inorder2[j])\n j += 1\n # Append remaining elements\n merged.extend(inorder1[i:])\n merged.extend(inorder2[j:])\n return merged\n\ndef merge_bst(arr1, arr2):\n inorder1 = []\n inorder2 = []\n inorder_from_level_order(arr1, 0, inorder1)\n inorder_from_level_order(arr2, 0, inorder2)\n return merge_inorder_traversals(inorder1, inorder2)","test":"METADATA = {\n 'author': 'ay',\n 'dataset': 'test'\n}\n\ndef check(candidate):\n # Test Case 1:\n input_data1 = [3, 1, 5]\n input_data2 = [4, 2, 6]\n assert candidate(input_data1, input_data2) == [1, 2, 3, 4, 5, 6]\n\n # Test Case 2:\n input_data3 = [8, 2, 10, 1]\n input_data4 = [5, 3, None, 0]\n assert candidate(input_data3, input_data4) == [0, 1, 2, 3, 5, 8, 10]\n\n # Test Case 3:\n input_data5 = [2,1,3]\n input_data6 = [4]\n assert candidate(input_data5, input_data6) == [1,2,3,4]\n\n # Test Case 4:\n input_data7 = [4, 2, 7,None, 3]\n input_data8 = [5,1,7]\n assert candidate(input_data7, input_data8) == [1, 2, 3, 4, 5, 7, 7]"} { "task_id": "PythonSaga/113","prompt":"from typing import List\ndef valid_bst(arr: List[int]) -> bool:\n \"\"\"A valid BST is defined as follows: \n The left subtree of a node contains only nodes with keys less than the node's key. \n The right subtree of a node contains only nodes with keys greater than the node's key. \n Both the left and right subtrees must also be binary search trees. \n Take input from the user and check if it is a valid BST or not. \n Example 1: \n Input: [2,1,3] # Given in level order traversal\n Output: True\n Input: [5,1,4,None,None,3,6]\n Output: False\n Input: [5,1,6,None,None,5.5,7]\n Output: True\"\"\"","entry_point":"valid_bst","canonical_solution":"class TreeNode:\n def __init__(self, value):\n self.value = value\n self.left = None\n self.right = None\n\ndef insert_bst(root, value):\n if not root:\n return TreeNode(value)\n\n if value < root.value:\n root.left = insert_bst(root.left, value)\n elif value > root.value:\n root.right = insert_bst(root.right, value)\n\n return root\n\ndef is_valid_bst(arr: List[int]) -> bool:\n if not arr:\n return True\n\n root = TreeNode(arr[0])\n queue = [root]\n index = 1\n\n while queue and index < len(arr):\n current = queue.pop(0)\n\n if arr[index] is not None:\n current.left = TreeNode(arr[index])\n queue.append(current.left)\n\n index += 1\n\n if index < len(arr) and arr[index] is not None:\n current.right = TreeNode(arr[index])\n queue.append(current.right)\n\n index += 1\n\n def is_bst(node, min_val=float('-inf'), max_val=float('inf')):\n if not node:\n return True\n\n if not min_val < node.value < max_val:\n return False\n\n return is_bst(node.left, min_val, node.value) and is_bst(node.right, node.value, max_val)\n\n return is_bst(root)","test":"METADATA = {\n 'author': 'ay',\n 'dataset': 'test'\n}\n\n\ndef check(candidate):\n input_data1 = [2, 1, 3]\n assert candidate(input_data1) == True\n input_data2 = [5, 1, 4, None, None, 3, 6]\n assert candidate(input_data2) == False\n input_data3 = [5, 1, 6, None, None, 5.5, 7]\n assert candidate(input_data3) == True\n input_data4 = [10, 5, 15, None, None, 12, 20]\n assert candidate(input_data4) == True"} { "task_id": "PythonSaga/114","prompt":"from typing import List\ndef longest_univalue_path(arr: List[int]) -> int:\n \"\"\"I have the root of a binary tree, and task is to return the length of the longest path, where each node in the path has the same value. \n This path may or may not pass through the root. \n The length of the path between two nodes is represented by the number of edges between them. \n Take input from user for binary tree and return the length of the longest path, where each node in the path has the same value. \n Example 1: \n Input: root = [5,4,5,1,1,5,5] # Level order traversal\n Output: 2\n Input: root = [2,4,5,4,4,5] # Level order traversal\n Output: 2\"\"\"","entry_point":"longest_univalue_path","canonical_solution":"def longest_univalue_path(arr: List[int]) -> int:\n def dfs(index, value):\n if index >= len(arr) or arr[index] is None:\n return 0\n left_len = dfs(2 * index + 1, arr[index])\n right_len = dfs(2 * index + 2, arr[index])\n # Update global maximum using paths from left and right children\n nonlocal max_length\n max_length = max(max_length, left_len + right_len)\n # Return the length of the path extending from the current node\n if arr[index] == value:\n return 1 + max(left_len, right_len)\n return 0\n\n if not arr:\n return 0\n max_length = 0\n dfs(0, arr[0])\n return max_length","test":"METADATA = {\n 'author': 'ay',\n 'dataset': 'test'\n}\n\n\ndef check(candidate):\n assert candidate([5, 4, 5, 1, 1, 5, 5]) == 2\n assert candidate([2, 4, 5, 4, 4, 5]) == 2\n assert candidate([1, 1, 1, 1, 1, None, 1]) == 4\n assert candidate([1, 2, 2, 2, 2, 3, 3, 2]) == 3"} { "task_id": "PythonSaga/115","prompt":"from typing import List\ndef max_heapify(arr: List[int]) -> List[int]:\n \"\"\"My friend gave me binary tree and asked me to construct max heap from it and return level order traversal of max heap. \n Take binary tree as input from user and construct max heap from it and return level order traversal of heap. \n Example: \n\n Input: [1, 3, 5, 4, 6, 13, 10, 9, 8, 15, 17]\n Output: [17, 15, 13, 9, 6, 5, 10, 4, 8, 3, 1]\"\"\"","entry_point":"max_heapify","canonical_solution":"def heapify(arr: List[int], n: int, i: int):\n largest = i # Initialize largest as root\n left = 2 * i + 1 # left = 2*i + 1\n right = 2 * i + 2 # right = 2*i + 2\n\n # If left child is larger than root\n if left < n and arr[largest] < arr[left]:\n largest = left\n\n # If right child is larger than largest so far\n if right < n and arr[largest] < arr[right]:\n largest = right\n\n # If largest is not root\n if largest != i:\n arr[i], arr[largest] = arr[largest], arr[i] # Swap\n\n # Heapify the root\n heapify(arr, n, largest)\n\ndef max_heapify(arr: List[int]) -> List[int]:\n n = len(arr)\n\n # Build a max heap\n for i in range(n // 2 - 1, -1, -1):\n heapify(arr, n, i)\n\n return arr","test":"METADATA = {\n 'author': 'ay',\n 'dataset': 'test'\n}\n\n\ndef check(candidate):\n input_data1 = [1, 3, 5, 4, 6, 13, 10, 9, 8, 15, 17]\n assert candidate(input_data1) == [17, 15, 13, 9, 6, 5, 10, 4, 8, 3, 1]\n input_data2 = [10, 5, 7, 2, 1, 8, 3, 6, 9, 4]\n assert candidate(input_data2) == [10, 9, 8, 6, 4, 7, 3, 5, 2, 1]\n input_data3 = [20, 15, 10, 5, 12, 14, 18, 8, 7, 2, 3, 1]\n assert candidate(input_data3) == [20, 15, 18, 8, 12, 14, 10, 5, 7, 2, 3, 1]\n input_data4 = [25, 30, 40, 20, 10, 35, 18, 15, 12, 8, 5]\n assert candidate(input_data4) == [40, 30, 35, 20, 10, 25, 18, 15, 12, 8, 5]"} { "task_id": "PythonSaga/116","prompt":"from typing import List\ndef lenght_of_rope(n:int, arr: List[int]) -> int:\n \"\"\"There are given N ropes of different lengths, we need to connect these ropes into one rope. \n The cost to connect two ropes is equal to sum of their lengths. \n The task is to connect the ropes with minimum cost. \n Take number of ropes and their lengths as input from user and print the minimum cost. \n Use heap concept to solve this problem.\n\n Example: \n Input: 4, [5, 4, 3, 7]\n Output: 38\n Input: 3, [1, 2, 3]\n Output: 9\"\"\"","entry_point":"lenght_of_rope","canonical_solution":"# Initialize min heap with rope lengths\nheapq.heapify(arr)\n\ntotal_cost = 0 # Initialize total cost\n\n# Keep connecting ropes until only one is left\nwhile len(arr) > 1:\n # Extract the two smallest ropes\n first = heapq.heappop(arr)\n second = heapq.heappop(arr)\n\n # Connect them\n connected_rope = first + second\n\n # Add the cost\n total_cost += connected_rope\n\n # Put the resulting rope back into the heap\n heapq.heappush(arr, connected_rope)\n\nreturn total_cost","test":"METADATA = {\n 'author': 'ay',\n 'dataset': 'test'\n}\n\n\ndef check(candidate):\n # Test Case 1:\n input_data1 = 4, [5, 4, 3, 7]\n assert candidate(*input_data1) == 38\n\n # Test Case 2:\n input_data2 = 3, [1, 2, 3]\n assert candidate(*input_data2) == 9\n\n # Test Case 3:\n input_data3 = 5, [10, 2, 8, 5, 4]\n assert candidate(*input_data3) == 64\n\n # Test Case 4:\n input_data4 = 2, [1, 5]\n assert candidate(*input_data4) == 6"} { "task_id": "PythonSaga/117","prompt":"def rearrange(s: str) -> bool:\n \"\"\"I have a word/string which has repeated characters. \n I want to rearrange the word such that no two same characters are adjacent to each other. \n If no such arrangement is possible, then return False, else return true. \n Take string as input from user. \n Use heap concept to solve this problem. \n\n Example 1: \n Input: 'aaabc' \n Output: True \n Input: 'aa' \n Output: False \"\"\"","entry_point":"rearrange","canonical_solution":"char_freq = {}\n\n# Count the frequency of each character in the string\nfor char in s:\n char_freq[char] = char_freq.get(char, 0) + 1\n\n# Create a max heap based on negative frequencies\nmax_heap = [(-freq, char) for char, freq in char_freq.items()]\nheapq.heapify(max_heap)\n\nresult = []\n\nwhile len(max_heap) > 1:\n # Extract the two most frequent characters\n freq1, char1 = heapq.heappop(max_heap)\n freq2, char2 = heapq.heappop(max_heap)\n\n # Append the characters to the result\n result.extend([char1, char2])\n\n # Decrement the frequencies and push back into the heap if the frequency is not zero\n if freq1 + 1 != 0:\n heapq.heappush(max_heap, (freq1 + 1, char1))\n if freq2 + 1 != 0:\n heapq.heappush(max_heap, (freq2 + 1, char2))\n\n# If there is only one character left, append it to the result\nif max_heap:\n result.append(max_heap[0][1])\n\n# Check if the result is a valid rearrangement\nreturn len(result) == len(s)","test":"METADATA = {\n 'author': 'ay',\n 'dataset': 'test'\n}\n\n\ndef check(candidate):\n # Test Case 1:\n input_data1 = 'aaabc'\n assert candidate(input_data1) == True\n\n # Test Case 2:\n input_data2 = 'aa'\n assert candidate(input_data2) == False\n\n # Test Case 3:\n input_data3 = 'aabbccc'\n assert candidate(input_data3) == True\n\n # Test Case 4:\n input_data4 = 'abcde'\n assert candidate(input_data4) == True"} { "task_id": "PythonSaga/118","prompt":"from typing import Dict\n\ndef huff_encode(n:int, d:Dict) -> Dict:\n \"\"\"I need to implement huffman coding for input characters based on their frequency. \n Take input for characters and their frequency from user. and then encode them using huffman coding. \n Example:\n Input: 6, {'a': 5, 'b': 9, 'c': 12, 'd': 13, 'e': 16, 'f': 45}\n Output: {'a': '1100', 'b': '1101', 'c': '100', 'd': '101', 'e': '111', 'f': '0'} \n \"\"\"","entry_point":"huff_encode","canonical_solution":"class Node:\n def __init__(self, char, freq):\n self.char = char\n self.freq = freq\n self.left = None\n self.right = None\n\n def __lt__(self, other):\n return self.freq < other.freq\n\ndef build_huffman_tree(freq_dict):\n min_heap = [Node(char, freq) for char, freq in freq_dict.items()]\n heapq.heapify(min_heap)\n\n while len(min_heap) > 1:\n left = heapq.heappop(min_heap)\n right = heapq.heappop(min_heap)\n\n merged_node = Node(None, left.freq + right.freq)\n merged_node.left = left\n merged_node.right = right\n\n heapq.heappush(min_heap, merged_node)\n\n return min_heap[0]\n\ndef generate_huffman_codes(root, code=\"\", huff_codes=None):\n if huff_codes is None:\n huff_codes = {}\n\n if root:\n if not root.left and not root.right:\n huff_codes[root.char] = code\n generate_huffman_codes(root.left, code + \"0\", huff_codes)\n generate_huffman_codes(root.right, code + \"1\", huff_codes)\n\ndef huff_encode(n: int, d: Dict) -> Dict:\n if n < 2:\n return {}\n\n # Build the Huffman tree\n root = build_huffman_tree(d)\n\n # Generate Huffman codes\n huff_codes = {}\n generate_huffman_codes(root, \"\", huff_codes)\n\n return huff_codes","test":"METADATA = {\n 'author': 'ay',\n 'dataset': 'test'\n}\n\n\ndef check(candidate):\n # Test Case 1:\n input_data1 = 6, {'a': 5, 'b': 9, 'c': 12, 'd': 13, 'e': 16, 'f': 45}\n assert candidate(*input_data1) == {'f': '0', 'c': '100', 'd': '101', 'a': '1100', 'b': '1101', 'e': '111'}\n\n # Test Case 2:\n input_data2 = 4, {'x': 2, 'y': 2, 'z': 2, 'w': 2}\n assert candidate(*input_data2) == {'z': '00', 'x': '01', 'w': '10', 'y': '11'}\n\n # Test Case 3:\n input_data3 = 3, {'p': 1, 'q': 2, 'r': 3}\n assert candidate(*input_data3) == {'r': '0', 'p': '10', 'q': '11'}\n\n # Test Case 4:\n input_data4 = 2, {'A': 10, 'B': 20}\n assert candidate(*input_data4) == {'A': '0', 'B': '1'}"} { "task_id": "PythonSaga/119","prompt":"from typing import List\ndef merge_lists(n:int, lists:List[List[int]]) -> List[int]:\n \"\"\"Take k sorted lists of size N and merge them into one sorted list. You can use a heap to solve this problem. \n Take input from the user for the number of lists and the elements of the lists. \n\n Example:\n Input: 3, [[1, 3, 5, 7], [2, 4, 6, 8], [0, 9, 10, 11]]\n Output: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ,10, 11]\"\"\"","entry_point":"merge_lists","canonical_solution":"result = []\nmin_heap = []\n\n# Initialize the heap with the first element from each list along with the list index\nfor i, lst in enumerate(lists):\n if lst:\n heapq.heappush(min_heap, (lst[0], i, 0))\n\nwhile min_heap:\n val, list_index, index_in_list = heapq.heappop(min_heap)\n result.append(val)\n\n # Move to the next element in the same list\n if index_in_list + 1 < len(lists[list_index]):\n heapq.heappush(min_heap, (lists[list_index][index_in_list + 1], list_index, index_in_list + 1))\n\nreturn result","test":"METADATA = {\n 'author': 'ay',\n 'dataset': 'test'\n}\n\n\ndef check(candidate):\n # Test Case 1:\n input_data1 = 3, [[1, 3, 5, 7], [2, 4, 6, 8], [0, 9, 10, 11]]\n assert candidate(*input_data1) == [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]\n\n # Test Case 2:\n input_data2 = 2, [[-1, 0, 2, 4], [3, 5, 6, 8]]\n assert candidate(*input_data2) == [-1, 0, 2, 3, 4, 5, 6, 8]\n\n # Test Case 3:\n input_data3 = 4, [[10, 15, 20, 25], [1, 5, 7, 30], [4, 8, 11, 13], [3, 6, 9, 12]]\n assert candidate(*input_data3) == [1, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 15, 20, 25, 30]\n\n # Test Case 4:\n input_data4 = 3, [[], [2, 4, 6, 8], [0, 9, 10, 11]]\n assert candidate(*input_data4) == [0, 2, 4, 6, 8, 9, 10, 11]"} { "task_id": "PythonSaga/120","prompt":"from typing import List \ndef autoComplete(words: List[str], word: str) -> List[str]:\n \"\"\"I came to know that auto complete feature while typing is performed using Trie data structure. \n Do a task where take a input of multiple words from user and a word to be completed. Return all the words that can be completed using the given word. \n Example: \n Input: ['hello', 'hell', 'hi', 'how', 'are', 'you', 'hero', 'hey'], 'he'\n Output: ['hello', 'hell', 'hero', 'hey'] \"\"\"","entry_point":"autoComplete","canonical_solution":"class TrieNode:\n def __init__(self):\n self.children = {}\n self.is_end_of_word = False\n\ndef insert_word(root, word):\n node = root\n for char in word:\n if char not in node.children:\n node.children[char] = TrieNode()\n node = node.children[char]\n node.is_end_of_word = True\n\ndef search_prefix(root, prefix):\n node = root\n for char in prefix:\n if char not in node.children:\n return []\n node = node.children[char]\n\n suggestions = []\n traverse_trie(node, prefix, suggestions)\n return suggestions\n\ndef traverse_trie(node, current_word, suggestions):\n if node.is_end_of_word:\n suggestions.append(current_word)\n\n for char, child_node in node.children.items():\n traverse_trie(child_node, current_word + char, suggestions)\n\ndef autoComplete(words: List[str], word: str) -> List[str]:\n root = TrieNode()\n\n for w in words:\n insert_word(root, w)\n\n suggestions = search_prefix(root, word)\n return suggestions","test":"METADATA = {\n 'author': 'ay',\n 'dataset': 'test'\n}\n\n\ndef check(candidate):\n # Test Case 1:\n input_words1 = ['hello', 'hell', 'hi', 'how', 'are', 'you', 'hero', 'hey']\n input_word1 = 'he'\n assert candidate(input_words1, input_word1) == ['hello', 'hell', 'hero', 'hey']\n\n # Test Case 2:\n input_words2 = ['apple', 'apricot', 'banana', 'apex', 'apologize', 'apartment']\n input_word2 = 'ap'\n assert candidate(input_words2, input_word2) == ['apple', 'apricot', 'apex', 'apologize', 'apartment']\n\n # Test Case 3:\n input_words3 = ['python', 'programming', 'pyramid', 'pyro', 'pyrite', 'puzzle']\n input_word3 = 'py'\n assert candidate(input_words3, input_word3) == ['python', 'programming', 'pyramid', 'pyro', 'pyrite']\n\n # Test Case 4:\n input_words4 = ['car', 'cat', 'cart', 'caramel', 'cabbage', 'camera']\n input_word4 = 'ca'\n assert candidate(input_words4, input_word4) == ['car', 'cat', 'cart', 'caramel', 'cabbage', 'camera']"} { "task_id": "PythonSaga/121","prompt":"from typing import List\ndef rename_cities(cities: List[str]) -> List[str]:\n \"\"\"Some cities are going to be renamed and accordingly name of their railway stations will also change. \n Changing the name of railway station should also result in changed station code. \n Railways have an idea that station code should be the shortest prefix out of all railway stations renamed prior to this. \n If some city has same name, then prefix will be the name with suffix as the count of occurence of that city prior to this and including this, seperated with spaces. \n Take a name of city as input from user and print the station code as output. \n Example 1: \n Input: ['Delhi', 'Mumbai', 'Chennai', 'Kolkata', 'Dehradun', 'Delhi']\n Output: ['D', 'M', 'C', 'K', 'Deh', 'Delhi2] \"\"\"\n ","entry_point":"rename_cities","canonical_solution":"city_count = {} # Tracks the count of each city\nused_codes = set() # Tracks all used codes to ensure uniqueness\ncodes = [] # Stores the resulting station codes\n\nfor city in cities:\n # Increment the city count or initialize it\n city_count[city] = city_count.get(city, 0) + 1\n\n if city_count[city] == 1:\n # For the first occurrence, find a unique prefix\n prefix = \"\"\n for i in range(1, len(city) + 1):\n prefix = city[:i]\n if prefix not in used_codes:\n break\n codes.append(prefix)\n used_codes.add(prefix)\n else:\n # For subsequent occurrences, use the full name with a count\n code = f\"{city}{city_count[city]}\"\n codes.append(code)\n used_codes.add(code)\n\nreturn codes","test":"METADATA = {\n 'author': 'ay',\n 'dataset': 'test'\n}\n\n\ndef check(candidate):\n # Test Case 1:\n input_cities1 = ['Delhi', 'Mumbai', 'Chennai', 'Kolkata', 'Dehradun', 'Delhi']\n assert candidate(input_cities1) == ['D', 'M', 'C', 'K', 'Deh', 'Delhi2']\n\n # Test Case 2:\n input_cities2 = ['Shimla', 'Safari', 'Jammu', 'Delhi', 'Jammu', 'Dehradun']\n assert candidate(input_cities2) == ['S', 'Sa', 'J', 'D', 'Jammu2', 'Deh']\n\n # Test Case 3:\n input_cities3 = ['NewYork', 'NewDelhi', 'NewJersey', 'NewYork', 'NewJersey', 'NewDelhi']\n assert candidate(input_cities3) == ['N', 'NewD', 'NewJ', 'NewYork2', 'NewJersey2', 'NewDelhi2']\n\n # Test Case 4:\n input_cities4 = ['Tokyo', 'Osaka', 'Kyoto', 'Tokyo', 'Kyoto', 'Osaka', 'Kyoto']\n assert candidate(input_cities4) == ['T', 'O', 'K', 'Tokyo2', 'Kyoto2', 'Osaka2', 'Kyoto3']"} { "task_id": "PythonSaga/122","prompt":"from typing import List\ndef max_xor(nums: List[int]) -> int:\n \"\"\"Given the sequence of number in a list. \n choose the subsequence of number in the list such that Bitwise Xor of all the elements in the subsequence is maximum possible. \n Try to use trie data structure to solve this problem. \n Take list as input from user and return the maximum possible value of Bitwise Xor of all the elements in the subsequence. \n\n Example:\n Input: [8, 1, 2, 12]\n Output: 14\n Input: [1, 2, 3, 4]\n Output: 7\"\"\"","entry_point":"max_xor","canonical_solution":"class TrieNode:\n def __init__(self):\n self.children = {}\n\ndef insert(num, root):\n node = root\n for i in range(31, -1, -1):\n bit = (num >> i) & 1\n if bit not in node.children:\n node.children[bit] = TrieNode()\n node = node.children[bit]\n\ndef find_max_xor(nums, root):\n max_xor = float('-inf')\n for num in nums:\n current_xor = 0\n node = root\n for i in range(31, -1, -1):\n bit = (num >> i) & 1\n opposite_bit = 1 - bit\n if opposite_bit in node.children:\n current_xor |= (1 << i)\n node = node.children[opposite_bit]\n else:\n node = node.children[bit]\n max_xor = max(max_xor, current_xor)\n return max_xor\n\ndef max_xor(nums: List[int]) -> int:\n root = TrieNode()\n for num in nums:\n insert(num, root)\n return find_max_xor(nums, root)","test":"METADATA = {\n 'author': 'ay',\n 'dataset': 'test'\n}\n\n\ndef check(candidate):\n # Test Case 1:\n input_nums1 = [8, 1, 2, 12]\n assert candidate(input_nums1) == 14\n\n # Test Case 2:\n input_nums2 = [1, 2, 3, 4]\n assert candidate(input_nums2) == 7\n\n # Test Case 3:\n input_nums3 = [5, 10, 15, 20, 25]\n assert candidate(input_nums3) == 30\n\n # Test Case 4:\n input_nums4 = [7, 3, 5, 2, 10, 8]\n assert candidate(input_nums4) == 15"} { "task_id": "PythonSaga/123","prompt":"from typing import List\ndef pal_pairs(words: List[str]) -> List[List[str]]:\n \"\"\"Given a list of words, return a list of all possible palindrome pairs.\n A palindrome pair is a pair of words that when concatenated, the result is a palindrome.\n Take a list of words as input from user and return a list of palindrome pairs.\n \n Example:\n Input: ['code', 'edoc', 'da', 'd']\n Output: [['code', 'edoc'], ['edoc', 'code'], ['da', 'd']]\n Input: ['abcd','dcba','lls','s','sssll']\n Output: [['abcd', 'dcba'], ['dcba', 'abcd'], ['lls', 'sssll'], ['s', 'lls']]\"\"\"","entry_point":"pal_pairs","canonical_solution":"def is_palindrome(word):\n return word == word[::-1]\n\ndef pal_pairs(words: List[str]) -> List[List[str]]:\n result = []\n word_set = set(words)\n\n for i in range(len(words)):\n for j in range(len(words)):\n if i != j:\n concat_word = words[i] + words[j]\n if is_palindrome(concat_word):\n result.append([words[i], words[j]])\n\n return result","test":"METADATA = {\n 'author': 'ay',\n 'dataset': 'test'\n}\n\n\ndef check(candidate):\n # Test Case 1:\n input_words1 = ['code', 'edoc', 'da', 'd']\n assert candidate(input_words1) == [['code', 'edoc'], ['da', 'd']]\n\n # Test Case 2:\n input_words2 = ['abcd', 'dcba', 'lls', 's', 'sssll']\n assert candidate(input_words2) == [['dcba', 'abcd'], ['s', 'lls'], ['sssll', 'lls']]\n\n # Test Case 3:\n input_words3 = ['race', 'car', 'level', 'deified', 'python']\n assert candidate(input_words3) == [['race', 'car'], ['level', 'deified']]\n\n # Test Case 4:\n input_words4 = ['bat', 'tab', 'noon', 'moon', 'hello']\n assert candidate(input_words4) == [['bat', 'tab'], ['noon', 'moon']]"} { "task_id": "PythonSaga/124","prompt":"from typing import List\ndef cross_words(n:int, m:int, board: List[List[str]], words: List[str]) -> List[str]:\n \"\"\"Given an m x n board of characters and a list of strings words, return all words on the board. \n Each word must be constructed from letters of sequentially adjacent cells, where adjacent cells are horizontally or vertically neighboring. \n The same letter cell may not be used more than once in a word. \n Take a matrix and a list of words as input from user and print all the words that can be formed from the matrix. \n\n Example 1: \n Input: 4,4,[[o,a,a,n],[e,t,a,e],[i,h,k,r],[i,f,l,v]],['oath','pea','eat','rain'] # row, col, matrix, words\n Output: ['oath','eat']\"\"\"","entry_point":"cross_words","canonical_solution":"def is_valid(board, visited, row, col):\n return 0 <= row < len(board) and 0 <= col < len(board[0]) and not visited[row][col]\n\ndef dfs(board, visited, row, col, current_word, trie, result):\n if '#' in trie:\n result.append(current_word)\n trie['#'] = None # Mark the word as found in the trie\n\n directions = [(0, 1), (1, 0), (0, -1), (-1, 0)]\n\n for dr, dc in directions:\n new_row, new_col = row + dr, col + dc\n if is_valid(board, visited, new_row, new_col) and board[new_row][new_col] in trie:\n visited[new_row][new_col] = True\n dfs(board, visited, new_row, new_col, current_word + board[new_row][new_col], trie[board[new_row][new_col]], result)\n visited[new_row][new_col] = False\n\ndef build_trie(words):\n trie = {}\n for word in words:\n node = trie\n for char in word:\n node = node.setdefault(char, {})\n node['#'] = None\n return trie\n\ndef find_words(board, words):\n trie = build_trie(words)\n result = []\n visited = [[False] * len(board[0]) for _ in range(len(board))]\n\n for i in range(len(board)):\n for j in range(len(board[0])):\n if board[i][j] in trie:\n visited[i][j] = True\n dfs(board, visited, i, j, board[i][j], trie[board[i][j]], result)\n visited[i][j] = False\n\n return result\n\ndef cross_words(n:int, m:int, board: List[List[str]], words: List[str]) -> List[str]:\n return find_words(board, words)","test":"METADATA = {\n 'author': 'ay',\n 'dataset': 'test'\n}\n\n\ndef check(candidate):\n # Test Case 1:\n input_board1 = [['o','a','a','n'],['e','t','a','e'],['i','h','k','r'],['i','f','l','v']]\n input_words1 = ['oath', 'pea', 'eat', 'rain']\n assert candidate(4, 4, input_board1, input_words1) == ['oath', 'eat']\n\n # Test Case 2:\n input_board2 = [['a','b'],['c','d']]\n input_words2 = ['ab', 'cb', 'ad', 'bd', 'ac', 'ca', 'da', 'cd', 'dc']\n assert candidate(2, 2, input_board2, input_words2) == ['ab', 'ac', 'bd', 'cd', 'ca', 'dc']\n\n # Test Case 3:\n input_board3 = [['a','b','c'],['d','e','f'],['g','h','i']]\n input_words3 = ['abc', 'def', 'ghi', 'cfh', 'dea']\n assert candidate(3, 3, input_board3, input_words3) == ['abc', 'def', 'ghi']\n\n # Test Case 4:\n input_board4 = [['a','b','c'],['d','e','f'],['g','h','i']]\n input_words4 = ['abcfedghi']\n assert candidate(3, 3, input_board4, input_words4) == ['abcfedghi']"} { "task_id": "PythonSaga/125","prompt":"from typing import List\ndef max_profit(n:int, items: List[List[int]], capacity: int) -> int:\n \"\"\"Given a list of items and a capacity, return the maximum value of the transferred items.\n Each item is a list of [value, weight].\n The item can be broken into fractions to maximize the value of the transferred items.\n Take input from the user for n items and the capacity of the bag. and return the maximum value of the transferred items.\n \n Example:\n Input: 3, [[60, 10], [100, 20], [120, 30]], 50\n Output: 240\n Input: 2, [[60, 10], [100, 20]], 50\n Output: 160\"\"\"","entry_point":"max_profit","canonical_solution":"# Calculate value per unit weight for each item and store it along with the item\nitems_with_ratio = [(item[0] / item[1], item[0], item[1]) for item in items] # (value/weight, value, weight)\n\n# Sort the items by value per unit weight in descending order\nitems_with_ratio.sort(reverse=True)\n\nmax_value = 0 # Maximum value of the transferred items\nfor ratio, value, weight in items_with_ratio:\n if capacity >= weight:\n # If the knapsack can carry the entire item, take all of it\n max_value += value\n capacity -= weight\n else:\n # If the knapsack cannot carry the entire item, take the fractional part\n max_value += ratio * capacity\n break # The knapsack is now full\n\nreturn max_value","test":"METADATA = {\n 'author': 'ay',\n 'dataset': 'test'\n}\n\n\ndef check(candidate):\n # Test Case 1:\n input_items1 = [[60, 10], [100, 20], [120, 30]]\n input_capacity1 = 50\n assert candidate(3, input_items1, input_capacity1) == 240\n\n # Test Case 2:\n input_items2 = [[60, -10], [100, 20]]\n input_capacity2 = 50\n assert candidate(2, input_items2, input_capacity2) == 30\n\n # Test Case 3:\n input_items3 = [[40, 10], [30, 5], [50, 15]]\n input_capacity3 = 20\n assert candidate(3, input_items3, input_capacity3) == 87\n\n # Test Case 4:\n input_items4 = [[25, 7], [15, 5], [30, 10], [10, 2], [5, 1]]\n input_capacity4 = 15\n assert candidate(5, input_items4, input_capacity4) == 55"} { "task_id": "PythonSaga/126","prompt":"from typing import List\ndef max_prof(n: int, jobs: List[List[int]]) -> List[int]:\n \"\"\"I want to sequence the job in such a way that my profit is maximized by the end of time. \n let say i'm given N jobs with their deadline and profit. \n I need to find the sequence of jobs that will maximize my profit. \n Each job takes 1 unit of time to complete and only one job can be scheduled at a time. \n 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. \n Example: \n Input: 4, [[4, 20], [1, 10], [1, 40], [1, 30]]\n Output: [60, 2]\"\"\"\n","entry_point":"max_prof","canonical_solution":"# Sort jobs by profit in descending order\njobs.sort(key=lambda x: x[1], reverse=True)\n\n# Initialize variables\nmax_deadline = max(job[0] for job in jobs) # Find the maximum deadline\nslots = [False] * max_deadline # To keep track of occupied time slots\njob_count = 0 # To count the number of jobs done\ntotal_profit = 0 # To calculate the total profit\n\n# Schedule jobs\nfor deadline, profit in jobs:\n for slot in range(min(deadline, max_deadline) - 1, -1, -1):\n if not slots[slot]: # If the slot is free\n slots[slot] = True # Mark the slot as occupied\n job_count += 1 # Increment the job count\n total_profit += profit # Add the profit\n break # Break after scheduling the job\n\nreturn [total_profit, job_count]","test":"METADATA = {\n 'author': 'ay',\n 'dataset': 'test'\n}\n\n\ndef check(candidate):\n # Test Case 1:\n input_jobs1 = [[4, 20], [1, 10], [1, 40], [1, 30]]\n assert candidate(4, input_jobs1) == [60, 2]\n\n # Test Case 2:\n input_jobs2 = [[2, 30], [3, 40], [4, 50], [5, 60]]\n assert candidate(4, input_jobs2) == [180, 4]\n\n # Test Case 3:\n input_jobs3 = [[1, 10], [2, 15], [3, 5], [1, 30], [4, 25]]\n assert candidate(5, input_jobs3) == [75, 4]\n\n # Test Case 4:\n input_jobs4 = [[1, 5], [2, 10], [3, 15], [4, 20], [5, 25]]\n assert candidate(5, input_jobs4) == [75, 5]"} { "task_id": "PythonSaga/127","prompt":"from typing import List\n\ndef min_cost(length: int, width: int, cost: List[List[int]]) -> int:\n \"\"\"I have a big piece of granite tile that I want to cut into squares. \n 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. \n 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. \n Take input from user p, q and cost of breaking each edge both horizontal and vertical. and return the minimum cost of cutting. \n\n Example: \n Input: 6, 4, [[2, 1, 3, 1, 4], [4, 1, 2]]\n Output: 42\"\"\"\n","entry_point":"min_cost","canonical_solution":"# Separate the horizontal and vertical costs\nhorizontal_cuts = cost[0]\nvertical_cuts = cost[1]\n\n# Add a marker to distinguish between horizontal and vertical cuts\nhorizontal_cuts = [(c, 'h') for c in horizontal_cuts]\nvertical_cuts = [(c, 'v') for c in vertical_cuts]\n\n# Combine and sort all cuts by cost in descending order\nall_cuts = sorted(horizontal_cuts + vertical_cuts, key=lambda x: x[0], reverse=True)\n\n# Initialize the number of segments in each direction\nhorizontal_segments = 1\nvertical_segments = 1\n\ntotal_cost = 0\nfor cost, cut_type in all_cuts:\n if cut_type == 'h':\n # The cost of a horizontal cut is multiplied by the current number of vertical segments\n total_cost += cost * vertical_segments\n horizontal_segments += 1\n else:\n # The cost of a vertical cut is multiplied by the current number of horizontal segments\n total_cost += cost * horizontal_segments\n vertical_segments += 1\n\nreturn total_cost","test":"METADATA = {'author': 'ay', 'dataset': 'test'}\n\ndef check(candidate):\n length1, width1 = 6, 4\n cost1 = [[2, 1, 3, 1, 4], [4, 1, 2]]\n assert candidate(length1, width1, cost1) == 42\n\n length3, width3 = 4, 4\n cost3 = [[1, 1, 1], [1, 1, 1]]\n assert candidate(length3, width3, cost3) == 15"} { "task_id": "PythonSaga/128","prompt":"from typing import List\n\ndef equal_ele(nums: List[int], k: int) -> int:\n \"\"\"User provides list of number and value X. \n We have to find the maximum number of equal elements possible for the list \n just by increasing the elements of the list by incrementing a total of atmost k. \n Take input from user for list of numbers and value X and return the maximum number of equal elements possible for the list. \n Example: \n\n Input: [5, 5, 3, 1], 5\n Output: 3\n Input: [2, 4, 9], 3\n Output: 2\"\"\"\n","entry_point":"equal_ele","canonical_solution":"nums.sort() # Step 1: Sort the list\nmax_equal = 1 # To keep track of the maximum number of equal elements\nj = 0 # Start of the sliding window\n\nfor i in range(len(nums)):\n # Step 3: Calculate the total increments needed for the current window\n while nums[i] * (i - j + 1) - sum(nums[j:i + 1]) > k:\n j += 1 # Slide the window forward if the total increments exceed k\n \n # Step 4: Update the maximum number of equal elements\n max_equal = max(max_equal, i - j + 1)\n\nreturn max_equal","test":"METADATA = {'author': 'ay', 'dataset': 'test'}\n\ndef check(candidate):\n # Test Case 1:\n nums1, k1 = [5, 5, 3, 1], 5\n assert candidate(nums1, k1) == 3\n\n # Test Case 2:\n nums2, k2 = [2, 4, 9], 3\n assert candidate(nums2, k2) == 2\n\n # Test Case 3:\n nums3, k3 = [1, 2, 3, 4, 5], 3\n assert candidate(nums3, k3) == 1\n\n # Test Case 4:\n nums4, k4 = [10, 10, 10, 10, 10], 2\n assert candidate(nums4, k4) == 5"} { "task_id": "PythonSaga/129","prompt":"def max_palindrom(num: str) -> str:\n \"\"\"My friend say there's always some possibliy to make any given number into palindrome by permutation of its digits. \n 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'. \n Example: \n Input: '313515'\n Output: '531135'\n Input: '123'\n Output: 'not possible'\"\"\"\n","entry_point":"max_palindrom","canonical_solution":"# Count the frequency of each digit\ndigit_count = [0] * 10\nfor digit in num:\n digit_count[int(digit)] += 1\n\n# Build the left half of the palindrome\nleft_half = []\nmiddle_digit = \"\"\nfor digit in range(9, -1, -1):\n count = digit_count[digit]\n\n if count % 2 != 0:\n if middle_digit:\n return \"not possible\"\n middle_digit = str(digit)\n count -= 1\n\n left_half.extend([str(digit)] * (count // 2))\n\n# Build the right half by reversing the left half\nright_half = left_half[::-1]\n\n# Combine the left half, middle digit (if any), and the right half\npalindrome = \"\".join(left_half + [middle_digit] + right_half)\n\nreturn palindrome","test":"METADATA = {'author': 'ay', 'dataset': 'test'}\n\ndef check(candidate):\n # Test Case 1:\n num1 = '313515'\n assert candidate(num1) == '531135'\n\n # Test Case 2:\n num2 = '123'\n assert candidate(num2) == 'not possible'\n\n # Test Case 3:\n num3 = '1223333'\n assert candidate(num3) == '3321233'\n\n # Test Case 4:\n num4 = '999977755533211'\n assert candidate(num4) == 'not possible'"} { "task_id": "PythonSaga/130","prompt":"from typing import List\n\ndef path(n: int, maze: List[List[int]]) -> List[List[int]]:\n \"\"\"I came to know about a very interesting topic known as backtracking. \n So, my friend gave me a problem to solve using backtracking. \n Let's say I have a maze and I have to find the path from source to destination. \n 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. \n 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. \n Take input from the user for n and the maze matrix and print the path from source to destination. \n Example: \n Input: 4,[[1,0,0,0],[1,1,0,1],[0,1,0,1],[1,1,1,1]]\n Output: [[1,0,0,0],[1,1,0,0],[0,1,0,0],[0,1,1,1]]\"\"\"\n","entry_point":"path","canonical_solution":"def solve_maze(maze, x, y, solution, n):\n # Base Case: If x, y is the destination, return True\n if x == n - 1 and y == n - 1 and maze[x][y] == 1:\n solution[x][y] = 1\n return True\n \n # Check if maze[x][y] is a valid move\n if 0 <= x < n and 0 <= y < n and maze[x][y] == 1:\n # Mark x, y as part of the solution path\n solution[x][y] = 1\n \n # Move Right\n if solve_maze(maze, x + 1, y, solution, n):\n return True\n \n # Move Down\n if solve_maze(maze, x, y + 1, solution, n):\n return True\n \n # If neither move right nor move down works, backtrack\n solution[x][y] = 0\n return False\n\n return False\n\ndef path(n: int, maze: List[List[int]]) -> List[List[int]]:\n # Initialize solution matrix with 0s\n solution = [[0 for _ in range(n)] for _ in range(n)]\n \n if not solve_maze(maze, 0, 0, solution, n):\n return \"No path exists\"\n \n return solution","test":"METADATA = {'author': 'ay', 'dataset': 'test'}\n\ndef check(candidate):\n n1 = 4\n maze1 = [[1, 0, 0, 0], [1, 1, 0, 1], [0, 1, 0, 1], [1, 1, 1, 1]]\n assert candidate(n1, maze1) == [[1, 0, 0, 0], [1, 1, 0, 0], [0, 1, 0, 0], [0, 1, 1, 1]]\n n2 = 3\n maze2 = [[1, 0, 0], [1, 1, 1], [0, 0, 1]]\n assert candidate(n2, maze2) == [[1, 0, 0], [1, 1, 1], [0, 0, 1]]\n n3 = 5\n maze3 = [[1, 0, 0, 0, 0], [1, 1, 1, 0, 1], [0, 1, 0, 1, 1], [1, 1, 1, 1, 1], [0, 0, 0, 1, 1]]\n assert candidate(n3, maze3) == [[1, 0, 0, 0, 0], [1, 1, 0, 0, 0], [0, 1, 0, 0, 0], [1, 1, 1, 1, 0], [0, 0, 0, 1, 1]]\n n4 = 2\n maze4 = [[1, 1], [0, 1]]\n assert candidate(n4, maze4) == [[1, 1], [0, 1]]"} { "task_id": "PythonSaga/131","prompt":"def big_number(num: str, swaps: int) -> str:\n \"\"\"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. \n I have to print the maximum value of the number after swapping the digits at most X times. \n 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. \n Example 1: \n Input: '1234567', 4\n Output: '7654321'\n Input: '3435335', 3\n Output: '5543333'\"\"\"\n","entry_point":"big_number","canonical_solution":"# Convert the string to a list of digits for easier manipulation\nnum_list = list(num)\n\ni = 0\nwhile swaps > 0 and i < len(num_list) - 1:\n max_digit_index = i\n # Find the maximum digit in the remaining part of the number\n for j in range(i + 1, len(num_list)):\n if num_list[j] > num_list[max_digit_index]:\n max_digit_index = j\n \n # If the maximum digit is different from the current digit, perform the swap\n if max_digit_index != i:\n num_list[i], num_list[max_digit_index] = num_list[max_digit_index], num_list[i]\n swaps -= 1\n \n i += 1\n\n# Convert the list back to a string\nresult = ''.join(num_list)\nreturn result","test":"METADATA = {'author': 'ay', 'dataset': 'test'}\n\ndef check(candidate):\n assert candidate('1234567', 4) == '7654321'\n assert candidate('3435335', 3) == '5543333'\n assert candidate('987654321', 5) == '987654321'\n assert candidate('102233', 2) == '332210'"} { "task_id": "PythonSaga/132","prompt":"from typing import List\n\ndef graph_colooring(n: int, m: int, e: int, edges: List[List[int]]) -> bool:\n \"\"\"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 \n such that no two adjacent vertices of the graph are colored with the same color. \n Here coloring of a graph means the assignment of colors to all vertices. \n Print 1 if it is possible to color vertices and 0 otherwise. \n 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. \n Example 1: \n Input: 4,3,5,[[0,1],[1,2],[1,3],[2,3],[3,0],[0,2]]\n Output: 1\"\"\"\n","entry_point":"graph_colooring","canonical_solution":"","test":"METADATA = {'author': 'ay', 'dataset': 'test'}\n\ndef check(candidate):\n assert candidate(4, 3, 5, [[0, 1], [1, 2], [1, 3], [2, 3], [3, 0], [0, 2]]) == 1\n assert candidate(3, 2, 3, [[0, 1], [1, 2], [2, 0]]) == 0\n assert candidate(5, 3, 7, [[0, 1], [0, 2], [1, 2], [1, 3], [2, 4], [3, 4], [4, 0]]) == 1\n assert candidate(6, 2, 7, [[0, 1], [1, 2], [2, 3], [3, 4], [4, 5], [5, 0], [0, 3]]) == 1"} { "task_id": "PythonSaga/133","prompt":"def additive_number(num: str) -> str:\n \"\"\"By tossing a number at me, my teacher asked to tell whether it is additive or not.\n An additive number is a string whose digits can form an additive sequence.\n A valid additive sequence should contain at least three numbers. Except for the first two numbers,\n each subsequent number in the sequence must be the sum of the preceding two.\n 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'.\n Example:\n Input: '112358'\n Output: 'It is an additive number'\n Input: '199100199'\n Output: 'It is an additive number'\"\"\"\n","entry_point":"additive_number","canonical_solution":"def additive_number(num: str) -> str:\n def is_additive(s, num1, num2):\n while s:\n num_sum = str(int(num1) + int(num2))\n if not s.startswith(num_sum):\n return False\n s = s[len(num_sum):]\n num1, num2 = num2, num_sum\n return True\n\n n = len(num)\n for i in range(1, n // 2 + 1):\n for j in range(i + 1, n):\n num1, num2 = num[:i], num[i:j]\n if (len(num1) > 1 and num1[0] == '0') or (len(num2) > 1 and num2[0] == '0'):\n continue\n if is_additive(num[j:], num1, num2):\n return \"It is an additive number\"\n\n return \"It is not an additive number\"","test":"METADATA = {'author': 'ay', 'dataset': 'test'}\n\ndef check(candidate):\n assert candidate('112358') == 'It is an additive number'\n assert candidate('199100199') == 'It is an additive number'\n assert candidate('123456') == 'It is not an additive number'\n assert candidate('111222333') == 'It is an additive number'"} { "task_id": "PythonSaga/134","prompt":"from typing import List\n\ndef solve_eq(left: List[str], right: str) -> bool:\n \"\"\"I have an equation, represented by words on the left side and the result on the right side. \n You need to check if the equation is solvable under the following rules: \n 1. Each character is decoded as one digit (0 - 9). \n 2. No two characters can map to the same digit. \n 3. Each words[i] and result are decoded as one number without leading zeros. \n 4. Sum of numbers on the left side (words) will equal to the number on the right side (result). \n Take input from the user and check if the equation is solvable or not. \n\n Example 1: \n Input: ['send', 'more'], 'money' # Here send and more are words and money is result.\n Output: True\n Input: ['ox', 'ox'], 'xx' # Here ox and ox are words and xx is result.\n Output: False\"\"\"\n","entry_point":"solve_eq","canonical_solution":"unique_chars = set(''.join(left) + right) # Gather all unique characters\nif len(unique_chars) > 10: # More unique characters than digits\n return False\n\nchar_to_digit = {}\ndigits_taken = set()\n\ndef solve(index):\n if index == len(unique_chars): # All characters have been assigned digits\n left_sum = sum(int(\"\".join(char_to_digit[char] for char in word)) for word in left)\n right_sum = int(\"\".join(char_to_digit[char] for char in right))\n return left_sum == right_sum\n\n char = list(unique_chars)[index]\n for digit in range(10):\n if str(digit) not in digits_taken and not (digit == 0 and any(word[0] == char for word in left + [right])):\n char_to_digit[char] = str(digit)\n digits_taken.add(str(digit))\n if solve(index + 1):\n return True\n del char_to_digit[char]\n digits_taken.remove(str(digit))\n return False\n\nreturn solve(0)","test":"METADATA = {'author': 'ay', 'dataset': 'test'}\n\ndef check(candidate):\n assert candidate(['send', 'more'], 'money') == True\n assert candidate(['ox', 'ox'], 'xx') == False\n assert candidate(['bat', 'tab'], 'bat') == False\n assert candidate(['house', 'water'], 'money') == False"} { "task_id": "PythonSaga/135","prompt":"def is_good(s: str) -> str:\n \"\"\"I have a task to find whether a string is good or not. A string s is good if \n for every letter of the alphabet that s contains, it appears both in uppercase and lowercase. \n Take input from the user and print whether the string is good or not. \n return the longest substring of s that is nice. If there are multiple, return the substring of the earliest occurrence. \n If there are none, return an 'Not good'. \n Example: \n Input: 'uSaisAI' \n Output: 'SaisAI' \n Input: 'xYz' \n Output: 'Not good'\"\"\"\n","entry_point":"is_good","canonical_solution":"def is_good(s: str) -> str:\n def is_nice(substr):\n return all(c.islower() and c.upper() in substr or c.isupper() and c.lower() in substr for c in set(substr))\n\n n = len(s)\n longest_nice_substr = \"\"\n for i in range(n):\n for j in range(i + 1, n + 1):\n substring = s[i:j]\n if is_nice(substring) and len(substring) > len(longest_nice_substr):\n longest_nice_substr = substring\n\n return longest_nice_substr if longest_nice_substr else \"Not good\"","test":"METADATA = {'author': 'ay', 'dataset': 'test'}\n\ndef check(candidate):\n assert candidate('uSaisAI') == 'SaisAI'\n assert candidate('xYz') == 'Not good'\n assert candidate('aAbBcC') == 'aAbBcC'\n assert candidate('AbCdEfG') == 'Not good'"} { "task_id": "PythonSaga/136","prompt":"from typing import List\n\ndef power_mod(a: int, b: List[int]) -> int:\n \"\"\"I have a very large number a and another number b. \n b is such large it is given in form of list. I need to calculate pow(a,b) % 1337. \n But I have to use a divide and conquer approach. \n Take a and b as input from the user and return pow(a,b) % 1337. \n\n Example: \n Input: 2, [3]\n Output: 8\n Input: 2, [1,0] # Here 2 is a and 10 is b\n Output: 1024\"\"\"\n","entry_point":"power_mod","canonical_solution":"def power_mod(a: int, b: List[int]) -> int:\n MOD = 1337\n\n def pow_helper(base, exponent):\n if exponent == 0:\n return 1\n if exponent == 1:\n return base % MOD\n\n half_pow = pow_helper(base, exponent // 2)\n result = (half_pow * half_pow) % MOD\n\n if exponent % 2 == 1:\n result = (result * base) % MOD\n\n return result\n\n b_int = int(\"\".join(map(str, b))) # Convert list to integer\n return pow_helper(a, b_int)","test":"METADATA = {'author': 'ay', 'dataset': 'test'}\n\ndef check(candidate):\n assert candidate(2, [3]) == 8\n assert candidate(2, [1, 0]) == 1024\n assert candidate(3, [2, 5]) == 1151\n assert candidate(5, [1, 3, 7]) == 52"} { "task_id": "PythonSaga/137","prompt":"from typing import List\n\ndef max_sum(arr: List[int]) -> int:\n \"\"\"I have a list of integers. I want to find the maximum sum of a sublist. \n You can access the list in circular fashion. \n Take input from the user and print the maximum sum and the sublist. \n Example: \n Input: [1, -5, 6, -2]\n Output: 6\n Input: [9, -4, 9]\n Output: 18\"\"\"\n ","entry_point":"max_sum","canonical_solution":"def kadane(arr: List[int]) -> int:\n \"\"\"Standard Kadane's algorithm to find the maximum subarray sum.\"\"\"\n max_ending_here = max_so_far = arr[0]\n for x in arr[1:]:\n max_ending_here = max(x, max_ending_here + x)\n max_so_far = max(max_so_far, max_ending_here)\n return max_so_far\n\ndef max_sum(arr: List[int]) -> int:\n max_kadane = kadane(arr) # Maximum subarray sum in non-circular fashion\n\n # Invert the array and apply Kadane's algorithm to find the minimum subarray sum\n max_wrap = 0\n for i in range(len(arr)):\n max_wrap += arr[i] # Calculate array-sum\n arr[i] = -arr[i] # Invert the array elements\n\n # Max sum with corner elements will be: array-sum - (-max subarray sum of inverted array)\n max_wrap = max_wrap + kadane(arr)\n\n # The maximum circular sum will be maximum of two sums\n if max_wrap > max_kadane and max_wrap != 0:\n return max_wrap\n else:\n return max_kadane","test":"METADATA = {'author': 'ay', 'dataset': 'test'}\n\ndef check(candidate):\n assert candidate([1, -5, 6, -2]) == 6\n assert candidate([9, -4, 9]) == 18\n assert candidate([5, -3, 5]) == 10\n assert candidate([4, -1, 2, -1]) == 5\n assert candidate([-2, 8, -3, 7, -1]) == 12"} { "task_id": "PythonSaga/138","prompt":"from typing import List\n\ndef recover_list(n: int, sums: List[int]) -> List[int]:\n \"\"\"My job is to recover all the forgotten list by subset sums. \n given a list sums containing the values of all 2^n subset sums of the unknown array (in no particular order). \n Take input from the user for the length of the forgotten list and subset sums, and return the forgotten list. \n Example: \n Input: 3 ,[ -3,-2,-1,0,0,1,2,3]\n Output: [1,2,-3]\n Input: 2, [0,0,0,0]\n Output: [0,0]\"\"\"\n","entry_point":"recover_list","canonical_solution":"","test":"METADATA = {'author': 'ay', 'dataset': 'test'}\n\ndef check(candidate):\n assert candidate(3, [-3, -2, -1, 0, 0, 1, 2, 3]) == [1, 2, -3]\n assert candidate(2, [0, 0, 0, 0]) == [0, 0]\n assert candidate(2, [-1, 0, -1, 0]) == [0, -1]"} { "task_id": "PythonSaga/139","prompt":"from typing import List\n\ndef being_sum(being: List[int], lower: int, upper: int) -> int:\n \"\"\"I have a list 'being' of integers and I want to find the being-sum. \n Given two integers lower and upper, return the number of being-sums that lie in [lower, upper] inclusive. \n Range sum S(i, j) is defined as the sum of the elements in 'being' between indices i and j inclusive, where i <= j. \n Take input from the user for 'being' and lower and upper and return the number of being-sums that lie in [lower, upper] inclusive. \n Example:\n Input: [-2, 5, -1], -2, 2\n Output: 3\"\"\"\n","entry_point":"being_sum","canonical_solution":"def being_sum(being: List[int], lower: int, upper: int) -> int:\n n = len(being)\n prefix_sums = [0] * (n + 1) # Initialize prefix sums array with an extra 0 at the beginning\n\n # Compute prefix sums\n for i in range(n):\n prefix_sums[i + 1] = prefix_sums[i] + being[i]\n\n count = 0\n # Iterate through all pairs (i, j) and calculate range sums S(i, j)\n for i in range(n):\n for j in range(i, n):\n range_sum = prefix_sums[j + 1] - prefix_sums[i]\n if lower <= range_sum <= upper:\n count += 1\n\n return count","test":"METADATA = {'author': 'ay', 'dataset': 'test'}\n\ndef check(candidate):\n assert candidate([-2, 5, -1], -2, 2) == 3\n assert candidate([1, 2, 3], 0, 5) == 5\n assert candidate([3, 2, 1, 5], 1, 6) == 8"} { "task_id": "PythonSaga/140","prompt":"def nCr(n: int, r: int) -> int:\n \"\"\"I'm very much interested in mathematical problems, and today I learned nCr. \n Help me to implement it using dynamic programming. \n Take input from the user n and r and return nCr. \n Example: \n Input: 4, 2 # here 4 is n and 2 is r\n Output: 6\n Input: 3, 2\n Output: 3\"\"\"\n","entry_point":"nCr","canonical_solution":"def nCr(n: int, r: int) -> int:\n # Using dynamic programming to calculate binomial coefficient\n dp = [[0] * (r + 1) for _ in range(n + 1)]\n\n for i in range(n + 1):\n for j in range(min(i, r) + 1):\n if j == 0 or j == i:\n dp[i][j] = 1\n else:\n dp[i][j] = dp[i - 1][j - 1] + dp[i - 1][j]\n\n return dp[n][r]","test":"METADATA = {'author': 'ay', 'dataset': 'test'}\n\ndef check(candidate):\n assert candidate(4, 2) == 6\n assert candidate(3, 2) == 3\n assert candidate(6, 3) == 20\n assert candidate(8, 4) == 70"} { "task_id": "PythonSaga/141","prompt":"def bouncing_balls(n: int, h: int) -> int:\n \"\"\"I have to test my bouncing ball, but there's a catch. \n The ball only bounces if it falls from a certain height; otherwise, it will burst if the height is above that. \n 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. \n There are a few other conditions: \n 1. If the ball survives the fall, it can be used again. \n 2. If the ball bursts, it cannot be used again. \n 3. If the ball survives the fall from a certain height, it will also survive the fall from any height below that. \n 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. \n 5. All balls are identical and are of the same weight. \n Find the minimum number of balls required to find the threshold T. \n 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. \n Example: \n Input: 2, 10 # Here 2 is N and 10 is H\n Output: 4\n Input: 1, 2 # Here 1 is N and 2 is H\n Output: 2\"\"\"\n","entry_point":"bouncing_balls","canonical_solution":"ballFloor = [[0 for x in range(k + 1)] for x in range(n + 1)]\n\nfor i in range(1, n + 1):\n ballFloor[i][1] = 1\n ballFloor[i][0] = 0\n\nfor j in range(1, k + 1):\n ballFloor[1][j] = j\n\nfor i in range(2, n + 1):\n for j in range(2, k + 1):\n ballFloor[i][j] = INT_MAX\n for x in range(1, j + 1):\n res = 1 + max(ballFloor[i - 1][x - 1], ballFloor[i][j - x])\n if res < ballFloor[i][j]:\n ballFloor[i][j] = res\n\nreturn ballFloor[n][k]","test":"METADATA = {'author': 'ay', 'dataset': 'test'}\n\ndef check(candidate):\n assert candidate(2, 10) == 4\n assert candidate(1, 2) == 2\n assert candidate(3, 15) == 5\n assert candidate(5, 25) == 5"} { "task_id": "PythonSaga/142","prompt":"def zebra_crossing(n: int) -> int:\n \"\"\"I'm waiting for a bus, and now I'm getting bored. To entertain myself, I looked around and found a zebra crossing. \n There can be two ways to cross the road. If there are n white stripes on the zebra crossing, then I can cross \n either by stepping 1 stripe at a time or 2 stripes at a time. But I can't step on the same stripe twice. \n Tell the number of ways I can cross the zebra crossing. \n Use dynamic programming to solve this problem. \n 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. \n Example: \n Input: 4\n Output: 5\n Input: 10\n Output: 89\"\"\"\n","entry_point":"zebra_crossing","canonical_solution":"def zebra_crossing(n):\n def f(n, dp):\n if n == 0:\n return 1\n if n == 1:\n return 1\n if n == 2:\n return 2\n if dp[n] != -1:\n return dp[n]\n one_step = f(n - 1, dp)\n two_step = f(n - 2, dp)\n dp[n] = one_step + two_step\n return (dp[n] % 1000000007)\n\n dp = [-1] * (n + 1)\n return f(n, dp)","test":"METADATA = {'author': 'ay', 'dataset': 'test'}\n\ndef check(candidate):\n assert candidate(4) == 5\n assert candidate(10) == 89\n assert candidate(8) == 34\n assert candidate(2) == 2"} { "task_id": "PythonSaga/143","prompt":"def count_ways(number: str) -> int:\n \"\"\"I wrote down a string of positive integers named 'number' but forgot to include commas to separate the numbers. \n The list of integers is non-decreasing, and no integer has leading zeros. \n I need to figure out the number of possible ways I could have written down the string 'number.' \n The result should be returned modulo 10^9 + 7, as the answer might be large. \n Take input as a string and return the number of possible ways to write down the string modulo 10^9 + 7.\n Example 1:\n Input: '327'\n Output: 2\n Input: '094'\n Output: 0\"\"\"\n","entry_point":"count_ways","canonical_solution":"MOD = 10**9 + 7\n\ndef count_ways(number: str) -> int:\n n = len(number)\n dp = [0] * (n + 1)\n dp[0] = 1 # Base case\n\n for i in range(1, n + 1):\n for length in range(1, 4): # Check substrings of length 1 to 3 (since integers can range from 1 to 999)\n if i - length >= 0:\n substr = number[i - length:i]\n if (substr[0] != '0' or length == 1) and (i - length == 0 or substr >= number[max(i - 2 * length, 0):i - length]):\n # Check if substr is valid and non-decreasing\n dp[i] = (dp[i] + dp[i - length]) % MOD\n\n return dp[n]","test":"METADATA = {'author': 'ay', 'dataset': 'test'}\n\ndef check(candidate):\n assert candidate('327') == 2\n assert candidate('094') == 0\n assert candidate('111') == 2"} { "task_id": "PythonSaga/144","prompt":"from typing import List\ndef treasureHunt(a: int, b: int, x: int, forbidden: List[int]) -> int:\n \"\"\"I'm playing a game on road where to win treasure I have to hop \n forward or backward on the x-axis. I start at position 0, and my treasure is at position x. \n There are rules for how I can hop: \n I can jump exactly a positions forward (to the right). \n I can jump exactly b positions backward (to the left). \n I cannot jump backward twice in a row. \n I cannot jump to any forbidden positions. \n 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. \n 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. \n 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 \n me on position x, the result is -1. \n Example 1: \n Input: 15, 13, 11, [8,3,16,6,12,20] # a, b, x, forbidden\n Output: -1\n Input: 16, 9, 7, [1,6,2,14,5,17,4] # a, b, x, forbidden\n Output: 2 \n \"\"\"\n ","entry_point":"treasureHunt","canonical_solution":"MOD = 10**9 + 7 # For large numbers\nvisited = set() # To keep track of visited positions with a flag for last move\nforbidden = set(forbidden) # Convert list to set for efficient lookups\n\nqueue = deque([(0, 0, False)]) # Position, steps, last move was backward\nwhile queue:\n position, steps, last_backward = queue.popleft()\n\n if position == x:\n return steps % MOD\n\n # Forward move\n forward_pos = position + a\n if forward_pos not in forbidden and (forward_pos, False) not in visited:\n visited.add((forward_pos, False))\n queue.append((forward_pos, steps + 1, False))\n\n # Backward move, ensuring not to move backward twice in a row\n if not last_backward and position - b not in forbidden and position - b >= 0:\n backward_pos = position - b\n if (backward_pos, True) not in visited:\n visited.add((backward_pos, True))\n queue.append((backward_pos, steps + 1, True))\n\nreturn -1 # Treasure is unreachable","test":"def check(candidate):\n assert candidate(15, 13, 11, [8, 3, 16, 6, 12, 20]) == -1\n assert candidate(16, 9, 7, [1, 6, 2, 14, 5, 17, 4]) == 2\n assert candidate(3, 15, 9, [14,4,18,1,15]) == 3"} { "task_id": "PythonSaga/145","prompt":"from collections import deque\nfrom typing import List\ndef houses(n:int, connections:List[List[int]]) -> List[int]:\n \"\"\"I'm standing at entry point of village. In this village there's no proper streets. Houses are randomly connected \n 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. \n 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, \n than i visit to all third houses which can be reached from second house and so on. \n Take input from user in form of number of houses and connections between houses and return the order in which i should visit houses. \n Starting point is always house 0. and later all houses are numbered in order of their appearance in input. \n Example: \n Input: 5, [[1,2,3],[],[4],[],[]]\n Output: [0,1,2,3,4]\n Input: 3, [[1,2],[],[]]\n Output: [0,1,2]\"\"\"\n ","entry_point":"houses","canonical_solution":"order = [] # To store the order of visiting houses\nvisited = [False] * n # To keep track of visited houses\nqueue = deque([0]) # Start from house 0\n\nwhile queue:\n house = queue.popleft()\n if not visited[house]:\n order.append(house)\n visited[house] = True\n # Enqueue all connected, unvisited houses\n for connected_house in connections[house]:\n if not visited[connected_house]:\n queue.append(connected_house)\n\nreturn order","test":"METADATA = {\n 'author': 'ay',\n 'dataset': 'test'\n}\n\ndef check(candidate):\n assert candidate(5, [[1, 2, 3], [], [4], [], []]) == [0, 1, 2, 3, 4]\n assert candidate(3, [[1, 2], [], []]) == [0, 1, 2]\n assert candidate(6, [[1, 2], [3, 5], [4], [], [], []]) == [0, 1, 2, 3, 5, 4]\n assert candidate(4, [[1, 2], [3], [], []]) == [0, 1, 2, 3]"} { "task_id": "PythonSaga/146","prompt":"from collections import deque \nfrom typing import List\n\ndef knight_moves(n:int, start:List[int], end:List[int]) -> int:\n \"\"\"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. \n 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). \n how many minimum steps it would take to reach from (x1,y1) to (x2,y2). \n Take input from user for size of board and position of knight and position of destination. and return minimum steps. \n Example: \n Input: 6, [4,5], [1,1] # 6 is size of board, [4,5] is position of knight and [1,1] is position of destination.\n Output: 3 \"\"\"\n","entry_point":"knight_moves","canonical_solution":"from collections import deque\n\nsource_row = KnightPos[0] - 1\nsource_col = KnightPos[1] - 1\n\ndist = (TargetPos[0] - 1, TargetPos[1] - 1)\n\nqueue = deque([(source_row, source_col, 0)])\n\ndeltas = [(2, 1), (1, 2), (-2, 1), (-1, 2), (2, -1), (1, -2), (-2, -1), (-1, -2)]\n\nvisited = set()\n\nwhile queue:\n row, col, step = queue.popleft()\n \n if (row, col) == dist: return step\n\n for drow, dcol in deltas:\n row_delta = drow + row\n col_delta = dcol + col\n \n row_inbound = 0 <= row_delta < N\n col_inbound = 0 <= col_delta < N\n\n if not row_inbound or not col_inbound: continue\n \n if (row_delta, col_delta) not in visited:\n queue.append((row_delta, col_delta, step + 1))\n visited.add((row_delta, col_delta))\n \nreturn -1","test":"METADATA = {\n 'author': 'ay',\n 'dataset': 'test'\n}\n\ndef check(candidate):\n assert candidate(6, [4, 5], [1, 1]) == 3\n assert candidate(8, [2, 2], [7, 7]) == 4\n assert candidate(5, [0, 0], [4, 4]) == 4\n assert candidate(4, [1, 1], [3, 3]) == 4"} { "task_id": "PythonSaga/147","prompt":"from typing import List\ndef remove_poles(v:int, w:int, wires:List[List[int]]) -> List[int]:\n \"\"\"I have new job where i have to remove electric poles. There a v electric poles conected by w wires in random order. \n But soome how each pole is connected to every other pole directly or indirectly. let's say this complete setup as one chunk. \n I want to find all that pole by removal of that just one pole, whole chunk will be disconnected. \n There can be multiple such poles which can be removed to disconnect the chunk. list all those poles. \n 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. \n Few things to note: \n pole number starts from 0 to v-1 and wires are bidirectional. \n Example: \n Input: 5, 5, [[0,1],[1,4],[4,2],[2,3],[3,4]]\n Output: [1,4]\n Input: 5, 4, [[0,1],[1,4],[4,2],[2,3]]\n Output: [1,4,2]\"\"\"\n ","entry_point":"remove_poles","canonical_solution":"def dfs(v, u, visited, disc, low, parent, ap, graph, time):\n children = 0\n visited[u] = True\n disc[u] = low[u] = time[0]\n time[0] += 1\n\n for neighbour in graph[u]:\n if not visited[neighbour]:\n parent[neighbour] = u\n children += 1\n dfs(v, neighbour, visited, disc, low, parent, ap, graph, time)\n\n low[u] = min(low[u], low[neighbour])\n\n if parent[u] == -1 and children > 1:\n ap[u] = True\n if parent[u] != -1 and low[neighbour] >= disc[u]:\n ap[u] = True\n elif neighbour != parent[u]:\n low[u] = min(low[u], disc[neighbour])\n\ndef remove_poles(v: int, w: int, wires: List[List[int]]) -> List[int]:\n graph = [[] for _ in range(v)]\n for wire in wires:\n graph[wire[0]].append(wire[1])\n graph[wire[1]].append(wire[0])\n\n visited = [False] * v\n disc = [float('inf')] * v\n low = [float('inf')] * v\n parent = [-1] * v\n ap = [False] * v # Articulation points\n time = [0]\n\n for i in range(v):\n if not visited[i]:\n dfs(v, i, visited, disc, low, parent, ap, graph, time)\n\n return [i for i, x in enumerate(ap) if x]","test":"METADATA = {\n 'author': 'ay',\n 'dataset': 'test'\n}\n\ndef check(candidate):\n assert candidate(5, 5, [[0, 1], [1, 4], [4, 2], [2, 3], [3, 4]]) == [1, 4]\n assert candidate(5, 4, [[0, 1], [1, 4], [4, 2], [2, 3]]) == [1, 4, 2]\n assert candidate(5, 5, [[0, 1], [1, 2], [0, 2], [2, 3], [3, 4]]) == [2, 3]"} { "task_id": "PythonSaga/148","prompt":"from typing import List\ndef strongly_connected(S:int, T:int, tracks:List[List[int]]) -> List[List[int]]:\n \"\"\"I'm the new railway state incharge and I want to know few things about railway networks. \n right now there are S stations and T tracks in between them . Some how all stations are connected to some other stations. \n Your task is to find the members of strongly connected stations in the state. \n Take input for S , T and T lines of input for tracks. and return the all strongly connected stations. \n Assume each station starts with 0 and ends with S-1 and each track if directed from one station to another. \n Example: \n Input: 5, 5, [[1,0],[0,2],[2,1],[0,3],[3,4]]\n Output: [[0,1,2] ,[3] ,[4]]\"\"\"\n","entry_point":"strongly_connected","canonical_solution":"def dfs(graph, v, visited, stack):\n visited[v] = True\n for i in graph[v]:\n if not visited[i]:\n dfs(graph, i, visited, stack)\n stack.append(v)\n\ndef transpose(graph, S):\n gT = [[] for _ in range(S)]\n for i in range(S):\n for j in graph[i]:\n gT[j].append(i)\n return gT\n\ndef dfsUtil(graph, v, visited, component):\n visited[v] = True\n component.append(v)\n for i in graph[v]:\n if not visited[i]:\n dfsUtil(graph, i, visited, component)\n\ndef strongly_connected(S, T, tracks):\n graph = [[] for _ in range(S)]\n for track in tracks:\n graph[track[0]].append(track[1])\n\n stack = []\n visited = [False] * S\n\n # Step 1: Fill the stack with vertices based on their finishing times\n for i in range(S):\n if not visited[i]:\n dfs(graph, i, visited, stack)\n\n # Step 2: Transpose the graph\n graphT = transpose(graph, S)\n\n # Step 3: Perform DFS on the transposed graph in the order given by the stack\n visited = [False] * S\n scc = []\n while stack:\n v = stack.pop()\n if not visited[v]:\n component = []\n dfsUtil(graphT, v, visited, component)\n scc.append(sorted(component))\n\n return scc","test":"METADATA = {\n 'author': 'ay',\n 'dataset': 'test'\n}\n\ndef check(candidate):\n assert candidate(5, 5, [[1,0],[0,2],[2,1],[0,3],[3,4]]) == [[0,1,2] ,[3] ,[4]]\n assert candidate(3, 3, [[0,1],[1,2],[2,0]]) == [[0,1,2]]\n assert candidate(9, 17, [[0,2],[0,1],[1,0],[1,3],[2,0],[2,3],[3,4],[4,3],[5,1],[5,4],[5,7],[6,5],[7,4],[7,6],[8,6],[8,7],[8,8]]) == [[0,1,2],[3,4],[5,6,7],[8]]"} { "task_id": "PythonSaga/149","prompt":"from typing import List\ndef maze(n:int, m:int, maze:List[List[str]]) -> bool:\n \"\"\"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 \n you have to find whether you can reach from start to end or not. You can traverse up, down, right and left.\n The description of cells is as follows: \n A value of cell S means start. \n A value of cell D means end. \n A value of cell X means Blank cell. \n A value of cell 0 means Wall. \n Take input from user for rows and columns of maze and then take input for maze. \n Return True if you can reach from start to end else return False. \n Example: \n 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]]\n Output: False\"\"\"\n","entry_point":"maze","canonical_solution":"def dfs(maze, i, j, visited):\n # Base conditions\n if not (0 <= i < len(maze) and 0 <= j < len(maze[0])) or maze[i][j] == '0' or visited[i][j]:\n return False\n if maze[i][j] == 'D': # Destination found\n return True\n \n # Mark the current cell as visited\n visited[i][j] = True\n\n # Explore all four directions from the current cell\n directions = [(0, 1), (0, -1), (1, 0), (-1, 0)]\n for di, dj in directions:\n if dfs(maze, i + di, j + dj, visited):\n return True\n \n return False\n\ndef maze(n, m, maze):\n visited = [[False for _ in range(m)] for _ in range(n)]\n\n # Find the starting point\n for i in range(n):\n for j in range(m):\n if maze[i][j] == 'S':\n return dfs(maze, i, j, visited)\n\n return False # Start point not found","test":"METADATA = {\n 'author': 'ay',\n 'dataset': 'test'\n}\n\ndef check(candidate):\n assert candidate(5, 5, [['X', '0', 'X', '0', '0'],\n ['X', '0', '0', '0', 'X'],\n ['X', 'X', 'X', 'X', 'X'],\n ['0', 'D', 'X', '0', '0'],\n ['X', '0', '0', 'S', 'X']]) == False\n\n assert candidate(4, 5, [['X', '0', 'X', '0', 'X'],\n ['0', '0', 'X', '0', 'X'],\n ['X', 'X', 'X', 'X', 'X'],\n ['X', 'D', 'X', 'S', 'X']]) == True\n\n assert candidate(3, 3, [['S', '0', '0'],\n ['0', 'X', 'D'],\n ['X', '0', '0']]) == False\n\n assert candidate(4, 4, [['S', 'X', '0', 'X'],\n ['0', 'X', '0', '0'],\n ['X', 'X', '0', 'D'],\n ['X', 'X', 'X', 'X']]) == True"} { "task_id": "PythonSaga/150","prompt":"from typing import List\ndef student_room(query: List[List[int]]) -> List[bool]:\n \"\"\"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. \n If same student is added with another student, it goes to same room. \n Do two task : \n 1. Take input for 2 students at a time and put them in same room. \n 2. Or give input for 2 students and check if they are in same room or not. \n Take input from user for queries he want to perform, queries can be of two types: \n 1. Add student to room \n 2. Check if two students are in same room \n 3. Exit \n Example: [query, student1, student2]\n 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\n Output: [False, True]\"\"\"\n ","entry_point":"student_room","canonical_solution":"def find(parent, i):\n if parent[i] != i:\n parent[i] = find(parent, parent[i]) # Path compression\n return parent[i]\n\ndef union(parent, a, b):\n rootA = find(parent, a)\n rootB = find(parent, b)\n if rootA != rootB:\n parent[rootB] = rootA # Merge the sets\n\ndef student_room(query: List[List[int]]) -> List[bool]:\n parent = {} # To keep track of the representative (leader) of each room\n output = []\n\n for q in query:\n if q[0] == 1: # Add student to room\n a, b = q[1], q[2]\n if a not in parent:\n parent[a] = a\n if b not in parent:\n parent[b] = b\n union(parent, a, b)\n elif q[0] == 2: # Check if two students are in the same room\n a, b = q[1], q[2]\n if a in parent and b in parent and find(parent, a) == find(parent, b):\n output.append(True)\n else:\n output.append(False)\n elif q[0] == 3: # Exit\n break\n\n return output","test":"METADATA = {\n 'author': 'ay',\n 'dataset': 'test'\n}\n\ndef check(candidate):\n assert candidate([[1, 1, 3], [2, 1, 4], [1, 2, 3], [2, 1, 3], [3]]) == [False, True]\n assert candidate([[1, 1, 2], [1, 3, 4], [2, 1, 4], [2, 2, 3], [3]]) == [False, False]\n assert candidate([[1, 1, 2], [1, 3, 4], [2, 1, 4], [1, 2, 3], [2, 1, 3], [3]]) == [False, True]\n assert candidate([[1, 1, 2], [1, 2, 3], [2, 3, 4], [2, 1, 4], [3]]) == [False, False]"} { "task_id": "PythonSaga/151","prompt":"from typing import List\ndef water_pipeline(tanks: int, pipes: List[List[int]]) -> bool:\n \"\"\"I have a water pipeline system with water tanks and pipes. \n All pipes are biderctional and all tanks are connected to each other either directly or indirectly. \n There's no self loop in the system. I want to find all the cycles in the system to avoid water wastage. \n Take input from user for W water tanks and P pipes. Then take input for each pipe in the format (tank1, tank2). \n Return True if there's any cycle in the system else return False. \n Few points to note: \n 1. Each tank have number from 0 to W-1. \n 2. Try to use disjoint set data structure to solve this problem. \n Example: \n Input: 5, [[1,3],[3,0],[0,2],[2,4],[4,0]]\n Output: True\"\"\"\n ","entry_point":"water_pipeline","canonical_solution":"def find(parent, i):\n if parent[i] != i:\n parent[i] = find(parent, parent[i]) # Path compression\n return parent[i]\n\ndef union(parent, a, b):\n rootA = find(parent, a)\n rootB = find(parent, b)\n if rootA == rootB: # A cycle is found\n return True\n parent[rootB] = rootA # Merge the sets\n return False\n\ndef water_pipeline(tanks: int, pipes: List[List[int]]) -> bool:\n parent = list(range(tanks)) # Each tank is initially its own parent\n\n for a, b in pipes:\n if union(parent, a, b): # If union returns True, a cycle is found\n return True\n\n return False # No cycles found","test":"METADATA = {\n 'author': 'ay',\n 'dataset': 'test'\n}\n\ndef check(candidate):\n assert candidate(5, [[1, 3], [3, 0], [0, 2], [2, 4], [4, 0]]) == True\n assert candidate(4, [[0, 1], [1, 2], [2, 3], [3, 0]]) == True\n assert candidate(3, [[0, 1], [1, 2]]) == False\n assert candidate(6, [[0, 1], [1, 2], [2, 3], [3, 4], [4, 5]]) == False"} { "task_id": "PythonSaga/152","prompt":"from typing import List\ndef water_supply(villages: int, wells: List[int], pipes: List[List[int]]) -> int:\n \"\"\"I have an N number of villages numbered 1 to N, an list wells[] \n 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] \n which denotes that the cost to connect village X and Y with water pipes is C. \n Your task is to provide water to each and every village either by building a well in the village or connecting \n it to some other village having water. Find the minimum cost to do so. \n Take input from user for N, wells[] and pipes[][]. and return the minimum cost to provide water to all villages. \n Example 1: \n 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, \n [[1, 2, 1], [2, 3, 1]] is the cost of connecting pipes in each village\n Output: 3\"\"\"\n ","entry_point":"water_supply","canonical_solution":"def find(parent, i):\n if parent[i] != i:\n parent[i] = find(parent, parent[i]) # Path compression\n return parent[i]\n\ndef union(parent, rank, x, y):\n xroot = find(parent, x)\n yroot = find(parent, y)\n if rank[xroot] < rank[yroot]:\n parent[xroot] = yroot\n elif rank[xroot] > rank[yroot]:\n parent[yroot] = xroot\n else:\n parent[yroot] = xroot\n rank[xroot] += 1\n\ndef water_supply(villages: int, wells: List[int], pipes: List[List[int]]) -> int:\n parent = [i for i in range(villages + 1)] # Including the virtual node\n rank = [0] * (villages + 1)\n \n # Create edges list: (cost, village1, village2), including virtual node connections\n edges = [(cost, 0, i + 1) for i, cost in enumerate(wells)] # Connecting villages to the virtual node (0) via wells\n for x, y, c in pipes:\n edges.append((c, x, y))\n \n edges.sort() # Sort by cost\n \n total_cost = 0\n for cost, x, y in edges:\n if find(parent, x) != find(parent, y): # If adding this edge doesn't form a cycle\n union(parent, rank, x, y)\n total_cost += cost\n \n return total_cost","test":"METADATA = {\n 'author': 'ay',\n 'dataset': 'test'\n}\n\ndef check(candidate):\n assert candidate(3, [1, 2, 2], [[1, 2, 1], [2, 3, 1]]) == 3\n assert candidate(4, [2, 3, 1, 4], [[1, 2, 2], [2, 3, 3], [3, 4, 4]]) == 9\n assert candidate(5, [1, 2, 3, 4, 5], [[1, 2, 1], [3, 4, 2], [4, 5, 3], [2, 3, 1]]) == 8\n assert candidate(3, [3, 5, 2], [[1, 2, 1], [2, 3, 2]]) == 5"} { "task_id": "PythonSaga/153","prompt":"from typing import List\ndef gang_fight(fights: List[List[int]]) -> int:\n \"\"\"There's a fight going on in the school. It is between 2 gangs. \n Let's say there are N fights going on between gang A and gang B. We have 2D list of size N, Denotig \n that student list[i][0] and list[i][1] are fighting with each other. \n The task is to find the maximum number of student belonging to an gang if it is \n possible to distribute all the student among A and B, otherwise print -1. \n Take input from user in the form of 2D list and return the maximum number of student belonging to an gang. \n Example 1: \n Input: [[1,2],[2,3],[2,4],[2,5]] \n Output: 4 \n Example 2: \n Input: [[1,2],[2,3],[3,1]] \n Output: -1 \"\"\"\n ","entry_point":"gang_fight","canonical_solution":"def is_bipartite(graph, start, color):\n queue = deque([start])\n color[start] = 1 # Assign a color to the starting vertex\n\n while queue:\n u = queue.popleft()\n for v in graph[u]:\n if color[v] == -1: # If not colored\n color[v] = 1 - color[u] # Assign an alternate color\n queue.append(v)\n elif color[v] == color[u]: # If the adjacent has the same color, it's not bipartite\n return False\n return True\n\ndef gang_fight(fights: List[List[int]]) -> int:\n if not fights:\n return 0\n\n # Find the maximum student number to determine the graph size\n max_student = max(max(fight) for fight in fights)\n graph = [[] for _ in range(max_student + 1)]\n color = [-1] * (max_student + 1) # -1 indicates not colored\n\n # Build the graph\n for fight in fights:\n graph[fight[0]].append(fight[1])\n graph[fight[1]].append(fight[0])\n\n # Check if the graph is bipartite and color the graph\n for student in range(1, max_student + 1):\n if color[student] == -1 and not is_bipartite(graph, student, color):\n return -1 # The graph is not bipartite\n\n # Count the number of students in one of the gangs\n max_gang_size = color.count(1)\n return max(max_gang_size, len(color) - max_gang_size - 1) # Exclude the -1 (not colored) count","test":"METADATA = {\n 'author': 'ay',\n 'dataset': 'test'\n}\n\ndef check(candidate):\n assert candidate([[1, 2], [2, 3], [2, 4], [2, 5]]) == 4\n assert candidate([[1, 2], [2, 3], [3, 1]]) == -1\n assert candidate([[1, 2], [2, 3], [3, 4], [3, 5], [6, 7], [7, 8], [7, 9], [7, 10]]) == 7"} { "task_id": "PythonSaga/154","prompt":"from typing import List\ndef colony_pipes(houses: int, pipes: int, connections: List[List[int]]) -> List[int]:\n \"\"\"i'm connecting houses in colony with pipeline. I have H houses and P pipes. \n I can conect one pipe between two houses (a to b). after each connection I have to print the minimmum \n differnce possible between the size any two chunck of the colony. If there is only one chunk simply print 0. \n chunck is a set of houses connected with each other. \n Take input from user foor H and P and then take input for P pipe connections. and return the minimum difference. \n example: \n Input: 2, 1, [[1,2]] # 2 is the number of houses, 1 is the number of pipes, [[1,2]] is the pipe connection\n Output: 0\n 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\n Output: 2\"\"\"\n ","entry_point":"colony_pipes","canonical_solution":"","test":"METADATA = {\n 'author': 'ay',\n 'dataset': 'test'\n}\n\ndef check(candidate):\n assert candidate(2, 1, [[1, 2]]) == [0]\n assert candidate(4, 2, [[1, 2], [2, 4]]) == [0, 2]\n assert candidate(5, 3, [[1, 2], [3, 4], [4, 5]]) == [0, 0, 1]\n assert candidate(6, 4, [[1, 2], [3, 4], [2, 5], [6, 1]]) == [0, 0, 1, 2]"} { "task_id": "PythonSaga/155","prompt":"from typing import List\ndef water_plant(cities: int, connections: List[List[int]]) -> int:\n \"\"\"i have a one water processong plant and a city. The job of water plant is to supply water to the city. \n 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. \n 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. \n Points to be noted: \n 1. there may be multiple villages in between water plant and city. \n 2. villages are interconceted with each other (not all) with pipes. \n 3. Names of villages are 1 to n. \n Take input from user in form of matrix. where first row is for water plant and last row is for city. \n in between rows are for villages. If there is no connection between two villages then put 0 in matrix. \n If there is connection between two villages then put the rate of water flow in matrix. \n Return the amount of water supplied to the city. Try to use max flow concept. \n Example: \n 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]]\n Output: 23\"\"\"\n ","entry_point":"water_plant","canonical_solution":"def bfs(rGraph, s, t, parent):\n visited = [False] * len(rGraph)\n queue = deque()\n queue.append(s)\n visited[s] = True\n\n while queue:\n u = queue.popleft()\n\n for ind, val in enumerate(rGraph[u]):\n if not visited[ind] and val > 0:\n if ind == t:\n parent[ind] = u\n return True\n queue.append(ind)\n parent[ind] = u\n visited[ind] = True\n return False\n\ndef edmonds_karp(graph, source, sink):\n rGraph = [row[:] for row in graph] # Residual graph\n parent = [-1] * len(graph)\n max_flow = 0\n\n while bfs(rGraph, source, sink, parent):\n path_flow = float('inf')\n s = sink\n\n while(s != source):\n path_flow = min(path_flow, rGraph[parent[s]][s])\n s = parent[s]\n\n max_flow += path_flow\n v = sink\n\n while(v != source):\n u = parent[v]\n rGraph[u][v] -= path_flow\n rGraph[v][u] += path_flow\n v = parent[v]\n\n return max_flow\n\ndef water_plant(cities, connections):\n # The source is the water plant (0) and the sink is the city (cities - 1)\n return edmonds_karp(connections, 0, cities - 1)","test":"METADATA = {\n 'author': 'ay',\n 'dataset': 'test'\n}\n\ndef check(candidate):\n assert candidate(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]]) == 23"} { "task_id": "PythonSaga/156","prompt":"from typing import List\ndef truck_load(cities: int, connections: List[List[int]]) -> int:\n \"\"\"in a network of cities and road there are number of trucks that are carrying goods from one city to another city. \n 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 \n 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. \n There can be multiple other cities in between city A and city B. \n Roads can be bidirectional. \n Take input from user for the number of cities in between city A and city B and the \n 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. \n Example: \n 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]]\n Output: 10\"\"\"","entry_point":"truck_load","canonical_solution":"","test":"METADATA = {\n 'author': 'ay',\n 'dataset': 'test'\n}\n\ndef check(candidate):\n assert candidate(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]]) == 10"} { "task_id": "PythonSaga/157","prompt":"import sys \nfrom typing import List\ndef parcel(cities: int, route: List[List[int]]) -> int:\n \"\"\"I have to courier the parcel from my home to my college. \n I want to know minimum days it will take to reach the parcel to my college. \n Give: \n 1. Number of cities in between my home and college. \n 2. Days taken between each city. \n 3. The route is undirected. \n 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. \n take input in form of matrix. and return minimum days taken to reach college. \n Example: \n input: 2, [[0,3,2,0],[0,0,5,2],[0,0,0,3],[0,0,0,0]]\n output: 5\"\"\"","entry_point":"parcel","canonical_solution":"","test":"METADATA = {\n 'author': 'ay',\n 'dataset': 'test'\n}\n\ndef check(candidate):\n assert candidate(2, [[0, 3, 2, 0], [0, 0, 5, 2], [0, 0, 0, 3], [0, 0, 0, 0]]) == 5"} { "task_id": "PythonSaga/158","prompt":"from collections import deque \nfrom typing import List\ndef blood_flow(organ: int, blood_vessel: List[List[int]]) -> int:\n \"\"\"Let's say i want to find max amount of blood that can flow from one organ to another. \n And in between there are n other organs. organ are connected via blood vessels. \n Take input from user as number of organ and capacity of each blood vessel fron organ to organ. \n Do this in form of matrix and return max amount of blood that can flow from one organ A to organ B. \n Also blood can flow is unidirectional. \n Example:\n 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]]\n Output: 7 \"\"\"","entry_point":"blood_flow","canonical_solution":"","test":"METADATA = {\n 'author': 'ay',\n 'dataset': 'test'\n}\n\ndef check(candidate):\n assert candidate(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]]) == 7"} { "task_id": "PythonSaga/159","prompt":"from collections import defaultdict \nfrom typing import List\ndef data_transfer(routers: int, network_links: List[List[int]]) -> int:\n \"\"\"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. \n Between these computers, there are n routers connected via network links with specific capacities. \n Data transfer is unidirectional. \n Example: \n 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]\n Output: 7 # The maximum amount of data that can flow from Computer A to Computer B is 7.\"\"\"","entry_point":"data_transfer","canonical_solution":"","test":"METADATA = {\n 'author': 'ay',\n 'dataset': 'test'\n}\n\n\ndef check(candidate):\n assert candidate(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]]) == 7"} { "task_id": "PythonSaga/160","prompt":"def divide_100_by(x:int)->str:\n \"\"\"Let's say you have function divide(x,y) that returns x/y. \n Write a function called bind1st(func, value) that can create a one parameter function from \n this two parameter function? create a new function called divide_100_by(y). \n Use bind2func to create a function that divides 100 by a number. \n Take input from user for any number and return the result of 100 divided by that number. \n Try to use decorator and closure to solve this problem. \n Example: \n Input: 10\n Output: \"100 divided by 10 is 10.00\"\n Input: 3\n Output: \"100 divided by 3 is 33.33\"\n \"\"\"\n ","entry_point":"divide_100_by","canonical_solution":"def bind1st(func):\n @wraps(func)\n def wrapper(value):\n return func(100, value)\n return wrapper\n\n@bind1st\ndef divide(x, y):\n return x / y\n\ndef divide_100_by(y):\n result = divide(y)\n return f\"100 divided by {y} is {result:.2f}\"\n\n# Example usage:\nuser_input = int(input(\"Enter a number: \"))\noutput = divide_100_by(user_input)\nprint(output)","test":"METADATA = {'author': 'ay','dataset': 'test'}\ndef check(candidate):\n user_input_1 = 10\n output_1 = candidate(user_input_1)\n assert output_1 == '100 divided by 10 is 10.00'\n\n user_input_2 = 3\n output_2 = candidate(user_input_2)\n assert output_2 == '100 divided by 3 is 33.33'\n\n user_input_3 = 7\n output_3 = candidate(user_input_3)\n assert output_3 == '100 divided by 7 is 14.29'\n\n user_input_4 = 11\n output_4 = candidate(user_input_4)\n assert output_4 == '100 divided by 11 is 9.09'"} { "task_id": "PythonSaga/161","prompt":"import time \nfrom typing import List\n\ndef math_ops(a: int, b: int) -> List[List[str]]:\n \"\"\"Let's say I have two number a and b, and I few functions: \n 1. mutliply(a, b) \n 2. divide(a, b) \n 3. power(a, b) \n But these function uses loops instead of direct multiplication, division, and power to solve the problem. \n I want to see how much time each function takes to run. \n But I don't want to write a code to calculate the time for each function. show time in nanoseconds. \n I want to create one function for that and use it for all the functions. \n Try to use concept of decorators and closures to solve this problem. \n 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. \n In time is greater than 0 return true else return false.\n Example:\n Input: 10, 5\n Output: [[\"50\", \"True\"], [\"2\", \"True\"], [\"100000\", \"True\"]]\n \"\"\"\n ","entry_point":"math_ops","canonical_solution":"import time\nfrom typing import List\ndef time_decorator(func):\n def wrapper(a, b):\n start = time.time_ns() # Capture start time in nanoseconds\n result = func(a, b) # Call the original function\n end = time.time_ns() # Capture end time in nanoseconds\n elapsed = end - start # Calculate elapsed time\n return [str(result), str(elapsed > 0)] # Format result and time check\n return wrapper\n\n@time_decorator\ndef multiply(a, b):\n result = 0\n for _ in range(b):\n result += a\n return result\n\n@time_decorator\ndef divide(a, b):\n count = 0\n while a >= b:\n a -= b\n count += 1\n return count\n\n@time_decorator\ndef power(a, b):\n result = 1\n for _ in range(b):\n result *= a\n return result\n\ndef math_ops(a: int, b: int) -> List[List[str]]:\n return [multiply(a, b), divide(a, b), power(a, b)]","test":"METADATA = {\n 'author': 'ay',\n 'dataset': 'test'\n}\n\ndef check(candidate):\n assert candidate(10, 5) == [['50', 'True'], ['2', 'True'], ['100000', 'True']]\n assert candidate(8, 2) == [['16', 'True'], ['4', 'True'], ['64', 'True']]\n assert candidate(15, 3) == [['45', 'True'], ['5', 'True'], ['3375', 'True']]\n assert candidate(7, -1) == [['21', 'True'], ['2', 'True'], ['343', 'True']]"} { "task_id": "PythonSaga/162","prompt":"from typing import List\ndef number_plate(number: List[str]) -> List[str]:\n \"\"\"I have a bunch of car number plates in the format of 'XX XX XXXX'. \n I want to print them in sorted order. Also, sometimes there is \n a prefix 'HS', 'AB', or 'XX' in front and sometimes it is not there. \n Take input from the user and print them in sorted order along with the new prefix \n 'Hind'. If there is a prefix already present then remove it and add 'Hind'. \n If there is no prefix then add 'Hind' in front of the number plate. \n Try to use decorator and closure concept. \n Example: \n Input: 5, ['HS 01 1234', '06 1234', 'AB 01 1134', '01 1234', 'XX 11 1234']\n Output: ['Hind 01 1134', 'Hind 01 1234', 'Hind 01 1234', 'Hind 06 1234', 'Hind 11 1234']\"\"\"\n ","entry_point":"number_plate","canonical_solution":"def number_plate_decorator(func: Callable[[List[str]], List[str]]) -> Callable[[List[str]], List[str]]:\n def wrapper(number: List[str]) -> List[str]:\n # Process each number plate: remove existing prefix and add \"Hind\" prefix\n processed = [\"Hind \" + \" \".join(plate.split()[1:]) if plate.split()[0] in [\"HS\", \"AB\", \"XX\"] else \"Hind \" + plate for plate in number]\n # Sort the processed number plates\n sorted_plates = sorted(processed)\n # Return the sorted number plates through the original function\n return func(sorted_plates)\n return wrapper\n\n@number_plate_decorator\ndef number_plate(number: List[str]) -> List[str]:\n return number","test":"METADATA = {\n 'author': 'ay',\n 'dataset': 'test'\n}\n\ndef check(candidate):\n assert candidate([\"HS 01 1234\", \"06 1234\", \"AB 01 1134\", \"01 1234\", \"XX 11 1234\"]) == ['Hind 01 1134', 'Hind 01 1234', 'Hind 01 1234', 'Hind 06 1234', 'Hind 11 1234']\n assert candidate([\"AB 12 3456\", \"XX 09 8765\", \"HS 05 4321\", \"03 5678\", \"YY 11 9876\"]) == ['Hind 03 5678', 'Hind 05 4321', 'Hind 09 8765', 'Hind 11 9876', 'Hind 12 3456']\n assert candidate([\"XX 01 2345\", \"AB 05 6789\", \"HS 10 4321\", \"07 9876\", \"YY 15 8765\"]) == ['Hind 01 2345', 'Hind 05 6789', 'Hind 07 9876', 'Hind 10 4321', 'Hind 15 8765']\n assert candidate([\"YY 21 3456\", \"HS 18 8765\", \"AB 09 4321\", \"15 9876\", \"XX 13 8765\"]) == ['Hind 09 4321', 'Hind 13 8765', 'Hind 15 9876', 'Hind 18 8765', 'Hind 21 3456']"} { "task_id": "PythonSaga/163","prompt":"from typing import List\ndef introduction(n:int ,name: List[str]) -> List[str]:\n \"\"\"Utilize decorators and closure to create a name directory using provided information about individuals, \n including first name, last name, age, and sex. Display their names in a designated format, \n sorted in ascending order based on age. The output should list the names of the \n youngest individuals first, and for individuals of the same age, maintain the order of their input. \n Take input from the user for the number of individuals, and then for each individual. \n Example: \n Input: 3, [['amit', 'yadav', 23, 'm'], ['amit', 'jain', 12, 'm'], ['ankita', 'did', 23, 'f']]\n Output: ['Mr. amit jain', 'Mr. amit yadav', 'Ms. ankita did']\"\"\"\n ","entry_point":"introduction","canonical_solution":"def name_directory_decorator(func):\n def wrapper(name: List[List[str]]):\n # Process the input list: format names and sort by age\n processed_list = sorted(name, key=lambda x: x[2]) # Sort by age\n formatted_list = [(\"Mr. \" if person[3] == \"m\" else \"Ms. \") + person[0] + \" \" + person[1] for person in processed_list]\n return func(formatted_list)\n return wrapper\n\n@name_directory_decorator\ndef introduction(name: List[str]) -> List[str]:\n return name","test":"METADATA = {\n 'author': 'ay',\n 'dataset': 'test'\n}\n\ndef check(candidate):\n assert candidate([['amit', 'yadav', 23, 'm'], ['amit', 'jain', 12, 'm'], ['ankita', 'did', 23, 'f']]) == ['Mr. amit jain', 'Mr. amit yadav', 'Ms. ankita did']\n assert candidate([['john', 'doe', 30, 'm'], ['jane', 'smith', 25, 'f'], ['alice', 'jones', 25, 'f']]) == ['Ms. jane smith', 'Ms. alice jones', 'Mr. john doe']\n assert candidate([['bob', 'brown', 22, 'm'], ['emma', 'white', 22, 'f'], ['david', 'lee', 22, 'm']]) == ['Mr. bob brown', 'Ms. emma white', 'Mr. david lee']\n assert candidate([['sam', 'johnson', 18, 'm'], ['sarah', 'miller', 17, 'f'], ['mark', 'anderson', 19, 'm']]) == ['Ms. sarah miller', 'Mr. sam johnson', 'Mr. mark anderson']"} { "task_id": "PythonSaga/164","prompt":"from typing import List\ndef mat_sum(n:int, m:int, matrix: List[List[int]]) -> int:\n \"\"\"I have an n*m matrix, filled with positive integers. \n I want to find the path in this matrix, from top left to bottom right, \n that minimizes the sum of the integers along the path. \n Try to use decorator and closure to solve this problem. \n Take input from the user of n * m matrix and print the minimum sum of the integers along the path. \n\n Example: \n Input: 3,3,[[1,3,1],[1,5,1],[4,2,1]]\n Output: 7\n Input: 2,3,[[1,2,3],[4,5,6]]\n Output: 12\"\"\"\n ","entry_point":"mat_sum","canonical_solution":"def min_path_decorator(func):\n def wrapper(n, m, matrix):\n return func(n, m, matrix)\n return wrapper\n\n@min_path_decorator\ndef mat_sum(n: int, m: int, matrix: List[List[int]]) -> int:\n # Dynamic Programming to calculate the minimum path sum\n for i in range(n):\n for j in range(m):\n if i == 0 and j == 0: # Skip the top-left corner\n continue\n elif i == 0: # Top row, can only come from the left\n matrix[i][j] += matrix[i][j-1]\n elif j == 0: # Leftmost column, can only come from above\n matrix[i][j] += matrix[i-1][j]\n else: # Interior cell, take the minimum of the top and left cells\n matrix[i][j] += min(matrix[i-1][j], matrix[i][j-1])\n return matrix[n-1][m-1] # The minimum path sum is in the bottom-right corner","test":"METADATA = {\n 'author': 'ay',\n 'dataset': 'test'\n}\n\ndef check(candidate):\n assert candidate(3, 3, [[1, 3, 1], [1, 5, 1], [4, 2, 1]]) == 7\n assert candidate(2, 3, [[1, 2, 3], [4, 5, 6]]) == 12\n assert candidate(3, 3, [[5, 2, 7], [8, 1, 9], [4, 3, 6]]) == 17\n assert candidate(3, 3, [[1, 1, 1], [1, 1, 1], [1, 1, 1]]) == 5"} { "task_id": "PythonSaga/165","prompt":"from typing import List\nimport concurrent.futures \ndef sum_divisible_by_3(n: int, pairs: List[List[int]]) -> List[int]:\n \"\"\"I want to implement concurrency and parallelism in code for faster execution. \n Take input from the user for n pair of numbers (a,b) where a int:\n \"\"\"Calculate the sum of numbers divisible by 3 within the given range (a, b], where b is inclusive.\"\"\"\n a, b = pair\n # Start from the next number if 'a' is not divisible by 3\n start = a + 1 if a % 3 != 0 else a\n return sum(x for x in range(start, b + 1) if x % 3 == 0)\n\ndef sum_divisible_by_3(n: int, pairs: List[List[int]]) -> List[int]:\n results = []\n with concurrent.futures.ThreadPoolExecutor() as executor:\n # Submit tasks to the executor for each pair\n futures = [executor.submit(sum_divisible_by_3_in_range, pair) for pair in pairs]\n for future in concurrent.futures.as_completed(futures):\n # Collect the results as they are completed\n results.append(future.result())\n return results","test":"METADATA = {\n 'author': 'ay',\n 'dataset': 'test'\n}\n\ndef check(candidate):\n assert candidate(2, [[1, 10], [3, 5]]) == [18, 0] \n assert candidate(3, [[2, 8], [5, 15], [1, 5]]) == [9, 27, 3] \n assert candidate(1, [[3, 9]]) == [15] \n assert candidate(4, [[1, 5], [6, 10], [11, 15], [16, 20]]) == [3, 9, 27, 18]"} { "task_id": "PythonSaga/166","prompt":"import threading \nimport concurrent.futures\nfrom typing import List \ndef matrix_multiplication(n: int, matrix: List[List[int]]) -> List[List[int]]:\n \"\"\"I want to implement matrix multiplication of n matrices each of size 3x3. \n Each matrix element is [n,n+1,n+2,n+3,n+4,n+5,n+6,n+7,n+8]. \n But I want to do this process concurrently and parallely using threads. \n Take input from the user for the number of matrices and n for each matrix and return the result. \n Example: \n Input: 3, [3,4,5]\n 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]]] \n # 3 matrices of size 3x3 and result of multiplication of 3 matrices\n \"\"\"\n","entry_point":"matrix_multiplication","canonical_solution":"","test":"METADATA = {\n 'author': 'ay',\n 'dataset': 'test'\n}\n\ndef check(candidate):\n assert candidate(3, [3, 4, 5]) == [\n [[3, 4, 5], [6, 7, 8], [9, 10, 11]],\n [[4, 5, 6], [7, 8, 9], [10, 11, 12]],\n [[5, 6, 7], [8, 9, 10], [11, 12, 13]],\n [[114, 126, 138], [156, 174, 192], [198, 222, 246]]\n ]\n assert candidate(2, [1, 2]) == [\n [[1, 2, 3], [4, 5, 6], [7, 8, 9]],\n [[2, 3, 4], [5, 6, 7], [8, 9, 10]],\n [[36, 42, 48], [81, 96, 111], [126, 150, 174]]\n ]\n assert candidate(1, [0]) == [\n [[0, 1, 2], [3, 4, 5], [6, 7, 8]], \n [[0, 1, 2], [3, 4, 5], [6, 7, 8]]\n ]"} { "task_id": "PythonSaga/167","prompt":"import time \nimport multiprocessing \nimport concurrent.futures \nfrom typing import List\ndef input_func(a:int, b:int) -> List[str]:\n \"\"\"I want to learn how concurrency and parallelism works in python. \n To do that i want to calculate pow(a,b) using for loops. \n I want to do this using concurrent.futures and multiprocessing module. \n Take input from the user for a and b and return time taken by both functions to complete the task in nano seconds. \n If time taken is greater than 0 return True else False. \n Example: \n Input: 2, 1000\n Output: [Time taken by concurently_done is True, Time taken by parallel_done is True]\"\"\"\n ","entry_point":"input_func","canonical_solution":"","test":"METADATA = {\n 'author': 'ay',\n 'dataset': 'test'\n}\n\ndef check(candidate):\n assert candidate(2, 1000) == ['Time taken by concurrently_done is True', 'Time taken by parallel_done is True']\n assert candidate(3, 500) == ['Time taken by concurrently_done is True', 'Time taken by parallel_done is True']\n assert candidate(5, 200) == ['Time taken by concurrently_done is True', 'Time taken by parallel_done is True']\n assert candidate(10, 100) == ['Time taken by concurrently_done is True', 'Time taken by parallel_done is True']"} { "task_id": "PythonSaga/168","prompt":"import concurrent.futures \nfrom typing import List\ndef conc_work(n: int, tasks: List[int]) -> List[str]:\n \"\"\"I want to learn how concurrent processes work in Python. To do that take multiple tasks and their duration to complete their work. \n Your goal is to create a program that executes these tasks concurrently to reduce overall processing time. \n In the end, you should be able to see the total time taken to complete all tasks. \n 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. \n example: \n Input: 4, [3,5,2,4] # 4 tasks with duration 3,5,2,4\n Output: [\"Executing Task C...\", \"Executing Task A...\", \"Executing Task D...\", \"Executing Task B...\", True]\"\"\"\n ","entry_point":"conc_work","canonical_solution":"def simulate_task(duration: int, task_name: str) -> str:\n \"\"\"Simulate a task that takes 'duration' seconds to complete.\"\"\"\n print(f\"Executing Task {task_name}...\")\n time.sleep(duration)\n return f\"Task {task_name} completed.\"\n\ndef conc_work(n: int, tasks: List[int]) -> List[str]:\n start_time = time.time()\n results = []\n task_names = [\"A\", \"B\", \"C\", \"D\", \"E\", \"F\", \"G\", \"H\", \"I\", \"J\"][:n] # Generate task names\n\n with concurrent.futures.ThreadPoolExecutor(max_workers=n) as executor:\n # Schedule the tasks concurrently\n future_to_task = {executor.submit(simulate_task, task, task_names[i]): i for i, task in enumerate(tasks)}\n for future in concurrent.futures.as_completed(future_to_task):\n task_name = task_names[future_to_task[future]]\n try:\n result = future.result()\n except Exception as exc:\n results.append(f\"Task {task_name} generated an exception: {exc}\")\n else:\n results.append(result)\n\n total_time = time.time() - start_time\n results.append(True if total_time > 0 else False)\n return results","test":"METADATA = {\n 'author': 'ay',\n 'dataset': 'test'\n}\n\ndef check(candidate):\n assert candidate(4, [3, 5, 2, 4]) == [\"Executing Task C...\", \"Executing Task A...\", \"Executing Task D...\", \"Executing Task B...\", True]\n assert candidate(3, [2, 4, 1]) == [\"Executing Task C...\", \"Executing Task A...\", \"Executing Task B...\", True]\n assert candidate(5, [1, 2, 3, 4, 5]) == [\"Executing Task A...\", \"Executing Task B...\", \"Executing Task C...\", \"Executing Task D...\", \"Executing Task E...\", True]\n assert candidate(2, [5, 3]) == [\"Executing Task B...\", \"Executing Task A...\", True]"} { "task_id": "PythonSaga/169","prompt":"import concurrent.futures\nfrom typing import List\ndef math_tasks(n: int, tasks: List[int]) -> List[str]:\n \"\"\"I want to implement concurrency and parallelism in code for faster execution. \n Take input from user for n tasks and their parameters. \n Print the result of each task. If parameters are invalid return \"Not Done\". else return \"Done\". \n Example: \n Input: 4, [1000000, 500000, 750000, 200000]\n Output: [\"Performing Task A...\", \"Performing Task B...\", \"Performing Task C...\", \"Performing Task D...\", \"Done\", \"Done\", \"Done\", \"Done\"]\"\"\"\n ","entry_point":"math_tasks","canonical_solution":"def perform_task(param: int) -> str:\n \"\"\"Simulate a math task that computes the sum of numbers up to 'param'.\n If 'param' is invalid, returns 'Not Done'.\"\"\"\n if param < 0:\n return \"Not Done\"\n result = sum(range(param + 1)) # Example task: sum of numbers up to 'param'\n return \"Done\"\n\ndef math_tasks(n: int, tasks: List[int]) -> List[str]:\n results = []\n with concurrent.futures.ThreadPoolExecutor(max_workers=n) as executor:\n # Schedule the tasks concurrently\n future_to_task = {executor.submit(perform_task, task): i for i, task in enumerate(tasks)}\n for future in concurrent.futures.as_completed(future_to_task):\n task_id = future_to_task[future]\n try:\n result = future.result()\n except Exception as exc:\n results.append(f\"Task {task_id} generated an exception: {exc}\")\n else:\n results.append(f\"Performing Task {chr(65 + task_id)}...\") # Task A, B, C, etc.\n results.append(result)\n return results","test":"METADATA = {\n 'author': 'ay',\n 'dataset': 'test'\n}\n\ndef check(candidate):\n assert candidate(4, [1000000, 500000, 750000, 200000]) == [\n \"Performing Task A...\",\n \"Performing Task B...\",\n \"Performing Task C...\",\n \"Performing Task D...\",\n \"Done\",\n \"Done\",\n \"Done\",\n \"Done\"\n ]\n assert candidate(3, [200, 500, 1000]) == [\n \"Performing Task A...\",\n \"Performing Task B...\",\n \"Performing Task C...\",\n \"Done\",\n \"Done\",\n \"Done\"\n ]\n assert candidate(2, [5, 10]) == [\n \"Performing Task A...\",\n \"Performing Task B...\",\n \"Done\",\n \"Done\"\n ]\n assert candidate(1, [3]) == [\n \"Performing Task A...\",\n \"Done\"\n ]"} { "task_id": "PythonSaga/170","prompt":"from typing import List\ndef input_for_class1(coffs:List[List[int]])->List[str]:\n \"\"\"Create a Python class named Polynomial that represents a polynomial of a single variable. \n The Polynomial class should support the following operations: \n 1. Initialization: The class should be initialized with a list of coefficients in decreasing order of powers. \n For example, Polynomial([1, -3, 0, 2]) represents the polynomial 1x^3 - 3x^2 + 2. \n 2. String Representation: Implement a __str__ method that returns a human-readable string representation of the polynomial. \n For example, if the polynomial is Polynomial([1, -3, 0, 2]), the __str__ method should return the string \"x^3 - 3x^2 + 2\". \n 3. Addition and Subtraction: Implement methods add and subtract that take another Polynomial object as an argument and return a \n new Polynomial object representing the sum or difference of the two polynomials, respectively. \n Take input from the user for the coefficients of the two polynomials and create two Polynomial objects. \n Example: \n Input: [[1, -3, 0, 2], [2, 0, 1]] # cofficients of first polynomial, coefficients of second polynomial\n 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\n Input: [[1, 2, 3], [3, 2, 1]]\n Output: [\"x^2 + 2x + 3\", \"3x^2 + 2x + 1\", \"4x^2 + 4x + 4\", \"-2x^2 +2\"]\"\"\"\n","entry_point":"input_for_class1","canonical_solution":"class Polynomial:\n def __init__(self, coeffs: List[int]):\n self.coeffs = coeffs\n\n def __str__(self):\n terms = []\n n = len(self.coeffs)\n for i, coeff in enumerate(self.coeffs):\n power = n - i - 1\n if coeff == 0:\n continue\n if power == 0:\n terms.append(str(coeff))\n elif power == 1:\n terms.append(f\"{coeff}x\" if coeff != 1 else \"x\")\n else:\n terms.append(f\"{coeff}x^{power}\" if coeff != 1 else f\"x^{power}\")\n return \" + \".join(terms).replace(\"+ -\", \"- \")\n\n def add(self, other):\n max_len = max(len(self.coeffs), len(other.coeffs))\n result_coeffs = [0] * max_len\n for i in range(max_len):\n coeff1 = self.coeffs[-i-1] if i < len(self.coeffs) else 0\n coeff2 = other.coeffs[-i-1] if i < len(other.coeffs) else 0\n result_coeffs[-i-1] = coeff1 + coeff2\n return Polynomial(result_coeffs)\n\n def subtract(self, other):\n max_len = max(len(self.coeffs), len(other.coeffs))\n result_coeffs = [0] * max_len\n for i in range(max_len):\n coeff1 = self.coeffs[-i-1] if i < len(self.coeffs) else 0\n coeff2 = other.coeffs[-i-1] if i < len(other.coeffs) else 0\n result_coeffs[-i-1] = coeff1 - coeff2\n return Polynomial(result_coeffs)\n\ndef input_for_class1(coffs: List[List[int]]) -> List[str]:\n poly1 = Polynomial(coffs[0])\n poly2 = Polynomial(coffs[1])\n sum_poly = poly1.add(poly2)\n diff_poly = poly1.subtract(poly2)\n return [str(poly1), str(poly2), str(sum_poly), str(diff_poly)]","test":"METADATA = {\n 'author': 'ay',\n 'dataset': 'test'\n}\n\ndef check(candidate):\n assert candidate([[1, -3, 0, 2], [2, 0, 1]]) == ['x^3 - 3x^2 + 2', '2x^2 + 1', 'x^3 - x^2 + 3', 'x^3 - 5x^2-1']\n assert candidate([[1, 2, 3], [3, 2, 1]]) == ['x^2 + 2x + 3', '3x^2 + 2x + 1', '4x^2 + 4x + 4', '-2x^2 +2']\n assert candidate([[5, 0, 0, 1], [0, -2, 1]]) == ['5x^3 + 1', '-2x + 1', '5x^3 - 2x^2 + 1', '5x^3 + 2x']\n assert candidate([[1, 1, 1, 1], [1, 1, 1]]) == ['x^3 + x^2 + x + 1', 'x^2 + x + 1', 'x^3 + 2x^2 + 2x + 2', 'x^3']"} { "task_id": "PythonSaga/171","prompt":"from typing import List\n\ndef input_for_class2(entries:List[str])->str:\n \"\"\"I want to see magic using class and object. Let's say i have a class named \"Person\".\n In object i will pass name, id nummber, salary and position. Then i want to print all the information of that object.\n 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\n 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.\n 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.\n Example:\n Input: [\"John\", 1234, 10000, \"Manager\"]\n Output: \"My name is John, My id number is 1234, My salary is 10000 and my position is Manager.\"\n Input: [\"Ram\", 12223, 20000, \"CEO\"]\n Output: \"My name is Ram, My id number is 12223, My salary is 20000 and my position is CEO.\"\n \"\"\"","entry_point":"input_for_class2","canonical_solution":"class Person:\n def __init__(self, name: str, id_number: int):\n self.name = name\n self.id_number = id_number\n\nclass Employee(Person):\n def __init__(self, name: str, id_number: int, salary: int, position: str):\n super().__init__(name, id_number)\n self.salary = salary\n self.position = position\n\n def print_information(self):\n 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}.\"\n\n# Example usage:\ndef input_for_class2(entries: List[str]) -> str:\n name, id_number, salary, position = entries\n employee = Employee(name, int(id_number), int(salary), position)\n return employee.print_information()","test":"METADATA = {\n 'author': 'ay',\n 'dataset': 'test'\n}\n\ndef check(candidate):\n assert candidate([\"John\", \"1234\", \"10000\", \"Manager\"]) == \"My name is John, My id number is 1234, My salary is 10000 and my position is Manager.\"\n assert candidate([\"Ram\", \"12223\", \"20000\", \"CEO\"]) == \"My name is Ram, My id number is 12223, My salary is 20000 and my position is CEO.\"\n assert candidate([\"Alice\", \"5678\", \"15000\", \"Engineer\"]) == \"My name is Alice, My id number is 5678, My salary is 15000 and my position is Engineer.\"\n assert candidate([\"Bob\", \"9876\", \"12000\", \"Developer\"]) == \"My name is Bob, My id number is 9876, My salary is 12000 and my position is Developer.\"\n"} { "task_id": "PythonSaga/172","prompt":"def input_for_class3(typess:str)->str:\n \"\"\"I want to test my knowledge of polymorphism. \n I want to create a car catalog using classes and polymorphism. \n On top we have class Car, with description \"Welcome to car catalog, here you can find all the cars you need.\" \n Let's say I have class name sedan, suv, coupe, hatchback, and truck. \n 1. Sedan class displays \" This is a sedan car with 4 doors and 5 seats, usage is for family.\" \n 2. SUV class displays \" This is a SUV car with 4 doors and 5 seats, usage is for offroad.\" \n 3. Coupe class displays \" This is a coupe car with 2 doors and 2 seats, usage is for sport.\" \n 4. Hatchback class displays \" This is a hatchback car with 4 doors and 5 seats, usage is for small family.\" \n 5. Truck class displays \" This is a truck car with 2 doors and 3 seats, usage is for work.\" \n when user inputs the car type, it will display the description of the of class car and the description of the car type. \n Take input from user and display the description of the car type. \n Example: \n Input: sedan\n 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.\n Input: suv\n 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.\"\"\"\n","entry_point":"input_for_class3","canonical_solution":"class Car:\n def __init__(self):\n self.description = \"Welcome to car catalog, here you can find all the cars you need.\"\n\n def get_description(self):\n return self.description\n\nclass Sedan(Car):\n def __init__(self):\n super().__init__()\n self.description += \" This is a sedan car with 4 doors and 5 seats, usage is for family.\"\n\nclass SUV(Car):\n def __init__(self):\n super().__init__()\n self.description += \" This is a SUV car with 4 doors and 5 seats, usage is for offroad.\"\n\nclass Coupe(Car):\n def __init__(self):\n super().__init__()\n self.description += \" This is a coupe car with 2 doors and 2 seats, usage is for sport.\"\n\nclass Hatchback(Car):\n def __init__(self):\n super().__init__()\n self.description += \" This is a hatchback car with 4 doors and 5 seats, usage is for small family.\"\n\nclass Truck(Car):\n def __init__(self):\n super().__init__()\n self.description += \" This is a truck car with 2 doors and 3 seats, usage is for work.\"\n\n# Example usage:\ndef input_for_class3(typess: str) -> str:\n car_types = {\n 'sedan': Sedan(),\n 'suv': SUV(),\n 'coupe': Coupe(),\n 'hatchback': Hatchback(),\n 'truck': Truck(),\n }\n\n if typess.lower() in car_types:\n return car_types[typess.lower()].get_description()\n else:\n return \"Invalid car type. Please choose from sedan, suv, coupe, hatchback, or truck.\"","test":"METADATA = {\n 'author': 'ay',\n 'dataset': 'test'\n}\n\n\ndef check(candidate):\n 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.\"\n 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.\"\n 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.\"\n 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.\"\n 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.\"\n"} { "task_id": "PythonSaga/173","prompt":"from typing import List\ndef input_for_class4(data:List[str])->List[str]:\n \"\"\"Create a Python class named BankAccount that represents a bank account. \n The BankAccount class should support the following operations: \n 1. Initialization: The class should be initialized with an account holder's name and an initial balance. \n 2. Deposit and Withdrawal: Implement methods deposit and withdraw that allow the account holder to deposit and withdraw funds, respectively. \n Ensure that withdrawals do not exceed the available balance. # \"Withdrawal amount exceeds available balance.\"\n 3. Balance Inquiry: Implement a method get_balance that returns the current balance. \n 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. \n Example \n Input: [\"John\", 1000, \"Deposit\", 500, \"Withdraw\", 200, \"Balance\", \"Exit\" ]\n Output: [\"Your current balance is 1300\"]\"\"\"","entry_point":"input_for_class4","canonical_solution":"from typing import List\nclass BankAccount:\n def __init__(self, name: str, initial_balance: float):\n self.name = name\n self.balance = initial_balance\n\n def deposit(self, amount: float):\n self.balance += amount\n\n def withdraw(self, amount: float):\n if amount > self.balance:\n return \"Withdrawal amount exceeds available balance.\"\n self.balance -= amount\n\n def get_balance(self):\n return self.balance\n\ndef input_for_class4(data: List[str]) -> List[str]:\n account = BankAccount(data[0], float(data[1]))\n i = 2 # Start from the third item in the list, which is the first operation\n output = []\n\n while i < len(data):\n operation = data[i]\n if operation == \"Deposit\":\n i += 1\n account.deposit(float(data[i]))\n elif operation == \"Withdraw\":\n i += 1\n withdrawal_message = account.withdraw(float(data[i]))\n if withdrawal_message:\n output.append(withdrawal_message)\n elif operation == \"Balance\":\n output.append(f\"Your current balance is {account.get_balance()}\")\n elif operation == \"Exit\":\n break\n i += 1\n\n return output","test":"def check(candidate):\n assert candidate([\"John\", \"1000\", \"Deposit\", \"500\", \"Withdraw\", \"200\", \"Balance\", \"Exit\"]) == [\"Your current balance is 1300\"]\n assert candidate([\"Alice\", \"1500\", \"Deposit\", \"300\", \"Balance\", \"Withdraw\", \"200\", \"Exit\"]) == [\"Your current balance is 1800\", \"Your current balance is 1600\"]\n assert candidate([\"Bob\", \"500\", \"Withdraw\", \"700\", \"Deposit\", \"200\", \"Balance\", \"Exit\"]) == [\"Withdrawal amount exceeds available balance.\", \"Your current balance is 700\"]\n assert candidate([\"Eve\", \"2000\", \"Withdraw\", \"500\", \"Deposit\", \"1000\", \"Balance\", \"Exit\"]) == [\"Your current balance is 2500\"]\n"} { "task_id": "PythonSaga/174","prompt":"from typing import List\ndef input_for_class5(data:List[str])->List[str]:\n \"\"\"You are tasked with designing a Python class to manage and monitor activities at a construction site. \n The class should encapsulate various aspects of construction management. Implement the following functionalities: \n Initialization: The class should be initialized with the construction site's name and the initial budget. \n Material Inventory: Implement methods to add materials to the construction site's inventory and retrieve the current inventory status. \n Worker Management: Implement methods to add and remove workers from the construction site. Each worker has a unique identifier, and name. \n Budget Tracking: Implement methods to track expenses and remaining budget. Ensure that expenses are deducted from the budget \n when materials are purchased or workers are hired. \n Progress Monitoring: Implement a method to monitor the overall progress of the construction site based on completed tasks and remaining tasks. \n Take apporpriate input from the user to test your class. You may use the following sample input/output to test your class: \n Example: \n 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\"]\n 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'}]\"\"\"","entry_point":"input_for_class5","canonical_solution":"class ConstructionSite:\n def __init__(self, name: str, initial_budget: float):\n self.name = name\n self.budget = initial_budget\n self.material_inventory = {}\n self.workers = {}\n\n def add_material(self, material_name: str, quantity: int):\n if material_name in self.material_inventory:\n self.material_inventory[material_name] += quantity\n else:\n self.material_inventory[material_name] = quantity\n\n def get_material_inventory(self):\n return self.material_inventory\n\n def add_worker(self, worker_name: str, worker_id: int):\n self.workers[worker_id] = worker_name\n\n def remove_worker(self, worker_id: int):\n if worker_id in self.workers:\n del self.workers[worker_id]\n\n def get_workers(self):\n return self.workers\n\n def track_expense(self, expense: float):\n self.budget -= expense\n\n def get_budget(self):\n return self.budget\n\n def monitor_progress(self, status: str):\n if status.lower() == \"completed\":\n return f\"Construction site {self.name} has been completed.\"\n elif status.lower() == \"in progress\":\n return f\"Construction site {self.name} is still in progress.\"\n else:\n return \"Invalid progress status.\"\n\n# Example usage:\ndef input_for_class5(data: List[str]) -> List[str]:\n construction_site_name = data[0]\n initial_budget = float(data[1])\n construction_site = ConstructionSite(construction_site_name, initial_budget)\n\n results = []\n i = 2\n while i < len(data):\n action = data[i]\n if action.lower() == \"material addition\":\n material_name = data[i + 1]\n quantity = int(data[i + 2])\n construction_site.add_material(material_name, quantity)\n i += 3\n elif action.lower() == \"worker addition\":\n worker_name = data[i + 1]\n worker_id = int(data[i + 2])\n construction_site.add_worker(worker_name, worker_id)\n i += 3\n elif action.lower() == \"worker removal\":\n worker_id = int(data[i + 1])\n construction_site.remove_worker(worker_id)\n i += 2\n elif action.lower() == \"status update\":\n status = data[i + 1]\n progress = construction_site.monitor_progress(status)\n results.append(progress)\n i += 2\n elif action.lower() == \"exit\":\n break\n\n 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()}\")\n return results","test":"METADATA = {'author': 'ay', 'dataset': 'test'}\n\ndef check(candidate):\n 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'}']\n 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'}']\n 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'}']\n 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 {}']"} { "task_id": "PythonSaga/175","prompt":"from typing import List\ndef input_for_cont1(data:str)->List[str]:\n \"\"\"I want to create dummy context manager. \n Here's it should be: \n 1. create class ContextManager \n 2. When I call it, it should print \"init method called\" \n 3. When I call it with \"with\" statement, it should print \"enter method called\" \n 4. When I exit from \"with\" statement, it should print \"exit method called\" \n 5. Before exit from \"with\" statement, it should print \"XXXX\" (XXXX - any text from user)\n Take XXXX from user and print all 4 messages in order mentioned above. \n Example: \n Input: \"Hello i'm in context manager\"\n Output: [\"init method called\", \"enter method called\", \"Hello i'm in context manager\", \"exit method called\"]\"\"\"","entry_point":"input_for_cont1","canonical_solution":"class ContextManager:\n def __init__(self, text: str):\n self.text = text\n print(\"init method called\")\n\n def __enter__(self):\n print(\"enter method called\")\n return self\n\n def __exit__(self, exc_type, exc_val, exc_tb):\n print(self.text)\n print(\"exit method called\")\n\ndef input_for_cont1(data: str) -> List[str]:\n messages = []\n\n # Define a function to capture print statements\n def mock_print(*args, **kwargs):\n messages.append(' '.join(map(str, args)))\n\n # Replace the built-in print function with mock_print within this context\n original_print = __builtins__.print\n __builtins__.print = mock_print\n\n # Use the ContextManager with the provided data\n with ContextManager(data):\n pass\n\n # Restore the original print function\n __builtins__.print = original_print\n\n return messages","test":"METADATA = {'author': 'ay', 'dataset': 'test'}\n\ndef check(candidate):\n assert candidate(\"Hello i'm in context manager\") == [\"init method called\", \"enter method called\", \"Hello i'm in context manager\", \"exit method called\"]"} { "task_id": "PythonSaga/176","prompt":"from decimal import Decimal, getcontext\ndef input_for_cont2(data:str)->str:\n \"\"\"I'm working in space and astronomy institute where calculations need to be \n done in a very precise way. I'm working on a project where I need to calculate. \n Small part of it is division of two numbers which need to be very precise upto \n n decimal places. \n Take input from user for two numbers and precision value n. and return the \n result upto n decimal places in form of string. \n You should use context manager to set precision value. \n Example: \n Input: 1, 42, 42 # 1 is a, 42 is b, 42 is precision value\n Output: \"0.0238095238095238095238095238095238095238095\"\n \"\"\"","entry_point":"input_for_cont2","canonical_solution":"# Set the precision\ngetcontext().prec = n\n\n# Perform the division using Decimal for high precision\nresult = Decimal(a) / Decimal(b)\n\n# Reset the precision to default (28) to avoid side effects\ngetcontext().prec = 28\n\nreturn str(result) # Convert the result to a string","test":"METADATA = {'author': 'ay', 'dataset': 'test'}\n\ndef check(candidate):\n assert candidate(\"1,42,42\") == \"0.0238095238095238095238095238095238095238095\"\n assert candidate(\"3,7,9\") == \"0.428571429\"\n assert candidate(\"3,7,9\") == \"0.428571428571428571428571428571429\""} { "task_id": "PythonSaga/177","prompt":"from decimal import Decimal, getcontext\ndef input_for_cont3(data:str)->str:\n \"\"\"I'm working in science lab where experminets and their calculations \n done in a very precise way. I'm working on a project where I need to calculate. \n Small part of it is division of two numbers which need to be very precise upto \n n decimal places. \n Take input from user for two numbers and precision value n. and return the \n result upto n decimal places in form of string. \n You should use context manager to set precision value. \n Example: \n Input: 1, 42, 42 # 1 is a, 42 is b, 42 is precision value\n Output: \"0.0238095238095238095238095238095238095238095\"\n \"\"\"","entry_point":"input_for_cont3","canonical_solution":"","test":"METADATA = {'author': 'ay', 'dataset': 'test'}\n\ndef check(candidate):\n assert candidate(\"1,42,42\") == \"0.0238095238095238095238095238095238095238095\"\n assert candidate(\"3,7,9\") == \"0.428571429\"\n assert candidate(\"3,7,9\") == \"0.428571428571428571428571428571429\""} { "task_id": "PythonSaga/178","prompt":"def divide(x:int, y:int) -> str:\n \"\"\"I have few codes which may or may not run successfully.\n I want to know what error it will print if it fails to run.\n And if it runs successfully, it should print the output.\n The code if for division of two numbers.\n Take two numbers as input from user and divide them.\n The error is: unsupported operand type(s) for //: 'int' and 'str' \n The error is: integer division or modulo by zero \n Example:\n Input: 5,2\n Output: \"2.5\"\n Input: 5,0\n Output: \"The error is: integer division or modulo by zero \"\"\"\n","entry_point":"divide","canonical_solution":"","test":"METADATA = {\n 'author': 'ay',\n 'dataset': 'test'\n}\n\ndef check(candidate):\n assert candidate(2,5) == \"0.4\"\n assert candidate(2,0) == \"integer division or modulo by zero\"\n assert candidate(1,5) == \"0.2\"\n assert candidate(11,0) == \"integer division or modulo by zero\""} { "task_id": "PythonSaga/179","prompt":"def write_file(first:str, second:str) -> str:\n \"\"\"I have a file named dummy.txt. I want to write some text in it i.e. \"This is a dummy file.\"\n Later I want to write some more text in it i.e. \"This is a dummy file2.\"\n But when I run the code, it gives me an error. I want to know what error it is, please print it.\n The error is: I/O operation on closed file.\"\"\"\n","entry_point":"write_file","canonical_solution":"","test":"METADATA = {\n 'author': 'ay',\n 'dataset': 'test'\n}\n\ndef check(candidate):\n assert candidate(\"This is a dummy file.\", \"This is a dummy file2.\") == \"I/O operation on closed file.\""} { "task_id": "PythonSaga/180","prompt":"def max_capacity(n:int, m:int) -> int:\n \"\"\"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.\n But the idea is the number of scoops to empty both bag should be natural number respectively.\n Also the scope should be of maximum capacity as possible.\n Take input from user for n and m and return the maximum capacity of scope.\n Try to use recursion to solve this problem.\n Example:\n Input: 3, 5\n Output: 1\n Input: 4,20\n Output: 4\n Input: 6,15\n Output: 3\"\"\"","entry_point":"max_capacity","canonical_solution":"if b == 0:\n return a\nreturn max_capacity(b, a % b)","test":"METADATA = {'author': 'ay', 'dataset': 'test'}\n\ndef check(candidate):\n assert candidate(3,5) == 1\n assert candidate(4,20) == 4 \n assert candidate(6,15) == 3\n assert candidate(26,39) == 13"} { "task_id": "PythonSaga/181","prompt":"def max_stencils(n:int, a:int, b:int, c:int) -> int:\n \"\"\"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.\n But in such a way that the number of stencils used to paint the wall should be maximum to bring out the best design.\n Also, the length of the wall should be completely covered by the stencils.\n Take input from user for n, a, b, and c and return the maximum number of stencils used to paint the wall.\n Try to use recursion to solve this problem.\n Example:\n Input: 23, 11, 9, 12\n Output: 2\n Input: 17, 10, 11, 3\n Output: 3\"\"\"","entry_point":"max_stencils","canonical_solution":"if n == 0 :\n return 0\nif n <= -1 :\n return -1 \nres = max(max_stencils(n-a,a,b,c),\n max_stencils(n-b,a,b,c),\n max_stencils(n-c,a,b,c))\nif res == -1 :\n return -1 \nreturn res + 1","test":"METADATA = {'author': 'ay', 'dataset': 'test'}\n\ndef check(candidate):\n assert candidate(23, 11, 9, 12) == 2\n assert candidate(17, 10, 11, 3) == 3\n assert candidate(18, 11, 9, 3) == 6\n assert candidate(21, 11, 9, 2) == 7"} { "task_id": "PythonSaga/182","prompt":"def round_chairs(n:int, k:int) -> int:\n \"\"\"I am playing a game of round chairs with my friends. Where n chairs are arranged in a circle.\n Every time a game starts the kth chair is removed from the circle and the game continues.\n 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.\n Take input from user for n and k and return the position of the last chair left in the circle.\n Try to use recursion to solve this problem.\n Example:\n Input: 14, 2\n Output: 13\n Input: 7, 3\n Output: 4\"\"\"","entry_point":"round_chairs","canonical_solution":"if (n == 1):\n return 1\nelse:\n return (round_chairs(n - 1, k) + k-1) % n + 1","test":"METADATA = {'author': 'ay', 'dataset': 'test'}\n\ndef check(candidate):\n assert candidate(14, 2) == 13\n assert candidate(7, 3) == 4\n assert candidate(10, 2) == 5\n assert candidate(11, 5) == 8"} { "task_id": "PythonSaga/183","prompt":"def qwerty_phone(key_presses: list) -> list:\n \"\"\"I saw the qwerty phones and i was thinking about the number of key presses to type a word.\n So, now I want to find the numbers of words that can be typed using the given number of key presses.\n My keypad looks like this:\n 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:{}\n 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.\n Try to use recursion to solve this problem.\n Example:\n Input: [2,3,4]\n 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']\"\"\"","entry_point":"qwerty_phone","canonical_solution":"digit_map = {\n '2': 'abc',\n '3': 'def',\n '4': 'ghi',\n '5': 'jkl',\n '6': 'mno',\n '7': 'pqrs',\n '8': 'tuv',\n '9': 'wxyz',\n}\n\ndef qwerty_phone(input):\n input = str(input)\n ret = ['']\n for char in input:\n letters = digit_map.get(char, '')\n ret = [prefix+letter for prefix in ret for letter in letters]\n return ret","test":"METADATA = {'author': 'ay', 'dataset': 'test'}\n\ndef check(candidate):\n 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']\n assert candidate([1]) == []\n assert candidate([2,3]) == ['ad', 'ae', 'af', 'bd', 'be', 'bf', 'cd', 'ce', 'cf']"} { "task_id": "PythonSaga/184","prompt":"def match_ptr(s:str, ptr:str) -> bool:\n \"\"\"Given an string s and a pattern ptr, implement pattern matching with support for '+' and '-' where:\n '+' Matches any single character.\n '-' Matches any sequence of characters (including the empty sequence).\n The matching should cover the entire input string (not partial).\n Take input from user for s and ptr and return True if the pattern matches the string, else False.\n Try to use recursion to solve this problem.\n Example:\n Input: s = \"aa\", ptr = \"a+\"\n Output: True\n Input: s = \"aa\", ptr = \"a\"\n Output: false\n \"\"\"","entry_point":"match_ptr","canonical_solution":"i, j, si, m = 0, 0, -1, 0\nwhile i < len(s):\n if j < len(p) and (s[i] == p[j] or p[j] == '+'):\n j += 1\n i += 1\n elif j < len(p) and p[j] == '-':\n si = j\n m = i\n j += 1\n elif si != -1:\n j = si + 1\n m += 1\n i = m\n else:\n return False\nwhile j < len(p) and p[j] == '-':\n j += 1\nreturn j == len(p)","test":"METADATA = {'author': 'ay', 'dataset': 'test'}\n\ndef check(candidate):\n assert candidate('aa', 'a+') == True\n assert candidate('aa','a') == False\n assert candidate('aab', '-a-') == True\n assert candidate('aab', '-a') == False"}