task_type
stringclasses
4 values
problem
stringlengths
14
5.23k
solution
stringlengths
1
8.29k
problem_tokens
int64
9
1.02k
solution_tokens
int64
1
1.98k
coding
Please solve the programming task below using a self-contained code snippet in a markdown code block. You are given two 0-indexed arrays of strings startWords and targetWords. Each string consists of lowercase English letters only. For each string in targetWords, check if it is possible to choose a string from startWords and perform a conversion operation on it to be equal to that from targetWords. The conversion operation is described in the following two steps: Append any lowercase letter that is not present in the string to its end. For example, if the string is "abc", the letters 'd', 'e', or 'y' can be added to it, but not 'a'. If 'd' is added, the resulting string will be "abcd". Rearrange the letters of the new string in any arbitrary order. For example, "abcd" can be rearranged to "acbd", "bacd", "cbda", and so on. Note that it can also be rearranged to "abcd" itself. Return the number of strings in targetWords that can be obtained by performing the operations on any string of startWords. Note that you will only be verifying if the string in targetWords can be obtained from a string in startWords by performing the operations. The strings in startWords do not actually change during this process.   Please complete the following python code precisely: ```python class Solution: def wordCount(self, startWords: List[str], targetWords: List[str]) -> int: ```
{"functional": "def check(candidate):\n assert candidate(startWords = [\"ant\",\"act\",\"tack\"], targetWords = [\"tack\",\"act\",\"acti\"]) == 2\n assert candidate(startWords = [\"ab\",\"a\"], targetWords = [\"abc\",\"abcd\"]) == 1\n\n\ncheck(Solution().wordCount)"}
311
80
coding
Solve the programming task below in a Python markdown code block. You are given N non-negative integers A_1, A_2, ..., A_N and another non-negative integer K. For a integer X between 0 and K (inclusive), let f(X) = (X XOR A_1) + (X XOR A_2) + ... + (X XOR A_N). Here, for non-negative integers a and b, a XOR b denotes the bitwise exclusive OR of a and b. Find the maximum value of f. What is XOR? The bitwise exclusive OR of a and b, X, is defined as follows: - When X is written in base two, the digit in the 2^k's place (k \geq 0) is 1 if, when written in base two, exactly one of A and B has 1 in the 2^k's place, and 0 otherwise. For example, 3 XOR 5 = 6. (When written in base two: 011 XOR 101 = 110.) -----Constraints----- - All values in input are integers. - 1 \leq N \leq 10^5 - 0 \leq K \leq 10^{12} - 0 \leq A_i \leq 10^{12} -----Input----- Input is given from Standard Input in the following format: N K A_1 A_2 ... A_N -----Output----- Print the maximum value of f. -----Sample Input----- 3 7 1 6 3 -----Sample Output----- 14 The maximum value is: f(4) = (4 XOR 1) + (4 XOR 6) + (4 XOR 3) = 5 + 2 + 7 = 14.
{"inputs": ["3 7\n1 6 3\n", "4 9\n7 4 0 3\n", "1 0\n1000000000000\n"], "outputs": ["14\n", "46\n", "1000000000000\n"]}
388
78
coding
Please solve the programming task below using a self-contained code snippet in a markdown code block. Given the root of a binary tree, return the length of the diameter of the tree. The diameter of a binary tree is the length of the longest path between any two nodes in a tree. This path may or may not pass through the root. The length of a path between two nodes is represented by the number of edges between them.   Please complete the following python code precisely: ```python # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def diameterOfBinaryTree(self, root: Optional[TreeNode]) -> int: ```
{"functional": "def check(candidate):\n assert candidate(root = tree_node([1,2,3,4,5])) == 3\n assert candidate(root = tree_node([1,2])) == 1\n\n\ncheck(Solution().diameterOfBinaryTree)"}
170
60
coding
Please solve the programming task below using a self-contained code snippet in a markdown code block. Suppose we have a file system that stores both files and directories. An example of one system is represented in the following picture: Here, we have dir as the only directory in the root. dir contains two subdirectories, subdir1 and subdir2. subdir1 contains a file file1.ext and subdirectory subsubdir1. subdir2 contains a subdirectory subsubdir2, which contains a file file2.ext. In text form, it looks like this (with ⟶ representing the tab character): dir ⟶ subdir1 ⟶ ⟶ file1.ext ⟶ ⟶ subsubdir1 ⟶ subdir2 ⟶ ⟶ subsubdir2 ⟶ ⟶ ⟶ file2.ext If we were to write this representation in code, it will look like this: "dir\n\tsubdir1\n\t\tfile1.ext\n\t\tsubsubdir1\n\tsubdir2\n\t\tsubsubdir2\n\t\t\tfile2.ext". Note that the '\n' and '\t' are the new-line and tab characters. Every file and directory has a unique absolute path in the file system, which is the order of directories that must be opened to reach the file/directory itself, all concatenated by '/'s. Using the above example, the absolute path to file2.ext is "dir/subdir2/subsubdir2/file2.ext". Each directory name consists of letters, digits, and/or spaces. Each file name is of the form name.extension, where name and extension consist of letters, digits, and/or spaces. Given a string input representing the file system in the explained format, return the length of the longest absolute path to a file in the abstracted file system. If there is no file in the system, return 0. Note that the testcases are generated such that the file system is valid and no file or directory name has length 0.   Please complete the following python code precisely: ```python class Solution: def lengthLongestPath(self, input: str) -> int: ```
{"functional": "def check(candidate):\n assert candidate(input = \"dir\\n\\tsubdir1\\n\\tsubdir2\\n\\t\\tfile.ext\") == 20\n assert candidate(input = \"dir\\n\\tsubdir1\\n\\t\\tfile1.ext\\n\\t\\tsubsubdir1\\n\\tsubdir2\\n\\t\\tsubsubdir2\\n\\t\\t\\tfile2.ext\") == 32\n assert candidate(input = \"a\") == 0\n assert candidate(input = \"file1.txt\\nfile2.txt\\nlongfile.txt\") == 12\n\n\ncheck(Solution().lengthLongestPath)"}
438
160
coding
Solve the programming task below in a Python markdown code block. Polycarp has $n$ friends, the $i$-th of his friends has $a_i$ candies. Polycarp's friends do not like when they have different numbers of candies. In other words they want all $a_i$ to be the same. To solve this, Polycarp performs the following set of actions exactly once: Polycarp chooses $k$ ($0 \le k \le n$) arbitrary friends (let's say he chooses friends with indices $i_1, i_2, \ldots, i_k$); Polycarp distributes their $a_{i_1} + a_{i_2} + \ldots + a_{i_k}$ candies among all $n$ friends. During distribution for each of $a_{i_1} + a_{i_2} + \ldots + a_{i_k}$ candies he chooses new owner. That can be any of $n$ friends. Note, that any candy can be given to the person, who has owned that candy before the distribution process. Note that the number $k$ is not fixed in advance and can be arbitrary. Your task is to find the minimum value of $k$. For example, if $n=4$ and $a=[4, 5, 2, 5]$, then Polycarp could make the following distribution of the candies: Polycarp chooses $k=2$ friends with indices $i=[2, 4]$ and distributes $a_2 + a_4 = 10$ candies to make $a=[4, 4, 4, 4]$ (two candies go to person $3$). Note that in this example Polycarp cannot choose $k=1$ friend so that he can redistribute candies so that in the end all $a_i$ are equal. For the data $n$ and $a$, determine the minimum value $k$. With this value $k$, Polycarp should be able to select $k$ friends and redistribute their candies so that everyone will end up with the same number of candies. -----Input----- The first line contains one integer $t$ ($1 \le t \le 10^4$). Then $t$ test cases follow. The first line of each test case contains one integer $n$ ($1 \le n \le 2 \cdot 10^5$). The second line contains $n$ integers $a_1, a_2, \ldots, a_n$ ($0 \le a_i \le 10^4$). It is guaranteed that the sum of $n$ over all test cases does not exceed $2 \cdot 10^5$. -----Output----- For each test case output: the minimum value of $k$, such that Polycarp can choose exactly $k$ friends so that he can redistribute the candies in the desired way; "-1" if no such value $k$ exists. -----Examples----- Input 5 4 4 5 2 5 2 0 4 5 10 8 5 1 4 1 10000 7 1 1 1 1 1 1 1 Output 2 1 -1 0 0 -----Note----- None
{"inputs": ["1\n2\n1 691\n", "1\n2\n1 691\n", "1\n3\n1 1 67\n", "1\n3\n1 1 67\n", "1\n3\n1 1 65\n", "1\n3\n0 1 65\n", "1\n3\n0 1 91\n", "1\n3\n0 0 91\n"], "outputs": ["1\n", "1\n", "1\n", "1\n", "-1\n", "1\n", "-1\n", "-1\n"]}
712
140
coding
Solve the programming task below in a Python markdown code block. Given an integer $n$. Consider all pairs of integer arrays $a$ and $p$ of the same length such that $n = \prod a_i^{p_i}$ (i.e. $a_1^{p_1}\cdot a_2^{p_2}\cdot\ldots$) ($a_i>1;p_i>0$) and $a_i$ is the product of some (possibly one) distinct prime numbers. For example, for $n = 28 = 2^2\cdot 7^1 = 4^1 \cdot 7^1$ the array pair $a = [2, 7]$, $p = [2, 1]$ is correct, but the pair of arrays $a = [4, 7]$, $p = [1, 1]$ is not, because $4=2^2$ is a product of non-distinct prime numbers. Your task is to find the maximum value of $\sum a_i \cdot p_i$ (i.e. $a_1\cdot p_1 + a_2\cdot p_2 + \ldots$) over all possible pairs of arrays $a$ and $p$. Note that you do not need to minimize or maximize the length of the arrays. -----Input----- Each test contains multiple test cases. The first line contains an integer $t$ ($1 \le t \le 1000$) — the number of test cases. Each test case contains only one integer $n$ ($2 \le n \le 10^9$). -----Output----- For each test case, print the maximum value of $\sum a_i \cdot p_i$. -----Examples----- Input 7 100 10 864 130056192 1000000000 2 999999018 Output 20 10 22 118 90 2 333333009 -----Note----- In the first test case, $100 = 10^2$ so that $a = [10]$, $p = [2]$ when $\sum a_i \cdot p_i$ hits the maximum value $10\cdot 2 = 20$. Also, $a = [100]$, $p = [1]$ does not work since $100$ is not made of distinct prime factors. In the second test case, we can consider $10$ as $10^1$, so $a = [10]$, $p = [1]$. Notice that when $10 = 2^1\cdot 5^1$, $\sum a_i \cdot p_i = 7$.
{"inputs": ["7\n100\n10\n864\n130056192\n1000000000\n2\n999999018\n"], "outputs": ["20\n10\n22\n118\n90\n2\n333333009\n"]}
615
84
coding
Solve the programming task below in a Python markdown code block. Read problems statements in Mandarin Chinese and Russian. Alice and Bob, both have to drink water. But they both don't want to go, so they will play a game to decide who will fetch water for both of them. Alice will choose a number randomly between 1 and N (both inclusive) and Bob will choose a number randomly between 1 and M (both inclusive). Both will write their numbers on a slip of paper. If sum of numbers choosen by both is odd, then Alice will go, else Bob will go. What is probability that Alice will go? ------ Input ------ First line contains, T, the number of testcases. Each testcase consists of N and M in one line, separated by a space. ------ Output ------ For each test case, output a single line containing probability as an irreducible fraction. ------ Constraints ------ $1 ≤ T ≤ 10^{5}$ $1 ≤ N,M ≤ 10^{9}$ ----- Sample Input 1 ------ 3 1 1 1 2 2 3 ----- Sample Output 1 ------ 0/1 1/2 1/2 ----- explanation 1 ------ #test1: The only way is when Alice and Bob both choose 1. So, Alice won't have to go because sum is even. #test2: The different ways are (1,1) and (1,2), where first term denotes the number choosen by Alice. So of all possible cases (ie. 2) in only 1 case Alice has to go. Therefore, probability is 1/2. #test3: The different ways are (1,1), (1,2), (1,3), (2,1), (2,2), (2,3) where first term denotes the number choosen by Alice. So of all possible cases (ie. 6) in only 3 cases Alice has to go. Therefore, probability is 1/2.
{"inputs": ["3\n1 1\n1 2\n2 3", "3\n1 1\n1 3\n2 3", "3\n1 2\n1 3\n2 3", "3\n1 1\n1 1\n2 3", "3\n1 1\n2 1\n2 3", "3\n1 3\n1 3\n2 2", "3\n1 1\n2 1\n1 3", "3\n1 2\n2 1\n2 3"], "outputs": ["0/1\n1/2\n1/2", "0/1\n1/3\n1/2\n", "1/2\n1/3\n1/2\n", "0/1\n0/1\n1/2\n", "0/1\n1/2\n1/2\n", "1/3\n1/3\n1/2\n", "0/1\n1/2\n1/3\n", "1/2\n1/2\n1/2\n"]}
428
237
coding
Solve the programming task below in a Python markdown code block. Given a list of unique words. Find all pairs of distinct indices (i, j) in the given list so that the concatenation of the two words, i.e. words[i] + words[j] is a palindrome. Examples: Non-string inputs should be converted to strings. Return an array of arrays containing pairs of distinct indices that form palindromes. Pairs should be returned in the order they appear in the original list. Also feel free to reuse/extend the following starter code: ```python def palindrome_pairs(words): ```
{"functional": "_inputs = [[['bat', 'tab', 'cat']], [['dog', 'cow', 'tap', 'god', 'pat']], [['abcd', 'dcba', 'lls', 's', 'sssll']], [[]], [['adgdfsh', 'wertewry', 'zxcbxcb', 'efveyn']], [[5, 2, 'abc', True, [False]]], [[5777, 'dog', 'god', True, 75]]]\n_outputs = [[[[0, 1], [1, 0]]], [[[0, 3], [2, 4], [3, 0], [4, 2]]], [[[0, 1], [1, 0], [2, 4], [3, 2]]], [[]], [[]], [[]], [[[0, 4], [1, 2], [2, 1]]]]\nimport math\ndef _deep_eq(a, b, tol=1e-5):\n if isinstance(a, float) or isinstance(b, float):\n return math.isclose(a, b, rel_tol=tol, abs_tol=tol)\n if isinstance(a, (list, tuple)):\n if len(a) != len(b): return False\n return all(_deep_eq(x, y, tol) for x, y in zip(a, b))\n return a == b\n\nfor i, o in zip(_inputs, _outputs):\n assert _deep_eq(palindrome_pairs(*i), o[0])"}
123
338
coding
Solve the programming task below in a Python markdown code block. Read problem statements in [Russian] and [Mandarin Chinese]. Given the time control of a chess match as a + b, determine which format of chess out of the given 4 it belongs to. 1) Bullet if a + b < 3 2) Blitz if 3 ≤ a + b ≤ 10 3) Rapid if 11 ≤ a + b ≤ 60 4) Classical if 60 < a + b ------ Input Format ------ - First line will contain T, number of testcases. Then the testcases follow. - Each testcase contains a single line of input, two integers a, b. ------ Output Format ------ For each testcase, output in a single line, answer 1 for bullet, 2 for blitz, 3 for rapid, and 4 for classical format. ------ Constraints ------ $1 ≤ T ≤ 1100$ $1 ≤ a ≤ 100$ $0 ≤ b ≤ 10$ ----- Sample Input 1 ------ 4 1 0 4 1 100 0 20 5 ----- Sample Output 1 ------ 1 2 4 3 ----- explanation 1 ------ TestCase $1$: Since $a + b = 1 < 3$, it belongs to bullet format. TestCase $2$: Since $3 ≤ (a + b = 5) ≤ 10$, it belongs to blitz format.
{"inputs": ["4\n1 0\n4 1\n100 0\n20 5\n"], "outputs": ["1\n2\n4\n3"]}
319
38
coding
Solve the programming task below in a Python markdown code block. You're given an array $a$. You should repeat the following operation $k$ times: find the minimum non-zero element in the array, print it, and then subtract it from all the non-zero elements of the array. If all the elements are 0s, just print 0. -----Input----- The first line contains integers $n$ and $k$ $(1 \le n,k \le 10^5)$, the length of the array and the number of operations you should perform. The second line contains $n$ space-separated integers $a_1, a_2, \ldots, a_n$ $(1 \le a_i \le 10^9)$, the elements of the array. -----Output----- Print the minimum non-zero element before each operation in a new line. -----Examples----- Input 3 5 1 2 3 Output 1 1 1 0 0 Input 4 2 10 3 5 3 Output 3 2 -----Note----- In the first sample: In the first step: the array is $[1,2,3]$, so the minimum non-zero element is 1. In the second step: the array is $[0,1,2]$, so the minimum non-zero element is 1. In the third step: the array is $[0,0,1]$, so the minimum non-zero element is 1. In the fourth and fifth step: the array is $[0,0,0]$, so we printed 0. In the second sample: In the first step: the array is $[10,3,5,3]$, so the minimum non-zero element is 3. In the second step: the array is $[7,0,2,0]$, so the minimum non-zero element is 2.
{"inputs": ["2 5\n2 3\n", "2 5\n2 3\n", "2 5\n4 3\n", "2 1\n4 3\n", "3 5\n1 2 3\n", "3 7\n1 2 3\n", "3 1\n6 1 7\n", "3 1\n6 6 7\n"], "outputs": ["2\n1\n0\n0\n0\n", "2\n1\n0\n0\n0\n", "3\n1\n0\n0\n0\n", "3\n", "1\n1\n1\n0\n0\n", "1\n1\n1\n0\n0\n0\n0\n", "1\n", "6\n"]}
407
170
coding
Solve the programming task below in a Python markdown code block. For encrypting strings this region of chars is given (in this order!): * all letters (ascending, first all UpperCase, then all LowerCase) * all digits (ascending) * the following chars: `.,:;-?! '()$%&"` These are 77 chars! (This region is zero-based.) Write two methods: ```python def encrypt(text) def decrypt(encrypted_text) ``` Prechecks: 1. If the input-string has chars, that are not in the region, throw an Exception(C#, Python) or Error(JavaScript). 2. If the input-string is null or empty return exactly this value! For building the encrypted string: 1. For every second char do a switch of the case. 2. For every char take the index from the region. Take the difference from the region-index of the char before (from the input text! Not from the fresh encrypted char before!). (Char2 = Char1-Char2) Replace the original char by the char of the difference-value from the region. In this step the first letter of the text is unchanged. 3. Replace the first char by the mirror in the given region. (`'A' -> '"'`, `'B' -> '&'`, ...) Simple example: * Input: `"Business"` * Step 1: `"BUsInEsS"` * Step 2: `"B61kujla"` * `B -> U` * `B (1) - U (20) = -19` * `-19 + 77 = 58` * `Region[58] = "6"` * `U -> s` * `U (20) - s (44) = -24` * `-24 + 77 = 53` * `Region[53] = "1"` * Step 3: `"&61kujla"` This kata is part of the Simple Encryption Series: Simple Encryption #1 - Alternating Split Simple Encryption #2 - Index-Difference Simple Encryption #3 - Turn The Bits Around Simple Encryption #4 - Qwerty Have fun coding it and please don't forget to vote and rank this kata! :-) Also feel free to reuse/extend the following starter code: ```python def decrypt(encrypted_text): ```
{"functional": "_inputs = [[\"$-Wy,dM79H'i'o$n0C&I.ZTcMJw5vPlZc Hn!krhlaa:khV mkL;gvtP-S7Rt1Vp2RV:wV9VuhO Iz3dqb.U0w\"], ['5MyQa9p0riYplZc'], [\"5MyQa79H'ijQaw!Ns6jVtpmnlZ.V6p\"], [''], [None]]\n_outputs = [['Do the kata \"Kobayashi-Maru-Test!\" Endless fun and excitement when finding a solution!'], ['This is a test!'], ['This kata is very interesting!'], [''], [None]]\nimport math\ndef _deep_eq(a, b, tol=1e-5):\n if isinstance(a, float) or isinstance(b, float):\n return math.isclose(a, b, rel_tol=tol, abs_tol=tol)\n if isinstance(a, (list, tuple)):\n if len(a) != len(b): return False\n return all(_deep_eq(x, y, tol) for x, y in zip(a, b))\n return a == b\n\nfor i, o in zip(_inputs, _outputs):\n assert _deep_eq(decrypt(*i), o[0])"}
508
307
coding
Solve the programming task below in a Python markdown code block. Your task is to write an update for a lottery machine. Its current version produces a sequence of random letters and integers (passed as a string to the function). Your code must filter out all letters and return **unique** integers as a string, in their order of first appearance. If there are no integers in the string return `"One more run!"` ## Examples ``` "hPrBKWDH8yc6Lt5NQZWQ" --> "865" "ynMAisVpHEqpqHBqTrwH" --> "One more run!" "555" --> "5" ``` Also feel free to reuse/extend the following starter code: ```python def lottery(s): ```
{"functional": "_inputs = [['wQ8Hy0y5m5oshQPeRCkG'], ['ffaQtaRFKeGIIBIcSJtg'], ['555'], ['HappyNewYear2020'], ['20191224isXmas'], ['']]\n_outputs = [['805'], ['One more run!'], ['5'], ['20'], ['20194'], ['One more run!']]\nimport math\ndef _deep_eq(a, b, tol=1e-5):\n if isinstance(a, float) or isinstance(b, float):\n return math.isclose(a, b, rel_tol=tol, abs_tol=tol)\n if isinstance(a, (list, tuple)):\n if len(a) != len(b): return False\n return all(_deep_eq(x, y, tol) for x, y in zip(a, b))\n return a == b\n\nfor i, o in zip(_inputs, _outputs):\n assert _deep_eq(lottery(*i), o[0])"}
168
239
coding
Solve the programming task below in a Python markdown code block. You already know that Valery's favorite sport is biathlon. Due to your help, he learned to shoot without missing, and his skills are unmatched at the shooting range. But now a smaller task is to be performed, he should learn to complete the path fastest. The track's map is represented by a rectangle n × m in size divided into squares. Each square is marked with a lowercase Latin letter (which means the type of the plot), with the exception of the starting square (it is marked with a capital Latin letters S) and the terminating square (it is marked with a capital Latin letter T). The time of movement from one square to another is equal to 1 minute. The time of movement within the cell can be neglected. We can move from the cell only to side-adjacent ones, but it is forbidden to go beyond the map edges. Also the following restriction is imposed on the path: it is not allowed to visit more than k different types of squares (squares of one type can be visited an infinite number of times). Squares marked with S and T have no type, so they are not counted. But S must be visited exactly once — at the very beginning, and T must be visited exactly once — at the very end. Your task is to find the path from the square S to the square T that takes minimum time. Among all shortest paths you should choose the lexicographically minimal one. When comparing paths you should lexicographically represent them as a sequence of characters, that is, of plot types. Input The first input line contains three integers n, m and k (1 ≤ n, m ≤ 50, n·m ≥ 2, 1 ≤ k ≤ 4). Then n lines contain the map. Each line has the length of exactly m characters and consists of lowercase Latin letters and characters S and T. It is guaranteed that the map contains exactly one character S and exactly one character T. Pretest 12 is one of the maximal tests for this problem. Output If there is a path that satisfies the condition, print it as a sequence of letters — the plot types. Otherwise, print "-1" (without quotes). You shouldn't print the character S in the beginning and T in the end. Note that this sequence may be empty. This case is present in pretests. You can just print nothing or print one "End of line"-character. Both will be accepted. Examples Input 5 3 2 Sba ccc aac ccc abT Output bcccc Input 3 4 1 Sxyy yxxx yyyT Output xxxx Input 1 3 3 TyS Output y Input 1 4 1 SxyT Output -1
{"inputs": ["1 2 4\nST\n", "1 2 1\nST\n", "2 1 4\nS\nT\n", "1 3 3\nSaT\n", "2 1 1\nS\nT\n", "1 3 3\nTyS\n", "1 4 1\nSxyT\n", "3 3 1\naaa\naaa\nTSa\n"], "outputs": ["\n", "\n", "\n", "a\n", "\n", "y\n", "-1\n", "\n"]}
592
127
coding
Please solve the programming task below using a self-contained code snippet in a markdown code block. A truck has two fuel tanks. You are given two integers, mainTank representing the fuel present in the main tank in liters and additionalTank representing the fuel present in the additional tank in liters. The truck has a mileage of 10 km per liter. Whenever 5 liters of fuel get used up in the main tank, if the additional tank has at least 1 liters of fuel, 1 liters of fuel will be transferred from the additional tank to the main tank. Return the maximum distance which can be traveled. Note: Injection from the additional tank is not continuous. It happens suddenly and immediately for every 5 liters consumed.   Please complete the following python code precisely: ```python class Solution: def distanceTraveled(self, mainTank: int, additionalTank: int) -> int: ```
{"functional": "def check(candidate):\n assert candidate(mainTank = 5, additionalTank = 10) == 60\n assert candidate(mainTank = 1, additionalTank = 2) == 10\n\n\ncheck(Solution().distanceTraveled)"}
184
61
coding
Solve the programming task below in a Python markdown code block. A string of length 6 consisting of lowercase English letters is said to be coffee-like if and only if its 3-rd and 4-th characters are equal and its 5-th and 6-th characters are also equal. Given a string S, determine whether it is coffee-like. -----Constraints----- - S is a string of length 6 consisting of lowercase English letters. -----Input----- Input is given from Standard Input in the following format: S -----Output----- If S is coffee-like, print Yes; otherwise, print No. -----Sample Input----- sippuu -----Sample Output----- Yes In sippuu, the 3-rd and 4-th characters are equal, and the 5-th and 6-th characters are also equal.
{"inputs": ["cofgee", "sjppvv", "uuppis", "ephoni", "cofgef", "uvppis", "eohoni", "fegfoc"], "outputs": ["No\n", "Yes\n", "No\n", "No\n", "No\n", "No\n", "No\n", "No\n"]}
169
78
coding
Please solve the programming task below using a self-contained code snippet in a markdown code block. You are given a 0-indexed integer array nums of even length. As long as nums is not empty, you must repetitively: Find the minimum number in nums and remove it. Find the maximum number in nums and remove it. Calculate the average of the two removed numbers. The average of two numbers a and b is (a + b) / 2. For example, the average of 2 and 3 is (2 + 3) / 2 = 2.5. Return the number of distinct averages calculated using the above process. Note that when there is a tie for a minimum or maximum number, any can be removed.   Please complete the following python code precisely: ```python class Solution: def distinctAverages(self, nums: List[int]) -> int: ```
{"functional": "def check(candidate):\n assert candidate(nums = [4,1,4,0,3,5]) == 2\n assert candidate(nums = [1,100]) == 1\n\n\ncheck(Solution().distinctAverages)"}
183
58
coding
Please solve the programming task below using a self-contained code snippet in a markdown code block. You are given a 0-indexed 1-dimensional (1D) integer array original, and two integers, m and n. You are tasked with creating a 2-dimensional (2D) array with m rows and n columns using all the elements from original. The elements from indices 0 to n - 1 (inclusive) of original should form the first row of the constructed 2D array, the elements from indices n to 2 * n - 1 (inclusive) should form the second row of the constructed 2D array, and so on. Return an m x n 2D array constructed according to the above procedure, or an empty 2D array if it is impossible.   Please complete the following python code precisely: ```python class Solution: def construct2DArray(self, original: List[int], m: int, n: int) -> List[List[int]]: ```
{"functional": "def check(candidate):\n assert candidate(original = [1,2,3,4], m = 2, n = 2) == [[1,2],[3,4]]\n assert candidate(original = [1,2,3], m = 1, n = 3) == [[1,2,3]]\n assert candidate(original = [1,2], m = 1, n = 1) == []\n assert candidate(original = [3], m = 1, n = 2) == []\n\n\ncheck(Solution().construct2DArray)"}
205
135
coding
Solve the programming task below in a Python markdown code block. Monocarp has decided to buy a new TV set and hang it on the wall in his flat. The wall has enough free space so Monocarp can buy a TV set with screen width not greater than $a$ and screen height not greater than $b$. Monocarp is also used to TV sets with a certain aspect ratio: formally, if the width of the screen is $w$, and the height of the screen is $h$, then the following condition should be met: $\frac{w}{h} = \frac{x}{y}$. There are many different TV sets in the shop. Monocarp is sure that for any pair of positive integers $w$ and $h$ there is a TV set with screen width $w$ and height $h$ in the shop. Monocarp isn't ready to choose the exact TV set he is going to buy. Firstly he wants to determine the optimal screen resolution. He has decided to try all possible variants of screen size. But he must count the number of pairs of positive integers $w$ and $h$, beforehand, such that $(w \le a)$, $(h \le b)$ and $(\frac{w}{h} = \frac{x}{y})$. In other words, Monocarp wants to determine the number of TV sets having aspect ratio $\frac{x}{y}$, screen width not exceeding $a$, and screen height not exceeding $b$. Two TV sets are considered different if they have different screen width or different screen height. -----Input----- The first line contains four integers $a$, $b$, $x$, $y$ ($1 \le a, b, x, y \le 10^{18}$) — the constraints on the screen width and height, and on the aspect ratio. -----Output----- Print one integer — the number of different variants to choose TV screen width and screen height so that they meet the aforementioned constraints. -----Examples----- Input 17 15 5 3 Output 3 Input 14 16 7 22 Output 0 Input 4 2 6 4 Output 1 Input 1000000000000000000 1000000000000000000 999999866000004473 999999822000007597 Output 1000000063 -----Note----- In the first example, there are $3$ possible variants: $(5, 3)$, $(10, 6)$, $(15, 9)$. In the second example, there is no TV set meeting the constraints. In the third example, there is only one variant: $(3, 2)$.
{"inputs": ["4 2 6 4\n", "1 1 1 1\n", "3 3 2 4\n", "3 3 2 6\n", "4 2 4 3\n", "5 5 1 1\n", "3 3 2 4\n", "4 2 4 3\n"], "outputs": ["1\n", "1\n", "1\n", "1\n", "0\n", "5\n", "1\n", "0\n"]}
628
118
coding
Solve the programming task below in a Python markdown code block. Vanya wants to pass n exams and get the academic scholarship. He will get the scholarship if the average grade mark for all the exams is at least avg. The exam grade cannot exceed r. Vanya has passed the exams and got grade a_{i} for the i-th exam. To increase the grade for the i-th exam by 1 point, Vanya must write b_{i} essays. He can raise the exam grade multiple times. What is the minimum number of essays that Vanya needs to write to get scholarship? -----Input----- The first line contains three integers n, r, avg (1 ≤ n ≤ 10^5, 1 ≤ r ≤ 10^9, 1 ≤ avg ≤ min(r, 10^6)) — the number of exams, the maximum grade and the required grade point average, respectively. Each of the following n lines contains space-separated integers a_{i} and b_{i} (1 ≤ a_{i} ≤ r, 1 ≤ b_{i} ≤ 10^6). -----Output----- In the first line print the minimum number of essays. -----Examples----- Input 5 5 4 5 2 4 7 3 1 3 2 2 5 Output 4 Input 2 5 4 5 2 5 2 Output 0 -----Note----- In the first sample Vanya can write 2 essays for the 3rd exam to raise his grade by 2 points and 2 essays for the 4th exam to raise his grade by 1 point. In the second sample, Vanya doesn't need to write any essays as his general point average already is above average.
{"inputs": ["1 1 1\n1 1\n", "1 2 1\n2 2\n", "1 1 1\n1 1\n", "1 2 1\n2 2\n", "1 3 1\n2 2\n", "1 1 1\n0 1\n", "1 5 1\n2 2\n", "1 5 1\n2 4\n"], "outputs": ["0\n", "0\n", "0\n", "0\n", "0\n", "1\n", "0\n", "0\n"]}
373
134
coding
Solve the programming task below in a Python markdown code block. Given a square grid of characters in the range ascii[a-z], rearrange elements of each row alphabetically, ascending. Determine if the columns are also in ascending alphabetical order, top to bottom. Return YES if they are or NO if they are not. Example $grid=[\text{'abc'},\text{'ade'},\text{'efg'}]$ The grid is illustrated below. a b c a d e e f g The rows are already in alphabetical order. The columns a a e, b d f and c e g are also in alphabetical order, so the answer would be YES. Only elements within the same row can be rearranged. They cannot be moved to a different row. Function Description Complete the gridChallenge function in the editor below. gridChallenge has the following parameter(s): string grid[n]: an array of strings Returns string: either YES or NO Input Format The first line contains $\boldsymbol{\boldsymbol{t}}$, the number of testcases. Each of the next $\boldsymbol{\boldsymbol{t}}$ sets of lines are described as follows: - The first line contains $n$, the number of rows and columns in the grid. - The next $n$ lines contains a string of length $n$ Constraints $1\leq t\leq100$ $1\leq n\leq100$ Each string consists of lowercase letters in the range ascii[a-z] Output Format For each test case, on a separate line print YES if it is possible to rearrange the grid alphabetically ascending in both its rows and columns, or NO otherwise. Sample Input STDIN Function ----- -------- 1 t = 1 5 n = 5 ebacd grid = ['ebacd', 'fghij', 'olmkn', 'trpqs', 'xywuv'] fghij olmkn trpqs xywuv Sample Output YES Explanation The $5$x$5$ grid in the $\mbox{I}$ test case can be reordered to abcde fghij klmno pqrst uvwxy This fulfills the condition since the rows 1, 2, ..., 5 and the columns 1, 2, ..., 5 are all alphabetically sorted.
{"inputs": ["1\n5\nebacd\nfghij\nolmkn\ntrpqs\nxywuv\n"], "outputs": ["YES\n"]}
519
36
coding
Please solve the programming task below using a self-contained code snippet in a markdown code block. Given a string s representing a valid expression, implement a basic calculator to evaluate it, and return the result of the evaluation. Note: You are not allowed to use any built-in function which evaluates strings as mathematical expressions, such as eval().   Please complete the following python code precisely: ```python class Solution: def calculate(self, s: str) -> int: ```
{"functional": "def check(candidate):\n assert candidate(s = \"1 + 1\") == 2\n assert candidate(s = \" 2-1 + 2 \") == 3\n assert candidate(s = \"(1+(4+5+2)-3)+(6+8)\") == 23\n\n\ncheck(Solution().calculate)"}
94
79
coding
Solve the programming task below in a Python markdown code block. While Alice was drinking sugarcane juice, she started wondering about the following facts: The juicer sells each glass of sugarcane juice for 50 coins. He spends 20\% of his total income on buying sugarcane. He spends 20\% of his total income on buying salt and mint leaves. He spends 30\% of his total income on shop rent. Alice wonders, what is the juicer's profit (in coins) when he sells N glasses of sugarcane juice? ------ Input Format ------ - The first line of input will contain an integer T — the number of test cases. The description of T test cases follows. - The first and only line of each test case contains an integer N, as described in the problem statement. ------ Output Format ------ For each test case, output on a new line the juicer's profit when he sells N glasses of juice. ------ Constraints ------ $1 ≤ T ≤ 1000$ $1 ≤ N ≤ 10^{6}$ ----- Sample Input 1 ------ 4 2 4 5 10 ----- Sample Output 1 ------ 30 60 75 150 ----- explanation 1 ------ Test case $1$: The total income is $50\times 2 = 100$ coins. The juicer spends $20$ coins on sugarcane, $20$ coins on salt and mint leaves and $30$ coins on rent. Thus, the profit is $100-(20+20+30) = 30$ coins. Test case $2$: The total income is $50\times 4 = 200$ coins. The juicer spends $40$ coins on sugarcane, $40$ coins on salt and mint leaves and $60$ coins on rent. Thus, the profit is $200-(40+40+60) = 60$ coins. Test case $3$: The total income is $50\times 5 = 250$ coins. The juicer spends $50$ coins on sugarcane, $50$ coins on salt and mint leaves and $75$ coins on rent. Thus, the profit is $250-(50+50+75) = 75$ coins. Test case $4$: The total income is $50\times 10 = 500$ coins. The juicer spends $100$ coins on sugarcane, $100$ coins on salt and mint leaves and $150$ coins on rent. Thus, the profit is $500-(100+100+150) = 150$ coins.
{"inputs": ["4\n2\n4\n5\n10\n"], "outputs": ["30\n60\n75\n150\n"]}
624
34
coding
Solve the programming task below in a Python markdown code block. A superhero fights with a monster. The battle consists of rounds, each of which lasts exactly $n$ minutes. After a round ends, the next round starts immediately. This is repeated over and over again. Each round has the same scenario. It is described by a sequence of $n$ numbers: $d_1, d_2, \dots, d_n$ ($-10^6 \le d_i \le 10^6$). The $i$-th element means that monster's hp (hit points) changes by the value $d_i$ during the $i$-th minute of each round. Formally, if before the $i$-th minute of a round the monster's hp is $h$, then after the $i$-th minute it changes to $h := h + d_i$. The monster's initial hp is $H$. It means that before the battle the monster has $H$ hit points. Print the first minute after which the monster dies. The monster dies if its hp is less than or equal to $0$. Print -1 if the battle continues infinitely. -----Input----- The first line contains two integers $H$ and $n$ ($1 \le H \le 10^{12}$, $1 \le n \le 2\cdot10^5$). The second line contains the sequence of integers $d_1, d_2, \dots, d_n$ ($-10^6 \le d_i \le 10^6$), where $d_i$ is the value to change monster's hp in the $i$-th minute of a round. -----Output----- Print -1 if the superhero can't kill the monster and the battle will last infinitely. Otherwise, print the positive integer $k$ such that $k$ is the first minute after which the monster is dead. -----Examples----- Input 1000 6 -100 -200 -300 125 77 -4 Output 9 Input 1000000000000 5 -1 0 0 0 0 Output 4999999999996 Input 10 4 -3 -6 5 4 Output -1
{"inputs": ["1 1\n-1\n", "1 1\n-1\n", "1 2\n1 -1\n", "1 2\n-1 1\n", "1 2\n-1 1\n", "1 2\n1 -1\n", "2 2\n1 -1\n", "1 1\n-1000000\n"], "outputs": ["1\n", "1\n", "-1\n", "1\n", "1\n", "-1\n", "-1\n", "1\n"]}
510
123
coding
Solve the programming task below in a Python markdown code block. There are n kangaroos with pockets. Each kangaroo has a size (integer number). A kangaroo can go into another kangaroo's pocket if and only if the size of kangaroo who hold the kangaroo is at least twice as large as the size of kangaroo who is held. Each kangaroo can hold at most one kangaroo, and the kangaroo who is held by another kangaroo cannot hold any kangaroos. The kangaroo who is held by another kangaroo cannot be visible from outside. Please, find a plan of holding kangaroos with the minimal number of kangaroos who is visible. -----Input----- The first line contains a single integer — n (1 ≤ n ≤ 5·10^5). Each of the next n lines contains an integer s_{i} — the size of the i-th kangaroo (1 ≤ s_{i} ≤ 10^5). -----Output----- Output a single integer — the optimal number of visible kangaroos. -----Examples----- Input 8 2 5 7 6 9 8 4 2 Output 5 Input 8 9 1 6 2 6 5 8 3 Output 5
{"inputs": ["1\n1\n", "1\n1\n", "1\n2\n", "1\n3\n", "1\n6\n", "3\n1\n2\n4\n", "3\n1\n2\n4\n", "4\n1\n1\n1\n2\n"], "outputs": ["1\n", "1\n", "1\n", "1\n", "1\n", "2\n", "2\n", "3\n"]}
268
100
coding
Solve the programming task below in a Python markdown code block. Given the coordinates (x, y) of a point in 2-D plane. Find if it is possible to reach (x, y) from (0, 0). The only possible moves from any coordinate (i, j) are as follows: Go to the point with coordinates (i + 1, j + 1). Go to the point with coordinates (i + 1, j - 1) Go to the point with coordinates (i - 1, j + 1). Go to the point with coordinates (i - 1, j - 1). ------ Input Format ------ - First line will contain T, number of testcases. Then the testcases follow. - Each testcase contains of a single line of input, two integers x, y. ------ Output Format ------ For each test case, print YES if it is possible to reach (x, y) from (0, 0), otherwise print NO. You may print each character of the string in uppercase or lowercase (for example, the strings "yEs", "yes", "Yes" and "YES" will all be treated as identical). ------ Constraints ------ $1 ≤ T ≤ 2\cdot10^{4}$ $-10^{9} ≤ x, y ≤ 10^{9}$ ----- Sample Input 1 ------ 6 0 2 1 2 -1 -3 -1 0 -3 1 2 -1 ----- Sample Output 1 ------ YES NO YES NO YES NO ----- explanation 1 ------ Test case $1$: A valid sequence of moves can be: $\;(0, 0) \rightarrow (1, 1) \rightarrow (0, 2)$. Test case $2$: There is no possible way to reach the point $(1, 2)$ from $(0, 0)$. Test case $3$: A valid sequence of moves can be: $\;(0, 0) \rightarrow (-1, -1) \rightarrow (0, -2) \rightarrow (-1, -3)$.
{"inputs": ["6\n0 2\n1 2\n-1 -3\n-1 0\n-3 1\n2 -1\n"], "outputs": ["YES\nNO\nYES\nNO\nYES\nNO\n"]}
457
51
coding
Solve the programming task below in a Python markdown code block. In this Kata, you will write a function `doubles` that will remove double string characters that are adjacent to each other. For example: `doubles('abbcccdddda') = 'aca'`, because, from left to right: ```Haskell a) There is only one 'a' on the left hand side, so it stays. b) The 2 b's disappear because we are removing double characters that are adjacent. c) Of the 3 c's, we remove two. We are only removing doubles. d) The 4 d's all disappear, because we first remove the first double, and again we remove the second double. e) There is only one 'a' at the end, so it stays. ``` Two more examples: `doubles('abbbzz') = 'ab'` and `doubles('abba') = ""`. In the second example, when we remove the b's in `'abba'`, the double `a` that results is then removed. The strings will contain lowercase letters only. More examples in the test cases. Good luck! Also feel free to reuse/extend the following starter code: ```python def doubles(s): ```
{"functional": "_inputs = [['abbbzz'], ['zzzzykkkd'], ['abbcccdddda'], ['vvvvvoiiiiin'], ['rrrmooomqqqqj'], ['xxbnnnnnyaaaaam'], ['qqqqqqnpppgooooonpppppqmmmmmc'], ['qqqqqwwwx'], ['jjjfzzzzzzsddgrrrrru'], ['jjjjjfuuuutgggggqppdaaas'], ['iiiiibllllllyqqqqqbiiiiiituuf'], ['mmmmmmuzzqllllmqqqp']]\n_outputs = [['ab'], ['ykd'], ['aca'], ['voin'], ['rmomj'], ['bnyam'], ['npgonpqmc'], ['qwx'], ['jfsgru'], ['jftgqdas'], ['ibyqbtf'], ['uqmqp']]\nimport math\ndef _deep_eq(a, b, tol=1e-5):\n if isinstance(a, float) or isinstance(b, float):\n return math.isclose(a, b, rel_tol=tol, abs_tol=tol)\n if isinstance(a, (list, tuple)):\n if len(a) != len(b): return False\n return all(_deep_eq(x, y, tol) for x, y in zip(a, b))\n return a == b\n\nfor i, o in zip(_inputs, _outputs):\n assert _deep_eq(doubles(*i), o[0])"}
265
332
coding
Solve the programming task below in a Python markdown code block. To protect people from evil, a long and tall wall was constructed a few years ago. But just a wall is not safe, there should also be soldiers on it, always keeping vigil. The wall is very long and connects the left and the right towers. There are exactly N spots (numbered 1 to N) on the wall for soldiers. The Kth spot is K miles far from the left tower and (N+1-K) miles from the right tower. Given a permutation of spots P of {1, 2, ..., N}, soldiers occupy the N spots in that order. The P[i]th spot is occupied before the P[i+1]th spot. When a soldier occupies a spot, he is connected to his nearest soldier already placed to his left. If there is no soldier to his left, he is connected to the left tower. The same is the case with right side. A connection between two spots requires a wire of length equal to the distance between the two. The realm has already purchased a wire of M miles long from Nokia, possibly the wire will be cut into smaller length wires. As we can observe, the total length of the used wire depends on the permutation of the spots P. Help the realm in minimizing the length of the unused wire. If there is not enough wire, output -1. -----Input----- First line contains an integer T (number of test cases, 1 ≤ T ≤ 10 ). Each of the next T lines contains two integers N M, as explained in the problem statement (1 ≤ N ≤ 30 , 1 ≤ M ≤ 1000). -----Output----- For each test case, output the minimum length of the unused wire, or -1 if the the wire is not sufficient. -----Example----- Input: 4 3 8 3 9 2 4 5 25 Output: 0 0 -1 5 Explanation: In the 1st case, for example, the permutation P = {2, 1, 3} will use the exact 8 miles wires in total. In the 2nd case, for example, the permutation P = {1, 3, 2} will use the exact 9 miles wires in total. To understand the first two cases, you can see the following figures: In the 3rd case, the minimum length of wire required is 5, for any of the permutations {1,2} or {2,1}, so length 4 is not sufficient. In the 4th case, for the permutation {1, 2, 3, 4, 5} we need the maximum length of the wire = 20. So minimum possible unused wire length = 25 - 20 = 5.
{"inputs": ["4\n3 8\n3 9\n2 4\n5 25"], "outputs": ["0\n0\n-1\n5"]}
603
36
coding
Please solve the programming task below using a self-contained code snippet in a markdown code block. You are given two integers m and n representing a 0-indexed m x n grid. You are also given two 2D integer arrays guards and walls where guards[i] = [rowi, coli] and walls[j] = [rowj, colj] represent the positions of the ith guard and jth wall respectively. A guard can see every cell in the four cardinal directions (north, east, south, or west) starting from their position unless obstructed by a wall or another guard. A cell is guarded if there is at least one guard that can see it. Return the number of unoccupied cells that are not guarded.   Please complete the following python code precisely: ```python class Solution: def countUnguarded(self, m: int, n: int, guards: List[List[int]], walls: List[List[int]]) -> int: ```
{"functional": "def check(candidate):\n assert candidate(m = 4, n = 6, guards = [[0,0],[1,1],[2,3]], walls = [[0,1],[2,2],[1,4]]) == 7\n assert candidate(m = 3, n = 3, guards = [[1,1]], walls = [[0,1],[1,0],[2,1],[1,2]]) == 4\n\n\ncheck(Solution().countUnguarded)"}
197
112
coding
Solve the programming task below in a Python markdown code block. Iahub and Iahubina went to a picnic in a forest full of trees. Less than 5 minutes passed before Iahub remembered of trees from programming. Moreover, he invented a new problem and Iahubina has to solve it, otherwise Iahub won't give her the food. Iahub asks Iahubina: can you build a rooted tree, such that * each internal node (a node with at least one son) has at least two sons; * node i has ci nodes in its subtree? Iahubina has to guess the tree. Being a smart girl, she realized that it's possible no tree can follow Iahub's restrictions. In this way, Iahub will eat all the food. You need to help Iahubina: determine if there's at least one tree following Iahub's restrictions. The required tree must contain n nodes. Input The first line of the input contains integer n (1 ≤ n ≤ 24). Next line contains n positive integers: the i-th number represents ci (1 ≤ ci ≤ n). Output Output on the first line "YES" (without quotes) if there exist at least one tree following Iahub's restrictions, otherwise output "NO" (without quotes). Examples Input 4 1 1 1 4 Output YES Input 5 1 1 5 2 1 Output NO
{"inputs": ["1\n1\n", "2\n1 2\n", "2\n2 2\n", "2\n2 3\n", "2\n2 1\n", "4\n1 1 1 3\n", "4\n1 2 1 4\n", "4\n1 1 1 2\n"], "outputs": ["YES", "NO", "NO\n", "NO\n", "NO\n", "NO\n", "NO\n", "NO\n"]}
318
110
coding
Solve the programming task below in a Python markdown code block. Vasya commutes by train every day. There are n train stations in the city, and at the i-th station it's possible to buy only tickets to stations from i + 1 to a_{i} inclusive. No tickets are sold at the last station. Let ρ_{i}, j be the minimum number of tickets one needs to buy in order to get from stations i to station j. As Vasya is fond of different useless statistic he asks you to compute the sum of all values ρ_{i}, j among all pairs 1 ≤ i < j ≤ n. -----Input----- The first line of the input contains a single integer n (2 ≤ n ≤ 100 000) — the number of stations. The second line contains n - 1 integer a_{i} (i + 1 ≤ a_{i} ≤ n), the i-th of them means that at the i-th station one may buy tickets to each station from i + 1 to a_{i} inclusive. -----Output----- Print the sum of ρ_{i}, j among all pairs of 1 ≤ i < j ≤ n. -----Examples----- Input 4 4 4 4 Output 6 Input 5 2 3 5 5 Output 17 -----Note----- In the first sample it's possible to get from any station to any other (with greater index) using only one ticket. The total number of pairs is 6, so the answer is also 6. Consider the second sample: ρ_{1, 2} = 1 ρ_{1, 3} = 2 ρ_{1, 4} = 3 ρ_{1, 5} = 3 ρ_{2, 3} = 1 ρ_{2, 4} = 2 ρ_{2, 5} = 2 ρ_{3, 4} = 1 ρ_{3, 5} = 1 ρ_{4, 5} = 1 Thus the answer equals 1 + 2 + 3 + 3 + 1 + 2 + 2 + 1 + 1 + 1 = 17.
{"inputs": ["2\n2\n", "2\n2\n", "3\n3 3\n", "3\n3 3\n", "3\n2 3\n", "4\n4 4 4\n", "4\n3 3 4\n", "4\n3 3 4\n"], "outputs": ["1\n", "1\n", "3\n", "3\n", "4\n", "6\n", "8\n", "8\n"]}
495
104
coding
Solve the programming task below in a Python markdown code block. Gennady owns a small hotel in the countryside where he lives a peaceful life. He loves to take long walks, watch sunsets and play cards with tourists staying in his hotel. His favorite game is called "Mau-Mau". To play Mau-Mau, you need a pack of $52$ cards. Each card has a suit (Diamonds — D, Clubs — C, Spades — S, or Hearts — H), and a rank (2, 3, 4, 5, 6, 7, 8, 9, T, J, Q, K, or A). At the start of the game, there is one card on the table and you have five cards in your hand. You can play a card from your hand if and only if it has the same rank or the same suit as the card on the table. In order to check if you'd be a good playing partner, Gennady has prepared a task for you. Given the card on the table and five cards in your hand, check if you can play at least one card. -----Input----- The first line of the input contains one string which describes the card on the table. The second line contains five strings which describe the cards in your hand. Each string is two characters long. The first character denotes the rank and belongs to the set $\{{\tt 2}, {\tt 3}, {\tt 4}, {\tt 5}, {\tt 6}, {\tt 7}, {\tt 8}, {\tt 9}, {\tt T}, {\tt J}, {\tt Q}, {\tt K}, {\tt A}\}$. The second character denotes the suit and belongs to the set $\{{\tt D}, {\tt C}, {\tt S}, {\tt H}\}$. All the cards in the input are different. -----Output----- If it is possible to play a card from your hand, print one word "YES". Otherwise, print "NO". You can print each letter in any case (upper or lower). -----Examples----- Input AS 2H 4C TH JH AD Output YES Input 2H 3D 4C AC KD AS Output NO Input 4D AS AC AD AH 5H Output YES -----Note----- In the first example, there is an Ace of Spades (AS) on the table. You can play an Ace of Diamonds (AD) because both of them are Aces. In the second example, you cannot play any card. In the third example, you can play an Ace of Diamonds (AD) because it has the same suit as a Four of Diamonds (4D), which lies on the table.
{"inputs": ["AS\n2H 4C TH JH AD\n", "2H\n3D 4C AC KD AS\n", "4D\nAS AC AD AH 5H\n", "3D\n8S 4S 2C AS 6H\n", "7H\nTC 4C KC AD 9S\n", "KH\n3C QD 9S KS 8D\n", "4H\nJH QC 5H 9H KD\n", "9H\nKC 6D KD 4C 2S\n"], "outputs": ["YES\n", "NO\n", "YES\n", "NO\n", "NO\n", "YES\n", "YES\n", "NO\n"]}
578
161
coding
Solve the programming task below in a Python markdown code block. [Haikus](https://en.wikipedia.org/wiki/Haiku_in_English) are short poems in a three-line format, with 17 syllables arranged in a 5–7–5 pattern. Your task is to check if the supplied text is a haiku or not. ### About syllables [Syllables](https://en.wikipedia.org/wiki/Syllable) are the phonological building blocks of words. *In this kata*, a syllable is a part of a word including a vowel ("a-e-i-o-u-y") or a group of vowels (e.g. "ou", "ee", "ay"). A few examples: "tea", "can", "to·day", "week·end", "el·e·phant". **However**, silent "E"s **do not** create syllables. *In this kata*, an "E" is considered silent if it's alone at the end of the word, preceded by one (or more) consonant(s) and there is at least one other syllable in the word. Examples: "age", "ar·range", "con·crete"; but not in "she", "blue", "de·gree". Some more examples: * one syllable words: "cat", "cool", "sprout", "like", "eye", "squeeze" * two syllables words: "ac·count", "hon·est", "beau·ty", "a·live", "be·cause", "re·store" ## Examples ``` An old silent pond... A frog jumps into the pond, splash! Silence again. ``` ...should return `True`, as this is a valid 5–7–5 haiku: ``` An old si·lent pond... # 5 syllables A frog jumps in·to the pond, # 7 splash! Si·lence a·gain. # 5 ``` Another example: ``` Autumn moonlight - a worm digs silently into the chestnut. ``` ...should return `False`, because the number of syllables per line is not correct: ``` Au·tumn moon·light - # 4 syllables a worm digs si·lent·ly # 6 in·to the chest·nut. # 5 ``` --- ## My other katas If you enjoyed this kata then please try [my other katas](https://www.codewars.com/collections/katas-created-by-anter69)! :-) Also feel free to reuse/extend the following starter code: ```python def is_haiku(text): ```
{"functional": "_inputs = [['An old silent pond...\\nA frog jumps into the pond,\\nsplash! Silence again.'], ['An old silent pond...\\nA frog jumps into the pond, splash!\\nSilence again.'], ['An old silent pond...\\nA frog jumps into the pond,\\nsplash!\\nSilence again.'], ['An old silent pond... A frog jumps into the pond, splash! Silence again.'], ['Autumn moonlight -\\na worm digs silently\\ninto the chestnut.'], [''], ['\\n\\n'], ['My code is cool, right?\\nJava # Pyhton ; Ruby // Go:\\nI know them all, yay! ;-)'], ['Edge case the urge come;\\nFurthermore eye the garage.\\nLike literature!'], ['a e i o u\\noo ee ay ie ey oa ie\\ny a e i o']]\n_outputs = [[True], [False], [False], [False], [False], [False], [False], [True], [True], [True]]\nimport math\ndef _deep_eq(a, b, tol=1e-5):\n if isinstance(a, float) or isinstance(b, float):\n return math.isclose(a, b, rel_tol=tol, abs_tol=tol)\n if isinstance(a, (list, tuple)):\n if len(a) != len(b): return False\n return all(_deep_eq(x, y, tol) for x, y in zip(a, b))\n return a == b\n\nfor i, o in zip(_inputs, _outputs):\n assert _deep_eq(is_haiku(*i), o[0])"}
571
370
coding
Solve the programming task below in a Python markdown code block. Let $s$ be some string consisting of symbols "0" or "1". Let's call a string $t$ a substring of string $s$, if there exists such number $1 \leq l \leq |s| - |t| + 1$ that $t = s_l s_{l+1} \ldots s_{l + |t| - 1}$. Let's call a substring $t$ of string $s$ unique, if there exist only one such $l$. For example, let $s = $"1010111". A string $t = $"010" is an unique substring of $s$, because $l = 2$ is the only one suitable number. But, for example $t = $"10" isn't a unique substring of $s$, because $l = 1$ and $l = 3$ are suitable. And for example $t =$"00" at all isn't a substring of $s$, because there is no suitable $l$. Today Vasya solved the following problem at the informatics lesson: given a string consisting of symbols "0" and "1", the task is to find the length of its minimal unique substring. He has written a solution to this problem and wants to test it. He is asking you to help him. You are given $2$ positive integers $n$ and $k$, such that $(n \bmod 2) = (k \bmod 2)$, where $(x \bmod 2)$ is operation of taking remainder of $x$ by dividing on $2$. Find any string $s$ consisting of $n$ symbols "0" or "1", such that the length of its minimal unique substring is equal to $k$. -----Input----- The first line contains two integers $n$ and $k$, separated by spaces ($1 \leq k \leq n \leq 100\,000$, $(k \bmod 2) = (n \bmod 2)$). -----Output----- Print a string $s$ of length $n$, consisting of symbols "0" and "1". Minimal length of the unique substring of $s$ should be equal to $k$. You can find any suitable string. It is guaranteed, that there exists at least one such string. -----Examples----- Input 4 4 Output 1111 Input 5 3 Output 01010 Input 7 3 Output 1011011 -----Note----- In the first test, it's easy to see, that the only unique substring of string $s = $"1111" is all string $s$, which has length $4$. In the second test a string $s = $"01010" has minimal unique substring $t =$"101", which has length $3$. In the third test a string $s = $"1011011" has minimal unique substring $t =$"110", which has length $3$.
{"inputs": ["4 4\n", "5 3\n", "7 3\n", "1 1\n", "2 2\n", "3 3\n", "3 1\n", "4 2\n"], "outputs": ["1111", "01010", "0010010", "1", "11", "111", "010", "0101"]}
673
99
coding
Please solve the programming task below using a self-contained code snippet in a markdown code block. Given an m x n binary matrix mat, return the distance of the nearest 0 for each cell. The distance between two adjacent cells is 1.   Please complete the following python code precisely: ```python class Solution: def updateMatrix(self, mat: List[List[int]]) -> List[List[int]]: ```
{"functional": "def check(candidate):\n assert candidate(mat = [[0,0,0],[0,1,0],[0,0,0]]) == [[0,0,0],[0,1,0],[0,0,0]]\n assert candidate(mat = [[0,0,0],[0,1,0],[1,1,1]]) == [[0,0,0],[0,1,0],[1,2,1]]\n\n\ncheck(Solution().updateMatrix)"}
82
111
coding
Solve the programming task below in a Python markdown code block. Chef has started developing interest in playing chess, and was learning how the [Queen] moves. Chef has an empty N \times N chessboard. He places a Queen at (X, Y) and wonders - What are the number of cells that are under attack by the Queen? Notes: The top-left cell is (1, 1), the top-right cell is (1, N), the bottom-left cell is (N,1) and the bottom-right cell is (N, N). The Queen can be moved any number of unoccupied cells in a straight line vertically, horizontally, or diagonally. The cell on which the Queen is present, is not said to be under attack by the Queen. ------ Input Format ------ - The first line contains a single integer T - the number of test cases. Then the test cases follow. - The first and only line of each test case contains three integers N, X and Y, as described in the problem statement. ------ Output Format ------ For each test case, output in a single line, the total number of cells that are under attack by the Queen. ------ Constraints ------ $1 ≤ T ≤ 10^{4}$ $1 ≤ N ≤ 10^{6}$ $1 ≤ X, Y ≤ N$ ----- Sample Input 1 ------ 5 1 1 1 3 2 2 3 2 1 2 2 2 150 62 41 ----- Sample Output 1 ------ 0 8 6 3 527 ----- explanation 1 ------ Test case 1: The only cell on the board is $(1,1)$. Since Queen stands on this cell, it is not under attack. Test case 2: The Queen can attack the following cells: $\{(1, 1), (1, 2), (1, 3), (2, 1), (2, 3), (3, 1), (3, 2), (3, 3)\}$. Test case 3: The Queen can attack the following cells: $\{(1, 1), (1, 2), (2, 2), (2, 3), (3, 1), (3, 2)\}$. Test case 4: The Queen can attack the following cells: $\{(1, 1), (1, 2), (2, 1)\}$.
{"inputs": ["5\n1 1 1\n3 2 2\n3 2 1\n2 2 2\n150 62 41\n"], "outputs": ["0\n8\n6\n3\n527\n"]}
529
58
coding
Solve the programming task below in a Python markdown code block. Read problems statements in Mandarin Chinese, Russian and Vietnamese as well. Chef likes problems related to numbers a lot. He is generally quite good at solving these kinds of problems, but today he got stuck at one number theory problem, and so he asks your help to solve it. Given a positive integer N, find out how many positive integers X satisfy the equation X + S(X) + S(S(X)) = N, where S(X) denoting sum of digits of X in decimal (base 10) representation. ------ Input ------ The only line of the input contains one integer number - N. ------ Output ------ Output single integer in a line denoting the count of number of positive integers X satisfying the above given equation. ------ Constraints ------ $1 ≤ N ≤ 10^{9}$ ----- Sample Input 1 ------ 6 ----- Sample Output 1 ------ 1 ----- explanation 1 ------ Example 1. Only one positive integer X = 2 satisfies the equation X + S(X) + S(S(X)) = 6, as X + S(X) + S(S(X)) = 2 + 2 + 2 = 6. ----- Sample Input 2 ------ 9939 ----- Sample Output 2 ------ 4 ----- explanation 2 ------ Example 2.X can be 9898, 9907, 9910 and 9913. 9898 + S(9898) + S(S(9898)) = 9898 + 34 + 7 = 9939 9907 + S(9907) + S(S(9907)) = 9907 + 25 + 7 = 9939 9910 + S(9910) + S(S(9910)) = 9910 + 19 + 10 = 9939 9913 + S(9913) + S(S(9913)) = 9913 + 22 + 4 = 9939 You can verify that there is not other positive value of X satisfying the given equation.
{"inputs": ["6", "9939"], "outputs": ["1", "4"]}
495
21
coding
Solve the programming task below in a Python markdown code block. A palindrome is a word, phrase, number, or other sequence of characters which reads the same backward as forward. Examples of numerical palindromes are: 2332 110011 54322345 For a given number ```num```, write a function which returns the number of numerical palindromes within each number. For this kata, single digit numbers will NOT be considered numerical palindromes. Return "Not valid" if the input is not an integer or is less than 0. ``` palindrome(5) => 0 palindrome(1221) => 2 palindrome(141221001) => 5 palindrome(1294) => 0 palindrome("1221") => "Not valid" ``` ```Haskell In Haskell, return a Maybe Int with Nothing for negative numbers. ``` Other Kata in this Series: Numerical Palindrome #1 Numerical Palindrome #1.5 Numerical Palindrome #2 Numerical Palindrome #3 Numerical Palindrome #3.5 Numerical Palindrome #4 Numerical Palindrome #5 Also feel free to reuse/extend the following starter code: ```python def palindrome(num): ```
{"functional": "_inputs = [[2], [141221001], [1551], [13598], ['ACCDDCCA'], ['1551'], [-4505]]\n_outputs = [[0], [5], [2], [0], ['Not valid'], ['Not valid'], ['Not valid']]\nimport math\ndef _deep_eq(a, b, tol=1e-5):\n if isinstance(a, float) or isinstance(b, float):\n return math.isclose(a, b, rel_tol=tol, abs_tol=tol)\n if isinstance(a, (list, tuple)):\n if len(a) != len(b): return False\n return all(_deep_eq(x, y, tol) for x, y in zip(a, b))\n return a == b\n\nfor i, o in zip(_inputs, _outputs):\n assert _deep_eq(palindrome(*i), o[0])"}
294
217
coding
Solve the programming task below in a Python markdown code block. group() A group() expression returns one or more subgroups of the match. Code >>> import re >>> m = re.match(r'(\w+)@(\w+)\.(\w+)','username@hackerrank.com') >>> m.group(0) # The entire match 'username@hackerrank.com' >>> m.group(1) # The first parenthesized subgroup. 'username' >>> m.group(2) # The second parenthesized subgroup. 'hackerrank' >>> m.group(3) # The third parenthesized subgroup. 'com' >>> m.group(1,2,3) # Multiple arguments give us a tuple. ('username', 'hackerrank', 'com') groups() A groups() expression returns a tuple containing all the subgroups of the match. Code >>> import re >>> m = re.match(r'(\w+)@(\w+)\.(\w+)','username@hackerrank.com') >>> m.groups() ('username', 'hackerrank', 'com') groupdict() A groupdict() expression returns a dictionary containing all the named subgroups of the match, keyed by the subgroup name. Code >>> m = re.match(r'(?P<user>\w+)@(?P<website>\w+)\.(?P<extension>\w+)','myname@hackerrank.com') >>> m.groupdict() {'website': 'hackerrank', 'user': 'myname', 'extension': 'com'} Task You are given a string $\mbox{S}$. Your task is to find the first occurrence of an alphanumeric character in $\mbox{S}$ (read from left to right) that has consecutive repetitions. Input Format A single line of input containing the string $\mbox{S}$. Constraints $0<len(S)<100$ Output Format Print the first occurrence of the repeating character. If there are no repeating characters, print -1. Sample Input ..12345678910111213141516171820212223 Sample Output 1 Explanation .. is the first repeating character, but it is not alphanumeric. 1 is the first (from left to right) alphanumeric repeating character of the string in the substring 111.
{"inputs": ["..12345678910111213141516171820212223\n"], "outputs": ["1\n"]}
510
49
coding
Please solve the programming task below using a self-contained code snippet in a markdown code block. You are a hiker preparing for an upcoming hike. You are given heights, a 2D array of size rows x columns, where heights[row][col] represents the height of cell (row, col). You are situated in the top-left cell, (0, 0), and you hope to travel to the bottom-right cell, (rows-1, columns-1) (i.e., 0-indexed). You can move up, down, left, or right, and you wish to find a route that requires the minimum effort. A route's effort is the maximum absolute difference in heights between two consecutive cells of the route. Return the minimum effort required to travel from the top-left cell to the bottom-right cell.   Please complete the following python code precisely: ```python class Solution: def minimumEffortPath(self, heights: List[List[int]]) -> int: ```
{"functional": "def check(candidate):\n assert candidate(heights = [[1,2,2],[3,8,2],[5,3,5]]) == 2\n assert candidate(heights = [[1,2,3],[3,8,4],[5,3,5]]) == 1\n assert candidate(heights = [[1,2,1,1,1],[1,2,1,2,1],[1,2,1,2,1],[1,2,1,2,1],[1,1,1,2,1]]) == 0\n\n\ncheck(Solution().minimumEffortPath)"}
200
140
coding
Solve the programming task below in a Python markdown code block. A string is called palindrome if it reads the same from left to right and from right to left. For example "kazak", "oo", "r" and "mikhailrubinchikkihcniburliahkim" are palindroms, but strings "abb" and "ij" are not. You are given string s consisting of lowercase Latin letters. At once you can choose any position in the string and change letter in that position to any other lowercase letter. So after each changing the length of the string doesn't change. At first you can change some letters in s. Then you can permute the order of letters as you want. Permutation doesn't count as changes. You should obtain palindrome with the minimal number of changes. If there are several ways to do that you should get the lexicographically (alphabetically) smallest palindrome. So firstly you should minimize the number of changes and then minimize the palindrome lexicographically. -----Input----- The only line contains string s (1 ≤ |s| ≤ 2·10^5) consisting of only lowercase Latin letters. -----Output----- Print the lexicographically smallest palindrome that can be obtained with the minimal number of changes. -----Examples----- Input aabc Output abba Input aabcd Output abcba
{"inputs": ["u\n", "u\n", "v\n", "w\n", "zza\n", "abb\n", "zaz\n", "acc\n"], "outputs": ["u\n", "u\n", "v\n", "w\n", "zaz\n", "bab\n", "zaz\n", "cac\n"]}
281
73
coding
Solve the programming task below in a Python markdown code block. Guy-Manuel and Thomas have an array $a$ of $n$ integers [$a_1, a_2, \dots, a_n$]. In one step they can add $1$ to any element of the array. Formally, in one step they can choose any integer index $i$ ($1 \le i \le n$) and do $a_i := a_i + 1$. If either the sum or the product of all elements in the array is equal to zero, Guy-Manuel and Thomas do not mind to do this operation one more time. What is the minimum number of steps they need to do to make both the sum and the product of all elements in the array different from zero? Formally, find the minimum number of steps to make $a_1 + a_2 +$ $\dots$ $+ a_n \ne 0$ and $a_1 \cdot a_2 \cdot$ $\dots$ $\cdot a_n \ne 0$. -----Input----- Each test contains multiple test cases. The first line contains the number of test cases $t$ ($1 \le t \le 10^3$). The description of the test cases follows. The first line of each test case contains an integer $n$ ($1 \le n \le 100$) — the size of the array. The second line of each test case contains $n$ integers $a_1, a_2, \dots, a_n$ ($-100 \le a_i \le 100$) — elements of the array . -----Output----- For each test case, output the minimum number of steps required to make both sum and product of all elements in the array different from zero. -----Example----- Input 4 3 2 -1 -1 4 -1 0 0 1 2 -1 2 3 0 -2 1 Output 1 2 0 2 -----Note----- In the first test case, the sum is $0$. If we add $1$ to the first element, the array will be $[3,-1,-1]$, the sum will be equal to $1$ and the product will be equal to $3$. In the second test case, both product and sum are $0$. If we add $1$ to the second and the third element, the array will be $[-1,1,1,1]$, the sum will be equal to $2$ and the product will be equal to $-1$. It can be shown that fewer steps can't be enough. In the third test case, both sum and product are non-zero, we don't need to do anything. In the fourth test case, after adding $1$ twice to the first element the array will be $[2,-2,1]$, the sum will be $1$ and the product will be $-4$.
{"inputs": ["1\n1\n0\n", "1\n1\n0\n", "4\n3\n2 -1 -1\n4\n-1 0 0 1\n2\n-1 2\n3\n0 -2 1\n", "4\n3\n2 -1 -1\n4\n-2 0 0 1\n2\n-1 2\n3\n0 -2 1\n", "4\n3\n2 -1 -1\n4\n-1 0 0 1\n2\n-1 2\n3\n0 -2 1\n", "1\n50\n2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 -98\n", "1\n50\n2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 -98\n", "1\n50\n2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 3 2 2 2 2 2 2 2 2 2 2 2 2 2 -98\n"], "outputs": ["1\n", "1\n", "1\n2\n0\n2\n", "1\n2\n0\n2\n", "1\n2\n0\n2\n", "1\n", "1\n", "0\n"]}
635
510
coding
Solve the programming task below in a Python markdown code block. There are $b$ boys and $g$ girls participating in Olympiad of Metropolises. There will be a board games tournament in the evening and $n$ participants have accepted the invitation. The organizers do not know how many boys and girls are among them. Organizers are preparing red badges for girls and blue ones for boys. Vasya prepared $n+1$ decks of badges. The $i$-th (where $i$ is from $0$ to $n$, inclusive) deck contains $i$ blue badges and $n-i$ red ones. The total number of badges in any deck is exactly $n$. Determine the minimum number of decks among these $n+1$ that Vasya should take, so that there will be a suitable deck no matter how many girls and boys there will be among the participants of the tournament. -----Input----- The first line contains an integer $b$ ($1 \le b \le 300$), the number of boys. The second line contains an integer $g$ ($1 \le g \le 300$), the number of girls. The third line contains an integer $n$ ($1 \le n \le b + g$), the number of the board games tournament participants. -----Output----- Output the only integer, the minimum number of badge decks that Vasya could take. -----Examples----- Input 5 6 3 Output 4 Input 5 3 5 Output 4 -----Note----- In the first example, each of 4 decks should be taken: (0 blue, 3 red), (1 blue, 2 red), (2 blue, 1 red), (3 blue, 0 red). In the second example, 4 decks should be taken: (2 blue, 3 red), (3 blue, 2 red), (4 blue, 1 red), (5 blue, 0 red). Piles (0 blue, 5 red) and (1 blue, 4 red) can not be used.
{"inputs": ["5\n6\n3\n", "5\n3\n5\n", "1\n1\n1\n", "1\n1\n2\n", "3\n3\n4\n", "4\n4\n5\n", "4\n4\n7\n", "3\n3\n5\n"], "outputs": ["4\n", "4\n", "2\n", "1\n", "3\n", "4\n", "2\n", "2\n"]}
445
102
coding
Solve the programming task below in a Python markdown code block. Read problems statements [Hindi] ,[Bengali] , [Mandarin chinese] , [Russian] and [Vietnamese] as well. Consider the following algorithm, which generates a (not necessarily uniformly) random permutation of numbers $1$ through $N$: P := [1, 2, ..., N] for i in 1..N do j := rand(1, N) swap(P[i], P[j]) Here, rand(1, N) returns a uniformly random integer between $1$ and $N$ inclusive. Let's denote the probability that the permutation generated by this algorithm is $P$ by $p(P)$. Find a permutation $P_{1}$ such that $p(P_{1})$ is maximum possible and a permutation $P_{2}$ such that $p(P_{2})$ is minimum possible. ------ Input ------ The first and only line of the input contains a single integer $N$. ------ Output ------ Print two lines. The first line should contain $N$ space-separated integers denoting your permutation $P_{1}$. The second line should contain $N$ space-separated integers denoting your permutation $P_{2}$. If there are multiple answers, you may print any one. ------ Constraints ------ $1 ≤ N ≤ 17$ ------ Subtasks ------ Subtask #1 (20 points): $1 ≤ N ≤ 7$ Subtask #2 (80 points): original constraints ----- Sample Input 1 ------ 2 ----- Sample Output 1 ------ 1 2 2 1 ----- explanation 1 ------ There are two possible permutations, $[1, 2]$ and $[2, 1]$. Both are equally likely to appear as the result of the given algorithm, so any pair of permutations is a valid answer.
{"inputs": ["2"], "outputs": ["1 2\n2 1"]}
400
18
coding
Solve the programming task below in a Python markdown code block. Inna and Dima bought a table of size n × m in the shop. Each cell of the table contains a single letter: "D", "I", "M", "A". Inna loves Dima, so she wants to go through his name as many times as possible as she moves through the table. For that, Inna acts as follows: initially, Inna chooses some cell of the table where letter "D" is written; then Inna can move to some side-adjacent table cell that contains letter "I"; then from this cell she can go to one of the side-adjacent table cells that contains the written letter "M"; then she can go to a side-adjacent cell that contains letter "A". Then Inna assumes that she has gone through her sweetheart's name; Inna's next move can be going to one of the side-adjacent table cells that contains letter "D" and then walk on through name DIMA in the similar manner. Inna never skips a letter. So, from the letter "D" she always goes to the letter "I", from the letter "I" she always goes the to letter "M", from the letter "M" she always goes to the letter "A", and from the letter "A" she always goes to the letter "D". Depending on the choice of the initial table cell, Inna can go through name DIMA either an infinite number of times or some positive finite number of times or she can't go through his name once. Help Inna find out what maximum number of times she can go through name DIMA. -----Input----- The first line of the input contains two integers n and m (1 ≤ n, m ≤ 10^3). Then follow n lines that describe Inna and Dima's table. Each line contains m characters. Each character is one of the following four characters: "D", "I", "M", "A". Note that it is not guaranteed that the table contains at least one letter "D". -----Output----- If Inna cannot go through name DIMA once, print on a single line "Poor Dima!" without the quotes. If there is the infinite number of names DIMA Inna can go through, print "Poor Inna!" without the quotes. Otherwise print a single integer — the maximum number of times Inna can go through name DIMA. -----Examples----- Input 1 2 DI Output Poor Dima! Input 2 2 MA ID Output Poor Inna! Input 5 5 DIMAD DIMAI DIMAM DDMAA AAMID Output 4 -----Note----- Notes to the samples: In the first test sample, Inna cannot go through name DIMA a single time. In the second test sample, Inna can go through the infinite number of words DIMA. For that, she should move in the clockwise direction starting from the lower right corner. In the third test sample the best strategy is to start from the cell in the upper left corner of the table. Starting from this cell, Inna can go through name DIMA four times.
{"inputs": ["1 1\nI\n", "1 1\nD\n", "1 1\nM\n", "1 1\nA\n", "1 1\nD\n", "1 1\nM\n", "1 1\nA\n", "1 1\nI\n"], "outputs": ["Poor Dima!\n", "Poor Dima!\n", "Poor Dima!\n", "Poor Dima!\n", "Poor Dima!\n", "Poor Dima!\n", "Poor Dima!\n", "Poor Dima!\n"]}
675
126
coding
Solve the programming task below in a Python markdown code block. Chef's dog Snuffles has so many things to play with! This time around, Snuffles has an array A containing N integers: A1, A2, ..., AN. Bad news: Snuffles only loves to play with an array in which all the elements are equal. Good news: We have a mover of size D. ! A mover of size D is a tool which helps to change arrays. Chef can pick two existing elements Ai and Aj from the array, such that i + D = j and subtract 1 from one of these elements (the element should have its value at least 1), and add 1 to the other element. In effect, a single operation of the mover, moves a value of 1 from one of the elements to the other. Chef wants to find the minimum number of times she needs to use the mover of size D to make all the elements of the array A equal. Help her find this out. -----Input----- - The first line of the input contains an integer T, denoting the number of test cases. The description of T test cases follows. - The first line of each test case contains two integers N and D, denoting the number of elements in the array and the size of the mover. - The second line of each testcase contains N space-separated integers: A1, A2, ..., AN, denoting the initial elements of the array. -----Output----- - For each test case, output a single line containing the minimum number of uses or -1 if it is impossible to do what Snuffles wants. -----Constraints----- - 1 ≤ T ≤ 10 - 2 ≤ N ≤ 105 - 1 ≤ D < N - 1 ≤ Ai ≤ 109 -----Subtasks----- - Subtask 1 (30 points) : N ≤ 103 - Subtask 2 (70 points) : Original constraints -----Example----- Input: 3 5 2 1 4 5 2 3 3 1 1 4 1 4 2 3 4 3 5 Output: 3 2 -1 -----Explanation----- Testcase 1: Here is a possible sequence of usages of the mover: - Move 1 from A3 to A1 - Move 1 from A3 to A1 - Move 1 from A2 to A4 At the end, the array becomes (3, 3, 3, 3, 3), which Snuffles likes. And you cannot achieve this in fewer moves. Hence the answer is 3. Testcase 2: Here is a possible sequence of usages of the mover: - Move 1 from A2 to A1 - Move 1 from A2 to A3 At the end, the array becomes (2, 2, 2), which Snuffles likes. And you cannot achieve this in fewer moves. Hence the answer is 2. Testcase 3: It is impossible to make all the elements equal. Hence the answer is -1.
{"inputs": ["3\n5 2\n1 4 5 2 3\n3 1\n1 4 1\n4 2\n3 4 3 5"], "outputs": ["3\n2\n-1"]}
660
53
coding
Solve the programming task below in a Python markdown code block. There are N hills in a row numbered 1 through N from left to right. Each hill has a height; for each valid i, the height of the i-th hill is Hi. Chef is initially on the leftmost hill (hill number 1). He can make an arbitrary number of jumps (including zero) as long as the following conditions are satisfied: - Chef can only jump from each hill to the next hill, i.e. from the i-th hill, he can jump to the i+1-th hill (if it exists). - It's always possible to jump to a hill with the same height as the current hill. - It's possible to jump to a taller hill if it's higher than the current hill by no more than U. - It's possible to jump to a lower hill if it's lower than the current hill by no more than D. - Chef can use a parachute and jump to a lower hill regardless of its height (as long as it's lower than the current hill). This jump can only be performed at most once. Chef would like to move as far right as possible. Determine the index of the rightmost hill Chef can reach. -----Input----- - The first line of the input contains a single integer T denoting the number of test cases. The description of T test cases follows. - The first line of each test case contains three space-separated integers N, U and D. - The second line contains N space-separated integers H1, H2, ..., HN. -----Output----- For each test case, print a single line containing one integer — the index of the rightmost reachable hill. -----Constraints----- - 1 ≤ T ≤ 100 - 1 ≤ N ≤ 100 - 1 ≤ U, D ≤ 1,000,000 - 1 ≤ Hi ≤ 1,000,000 for each valid i -----Subtasks----- Subtask #1 (100 points): original constraints -----Example----- Input: 3 5 3 2 2 5 2 6 3 5 2 3 4 4 4 4 4 5 2 7 1 4 3 2 1 Output: 3 5 1 -----Explanation----- Example case 1: Chef can jump to second hill because it's higher by no more than U=3 than first hill, to jump to third hill Chef has to use parachute because it's lower than second hill by 3 which is more than D=2, Chef can't jump to fourth hill because it's higher than third hill by 4 which is more than U=3 Example case 2: All hills are of the same height, so chef can reach the last hill with no problems. Example case 3: Chef can't jump to second hill because it's too high for him
{"inputs": ["3\n5 3 2\n2 5 2 6 3\n5 2 3\n4 4 4 4 4\n5 2 7\n1 4 3 2 1"], "outputs": ["3\n5\n1"]}
616
64
coding
Solve the programming task below in a Python markdown code block. Today an outstanding event is going to happen in the forest — hedgehog Filya will come to his old fried Sonya! Sonya is an owl and she sleeps during the day and stay awake from minute l_1 to minute r_1 inclusive. Also, during the minute k she prinks and is unavailable for Filya. Filya works a lot and he plans to visit Sonya from minute l_2 to minute r_2 inclusive. Calculate the number of minutes they will be able to spend together. -----Input----- The only line of the input contains integers l_1, r_1, l_2, r_2 and k (1 ≤ l_1, r_1, l_2, r_2, k ≤ 10^18, l_1 ≤ r_1, l_2 ≤ r_2), providing the segments of time for Sonya and Filya and the moment of time when Sonya prinks. -----Output----- Print one integer — the number of minutes Sonya and Filya will be able to spend together. -----Examples----- Input 1 10 9 20 1 Output 2 Input 1 100 50 200 75 Output 50 -----Note----- In the first sample, they will be together during minutes 9 and 10. In the second sample, they will be together from minute 50 to minute 74 and from minute 76 to minute 100.
{"inputs": ["6 6 5 8 9\n", "1 1 1 1 1\n", "1 2 3 4 5\n", "1 3 3 5 3\n", "1 2 2 3 5\n", "2 4 3 7 3\n", "2 4 1 2 5\n", "4 6 6 8 9\n"], "outputs": ["1\n", "0\n", "0\n", "0\n", "1\n", "1\n", "1\n", "1\n"]}
338
134
coding
Solve the programming task below in a Python markdown code block. This kata focuses on the Numpy python package and you can read up on the Numpy array manipulation functions here: https://docs.scipy.org/doc/numpy-1.13.0/reference/routines.array-manipulation.html You will get two integers `N` and `M`. You must return an array with two sub-arrays with numbers in ranges `[0, N / 2)` and `[N / 2, N)` respectively, each of them being rotated `M` times. ``` reorder(10, 1) => [[4, 0, 1, 2, 3], [9, 5, 6, 7, 8]] reorder(10, 3) => [[2, 3, 4, 0, 1], [7, 8, 9, 5, 6]] reorder(10, 97) => [[3, 4, 0, 1, 2], [8, 9, 5, 6, 7]] ``` Also feel free to reuse/extend the following starter code: ```python def reorder(a, b): ```
{"functional": "_inputs = [[10, 1], [10, 3], [10, 97]]\n_outputs = [[[[4, 0, 1, 2, 3], [9, 5, 6, 7, 8]]], [[[2, 3, 4, 0, 1], [7, 8, 9, 5, 6]]], [[[3, 4, 0, 1, 2], [8, 9, 5, 6, 7]]]]\nimport math\ndef _deep_eq(a, b, tol=1e-5):\n if isinstance(a, float) or isinstance(b, float):\n return math.isclose(a, b, rel_tol=tol, abs_tol=tol)\n if isinstance(a, (list, tuple)):\n if len(a) != len(b): return False\n return all(_deep_eq(x, y, tol) for x, y in zip(a, b))\n return a == b\n\nfor i, o in zip(_inputs, _outputs):\n assert _deep_eq(reorder(*i), o[0])"}
269
264
coding
Solve the programming task below in a Python markdown code block. The Story: Aliens from Kepler 27b have immigrated to Earth! They have learned English and go to our stores, eat our food, dress like us, ride Ubers, use Google, etc. However, they speak English a little differently. Can you write a program that converts our English to their Alien English? Task: Write a function converting their speech to ours. They tend to speak the letter `a` like `o` and `o` like a `u`. ```python >>> convert('hello') 'hellu' >>> convert('codewars') 'cudewors' ``` Also feel free to reuse/extend the following starter code: ```python def convert(st): ```
{"functional": "_inputs = [['codewars'], ['hello']]\n_outputs = [['cudewors'], ['hellu']]\nimport math\ndef _deep_eq(a, b, tol=1e-5):\n if isinstance(a, float) or isinstance(b, float):\n return math.isclose(a, b, rel_tol=tol, abs_tol=tol)\n if isinstance(a, (list, tuple)):\n if len(a) != len(b): return False\n return all(_deep_eq(x, y, tol) for x, y in zip(a, b))\n return a == b\n\nfor i, o in zip(_inputs, _outputs):\n assert _deep_eq(convert(*i), o[0])"}
160
165
coding
Solve the programming task below in a Python markdown code block. You are given two integers $a$ and $b$. You can perform a sequence of operations: during the first operation you choose one of these numbers and increase it by $1$; during the second operation you choose one of these numbers and increase it by $2$, and so on. You choose the number of these operations yourself. For example, if $a = 1$ and $b = 3$, you can perform the following sequence of three operations: add $1$ to $a$, then $a = 2$ and $b = 3$; add $2$ to $b$, then $a = 2$ and $b = 5$; add $3$ to $a$, then $a = 5$ and $b = 5$. Calculate the minimum number of operations required to make $a$ and $b$ equal. -----Input----- The first line contains one integer $t$ ($1 \le t \le 100$) — the number of test cases. The only line of each test case contains two integers $a$ and $b$ ($1 \le a, b \le 10^9$). -----Output----- For each test case print one integer — the minimum numbers of operations required to make $a$ and $b$ equal. -----Example----- Input 3 1 3 11 11 30 20 Output 3 0 4 -----Note----- First test case considered in the statement. In the second test case integers $a$ and $b$ are already equal, so you don't need to perform any operations. In the third test case you have to apply the first, the second, the third and the fourth operation to $b$ ($b$ turns into $20 + 1 + 2 + 3 + 4 = 30$).
{"inputs": ["1\n0 2\n", "1\n0 0\n", "1\n1 0\n", "1\n1 1\n", "1\n1 2\n", "1\n0 79\n", "1\n0 10\n", "1\n0 -1\n"], "outputs": ["3\n", "0\n", "1\n", "0\n", "1\n", "13\n", "4\n", "1\n"]}
413
105
coding
Please solve the programming task below using a self-contained code snippet in a markdown code block. You are given an array of strings words and a string chars. A string is good if it can be formed by characters from chars (each character can only be used once). Return the sum of lengths of all good strings in words.   Please complete the following python code precisely: ```python class Solution: def countCharacters(self, words: List[str], chars: str) -> int: ```
{"functional": "def check(candidate):\n assert candidate(words = [\"cat\",\"bt\",\"hat\",\"tree\"], chars = \"atach\") == 6\n assert candidate(words = [\"hello\",\"world\",\"leetcode\"], chars = \"welldonehoneyr\") == 10\n\n\ncheck(Solution().countCharacters)"}
99
74
coding
Solve the programming task below in a Python markdown code block. Late last night in the Tanner household, ALF was repairing his spaceship so he might get back to Melmac. Unfortunately for him, he forgot to put on the parking brake, and the spaceship took off during repair. Now it's hovering in space. ALF has the technology to bring the spaceship home if he can lock on to its location. Given a map: ```` .......... .......... .......... .......X.. .......... .......... ```` The map will be given in the form of a string with \n separating new lines. The bottom left of the map is [0, 0]. X is ALF's spaceship. In this example: If you cannot find the spaceship, the result should be ``` "Spaceship lost forever." ``` Can you help ALF? Check out my other 80's Kids Katas: 80's Kids #1: How Many Licks Does It Take 80's Kids #2: Help Alf Find His Spaceship 80's Kids #3: Punky Brewster's Socks 80's Kids #4: Legends of the Hidden Temple 80's Kids #5: You Can't Do That on Television 80's Kids #6: Rock 'Em, Sock 'Em Robots 80's Kids #7: She's a Small Wonder 80's Kids #8: The Secret World of Alex Mack 80's Kids #9: Down in Fraggle Rock 80's Kids #10: Captain Planet Also feel free to reuse/extend the following starter code: ```python def find_spaceship(astromap): ```
{"functional": "_inputs = [['X'], ['X\\n.'], ['.X\\n..'], ['..\\n.X'], ['..\\nX.'], ['.......\\nX.......'], ['..........\\n..........\\n.......X..\\n..........\\n..........'], ['..........\\n..........\\n..........\\n........X.\\n..........'], ['........................'], ['\\n\\n\\n\\n']]\n_outputs = [[[0, 0]], [[0, 1]], [[1, 1]], [[1, 0]], [[0, 0]], [[0, 0]], [[7, 2]], [[8, 1]], ['Spaceship lost forever.'], ['Spaceship lost forever.']]\nimport math\ndef _deep_eq(a, b, tol=1e-5):\n if isinstance(a, float) or isinstance(b, float):\n return math.isclose(a, b, rel_tol=tol, abs_tol=tol)\n if isinstance(a, (list, tuple)):\n if len(a) != len(b): return False\n return all(_deep_eq(x, y, tol) for x, y in zip(a, b))\n return a == b\n\nfor i, o in zip(_inputs, _outputs):\n assert _deep_eq(find_spaceship(*i), o[0])"}
351
292
coding
Solve the programming task below in a Python markdown code block. After Misha's birthday he had many large numbers left, scattered across the room. Now it's time to clean up and Misha needs to put them in a basket. He ordered this task to his pet robot that agreed to complete the task at certain conditions. Before the robot puts a number x to the basket, Misha should answer the question: is it possible to choose one or multiple numbers that already are in the basket, such that their XOR sum equals x? If the answer is positive, you also need to give the indexes of these numbers. If there are multiple options of choosing numbers, you are allowed to choose any correct option. After Misha's answer the robot puts the number to the basket. Initially the basket is empty. Each integer you put in the basket takes some number. The first integer you put into the basket take number 0, the second integer takes number 1 and so on. Misha needs to clean up the place as soon as possible but unfortunately, he isn't that good at mathematics. He asks you to help him. -----Input----- The first line contains number m (1 ≤ m ≤ 2000), showing how many numbers are scattered around the room. The next m lines contain the numbers in the order in which the robot puts them in the basket. Each number is a positive integer strictly less than 10^600 that doesn't contain leading zeroes. -----Output----- For each number either print a 0 on the corresponding line, if the number cannot be represented as a XOR sum of numbers that are in the basket, or print integer k showing how many numbers are in the representation and the indexes of these numbers. Separate the numbers by spaces. Each number can occur in the representation at most once. -----Examples----- Input 7 7 6 5 4 3 2 1 Output 0 0 0 3 0 1 2 2 1 2 2 0 2 2 0 1 Input 2 5 5 Output 0 1 0 -----Note----- The XOR sum of numbers is the result of bitwise sum of numbers modulo 2.
{"inputs": ["2\n5\n5\n", "2\n3\n5\n", "2\n6\n5\n", "2\n7\n5\n", "2\n7\n6\n", "2\n7\n9\n", "2\n5\n5\n", "2\n7\n12\n"], "outputs": ["0\n1 0\n", "0\n0\n", "0\n0\n", "0\n0\n", "0\n0\n", "0\n0\n", "0\n1 0\n", "0\n0\n"]}
464
123
coding
Solve the programming task below in a Python markdown code block. Permutation p is an ordered set of integers p_1, p_2, ..., p_{n}, consisting of n distinct positive integers, each of them doesn't exceed n. We'll denote the i-th element of permutation p as p_{i}. We'll call number n the size or the length of permutation p_1, p_2, ..., p_{n}. Petya decided to introduce the sum operation on the set of permutations of length n. Let's assume that we are given two permutations of length n: a_1, a_2, ..., a_{n} and b_1, b_2, ..., b_{n}. Petya calls the sum of permutations a and b such permutation c of length n, where c_{i} = ((a_{i} - 1 + b_{i} - 1) mod n) + 1 (1 ≤ i ≤ n). Operation $x \text{mod} y$ means taking the remainder after dividing number x by number y. Obviously, not for all permutations a and b exists permutation c that is sum of a and b. That's why Petya got sad and asked you to do the following: given n, count the number of such pairs of permutations a and b of length n, that exists permutation c that is sum of a and b. The pair of permutations x, y (x ≠ y) and the pair of permutations y, x are considered distinct pairs. As the answer can be rather large, print the remainder after dividing it by 1000000007 (10^9 + 7). -----Input----- The single line contains integer n (1 ≤ n ≤ 16). -----Output----- In the single line print a single non-negative integer — the number of such pairs of permutations a and b, that exists permutation c that is sum of a and b, modulo 1000000007 (10^9 + 7). -----Examples----- Input 3 Output 18 Input 5 Output 1800
{"inputs": ["3\n", "5\n", "1\n", "2\n", "4\n", "6\n", "7\n", "8\n"], "outputs": ["18\n", "1800\n", "1\n", "0\n", "0\n", "0\n", "670320\n", "0\n"]}
455
79
coding
Solve the programming task below in a Python markdown code block. Kevin Sun wants to move his precious collection of n cowbells from Naperthrill to Exeter, where there is actually grass instead of corn. Before moving, he must pack his cowbells into k boxes of a fixed size. In order to keep his collection safe during transportation, he won't place more than two cowbells into a single box. Since Kevin wishes to minimize expenses, he is curious about the smallest size box he can use to pack his entire collection. Kevin is a meticulous cowbell collector and knows that the size of his i-th (1 ≤ i ≤ n) cowbell is an integer s_{i}. In fact, he keeps his cowbells sorted by size, so s_{i} - 1 ≤ s_{i} for any i > 1. Also an expert packer, Kevin can fit one or two cowbells into a box of size s if and only if the sum of their sizes does not exceed s. Given this information, help Kevin determine the smallest s for which it is possible to put all of his cowbells into k boxes of size s. -----Input----- The first line of the input contains two space-separated integers n and k (1 ≤ n ≤ 2·k ≤ 100 000), denoting the number of cowbells and the number of boxes, respectively. The next line contains n space-separated integers s_1, s_2, ..., s_{n} (1 ≤ s_1 ≤ s_2 ≤ ... ≤ s_{n} ≤ 1 000 000), the sizes of Kevin's cowbells. It is guaranteed that the sizes s_{i} are given in non-decreasing order. -----Output----- Print a single integer, the smallest s for which it is possible for Kevin to put all of his cowbells into k boxes of size s. -----Examples----- Input 2 1 2 5 Output 7 Input 4 3 2 3 5 9 Output 9 Input 3 2 3 5 7 Output 8 -----Note----- In the first sample, Kevin must pack his two cowbells into the same box. In the second sample, Kevin can pack together the following sets of cowbells: {2, 3}, {5} and {9}. In the third sample, the optimal solution is {3, 5} and {7}.
{"inputs": ["1 1\n1\n", "1 1\n1\n", "1 2\n10\n", "1 2\n10\n", "1 1\n10\n", "2 1\n2 5\n", "2 2\n2 3\n", "2 2\n2 3\n"], "outputs": ["1\n", "1\n", "10\n", "10\n", "10\n", "7\n", "3\n", "3\n"]}
527
114
coding
Solve the programming task below in a Python markdown code block. # It's too hot, and they can't even… One hot summer day Pete and his friend Billy decided to buy watermelons. They chose the biggest crate. They rushed home, dying of thirst, and decided to divide their loot, however they faced a hard problem. Pete and Billy are great fans of even numbers, that's why they want to divide the number of watermelons in such a way that each of the two parts consists of an even number of watermelons. However, it is not obligatory that the parts are equal. Example: the boys can divide a stack of 8 watermelons into 2+6 melons, or 4+4 melons. The boys are extremely tired and want to start their meal as soon as possible, that's why you should help them and find out, whether they can divide the fruits in the way they want. For sure, each of them should get a part of positive weight. # Task Given an integral number of watermelons `w` (`1 ≤ w ≤ 100`; `1 ≤ w` in Haskell), check whether Pete and Billy can divide the melons so that each of them gets an even amount. ## Examples Also feel free to reuse/extend the following starter code: ```python def divide(weight): ```
{"functional": "_inputs = [[4], [2], [5], [88], [100], [67], [90], [10], [99], [32]]\n_outputs = [[True], [False], [False], [True], [True], [False], [True], [True], [False], [True]]\nimport math\ndef _deep_eq(a, b, tol=1e-5):\n if isinstance(a, float) or isinstance(b, float):\n return math.isclose(a, b, rel_tol=tol, abs_tol=tol)\n if isinstance(a, (list, tuple)):\n if len(a) != len(b): return False\n return all(_deep_eq(x, y, tol) for x, y in zip(a, b))\n return a == b\n\nfor i, o in zip(_inputs, _outputs):\n assert _deep_eq(divide(*i), o[0])"}
295
216
coding
Solve the programming task below in a Python markdown code block. # Task John won the championship of a TV show. He can get some bonuses. He needs to play a game to determine the amount of his bonus. Here are `n` rows and `m` columns of cards were placed on the ground. A non-negative number is written on each card. The rules of the game are: - Player starts from the top-left coner, walk to the bottom-right coner. - Players can only walk downward or right. - The sum of the numbers collected by the players will be used as the bonus. John has two chances to play this game on a game map. Specifically, when John finishes the game, the card on his path will be removed, and then he can walk again. Your task is to help John calculate the maximum amount of bonuses he can get. # Input - `gameMap/gamemap`: A `n` x `m` integer array. Each element represents the number on the card. - `4 <= n,m <= 40(Pyhon)/100(JS)` - All inputs are valid. # Output An integer. the maximum amount of bonuses John can get. # Eaxmple For ``` gameMap= [ [1, 3, 9], [2, 8, 5], [5, 7, 4] ] ``` The output should be `39`. One of the possible solution is: ``` 1st game: [ [>, >, v], [2, 8, v], [5, 7, v] ] 1+3+9+5+4=22 2nd game: [ [v, 0, 0], [>, v, 0], [5, >, >] ] 0+2+8+7+0=17 Final bonus = 22 + 17 = 39 ``` Also feel free to reuse/extend the following starter code: ```python def calc(gamemap): ```
{"functional": "_inputs = [[[[1, 3, 9], [2, 8, 5], [5, 7, 4]]], [[[11, 72, 38], [80, 69, 65], [68, 96, 99]]], [[[1, 5, 1, 1], [1, 5, 5, 1], [5, 5, 5, 1], [1, 1, 5, 1]]], [[[0, 0, 2, 3, 0, 0, 0], [0, 0, 3, 0, 0, 0, 0], [0, 0, 3, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 4, 0, 0], [0, 0, 0, 0, 4, 0, 0], [0, 0, 2, 0, 4, 0, 0], [0, 0, 0, 0, 0, 0, 0]]]]\n_outputs = [[39], [560], [40], [25]]\nimport math\ndef _deep_eq(a, b, tol=1e-5):\n if isinstance(a, float) or isinstance(b, float):\n return math.isclose(a, b, rel_tol=tol, abs_tol=tol)\n if isinstance(a, (list, tuple)):\n if len(a) != len(b): return False\n return all(_deep_eq(x, y, tol) for x, y in zip(a, b))\n return a == b\n\nfor i, o in zip(_inputs, _outputs):\n assert _deep_eq(calc(*i), o[0])"}
434
448
coding
Solve the programming task below in a Python markdown code block. Given two integers $n$ and $\textbf{r}$. In how many ways can $\textbf{r}$ items be chosen from $n$ items? Input Format The first line contains the number of test cases $\mathbf{T}$. Each of the next $\mathbf{T}$ lines contains two integers $n$ and $\textbf{r}$. Constraints $1\leq T\leq10^5$ $1\leq n\leq10^9$ $0\leq r\leq n$ Output Format Output $\mathbf{T}$ lines, containing the required answer for the corresponding test case. Output all answers modulo $142857$. Sample Input 4 2 1 4 0 5 2 10 3 Sample Output 2 1 10 120
{"inputs": ["4\n2 1\n4 0\n5 2\n10 3\n"], "outputs": ["2\n1\n10\n120\n"]}
201
40
coding
Solve the programming task below in a Python markdown code block. Read problems statements in Mandarin Chinese, Russian and Vietnamese as well. There are N chairs placed in circular order. Some of the chairs are empty while others have a child sitting in it. You are required to change the places of the children so that all the children sit next to each other (i.e. they form a connected segment). You can do that by doing the following operation a number of times: Choose a child and tell him to walk around the circle in clockwise order or anti-clockwise order until he finds the first empty chair, and tell him to sit there. What is the minimum number of operations required to make all children sit next to each other? ------ Input ------ The first line contains T, the number of test-cases. The first line of each test-case contains N, the number of chairs. The second line of each test-case contains a binary string of length N. If the i-th character is 1 then the i-th chair has a child initially. Otherwise (i.e. the i-th character is 0) it's empty. ------ Output ------ For each test case, output a single line containing a single integer donating minimum number of operations needed. ------ Constraints ------ $1 ≤ T ≤ 5,000$ $1 ≤ sum of N in all test-cases ≤ 10^{6}$ $at least one chair will be occupied$ ----- Sample Input 1 ------ 1 8 10001010 ----- Sample Output 1 ------ 2 ----- explanation 1 ------ The initial configuration is: 1 0 0 1 0 0 0 1 We can tell the child who is boldened to move counter-clockwise, and the new configuration will be: 0 1 0 1 0 0 0 1 because he has moved to the first empty chair on his way. Now, we again tell him to move counter-clockwise, and now the new configuration will be: 0 0 0 1 0 1 0 1 because he moved counter-clockwise, found an occupied chair, and hence kept moving. The next chair was vacant, and he sat down there. Note that, in this example, we moved the same child twice, but this need not be the case. We can move different children in different moves. You can check that this is the best we can do, and 2 is the minimum.
{"inputs": ["1\n8\n10001010"], "outputs": ["2"]}
531
23
coding
Please solve the programming task below using a self-contained code snippet in a markdown code block. Given an binary array nums and an integer k, return true if all 1's are at least k places away from each other, otherwise return false.   Please complete the following python code precisely: ```python class Solution: def kLengthApart(self, nums: List[int], k: int) -> bool: ```
{"functional": "def check(candidate):\n assert candidate(nums = [1,0,0,0,1,0,0,1], k = 2) == True\n assert candidate(nums = [1,0,0,1,0,1], k = 2) == False\n assert candidate(nums = [1,1,1,1,1], k = 0) == True\n assert candidate(nums = [0,1,0,1], k = 1) == True\n\n\ncheck(Solution().kLengthApart)"}
84
122
coding
Solve the programming task below in a Python markdown code block. Write a program that extracts n different numbers from the numbers 0 to 100 and outputs the number of combinations that add up to s. Each n number is from 0 to 100, and the same number cannot be used in one combination. For example, if n is 3 and s is 6, the combination of the three numbers totaling 6 is 1 + 2 + 3 = 6 0 + 1 + 5 = 6 0 + 2 + 4 = 6 There are three ways. Input Given multiple datasets. For each dataset, n (1 ≤ n ≤ 9) and s (0 ≤ s ≤ 1000) are given on one line, separated by a space. When both n and s are 0, it is the end of the input. The number of datasets does not exceed 50. Output For each dataset, output the number of combinations in which the sum of n integers is s on one line. No input is given with more than 1010 combinations. Example Input 3 6 3 1 0 0 Output 3 0
{"inputs": ["6 6\n3 1\n0 0", "2 8\n4 3\n0 0", "3 4\n1 3\n0 0", "3 4\n2 3\n0 0", "3 0\n2 3\n0 0", "3 1\n2 9\n0 0", "3 6\n3 1\n0 0", "3 12\n3 1\n0 0"], "outputs": ["0\n0\n", "4\n0\n", "1\n1\n", "1\n2\n", "0\n2\n", "0\n5\n", "3\n0", "12\n0\n"]}
260
159
coding
Solve the programming task below in a Python markdown code block. The [Sharkovsky's Theorem](https://en.wikipedia.org/wiki/Sharkovskii%27s_theorem) involves the following ordering of the natural numbers: ```math 3≺5≺7≺9≺ ...\\ ≺2·3≺2·5≺2·7≺2·9≺...\\ ≺2^n·3≺2^n·5≺2^n·7≺2^n·9≺...\\ ≺2^{(n+1)}·3≺2^{(n+1)}·5≺2^{(n+1)}·7≺2^{(n+1)}·9≺...\\ ≺2^n≺2^{(n-1)}≺...\\ ≺4≺2≺1\\ ``` Your task is to complete the function which returns `true` if `$a≺b$` according to this ordering, and `false` otherwise. You may assume both `$a$` and `$b$` are non-zero positive integers. Also feel free to reuse/extend the following starter code: ```python def sharkovsky(a, b): ```
{"functional": "_inputs = [[18, 12], [3, 9], [10, 16], [1, 22], [32, 1024], [17, 17]]\n_outputs = [[True], [True], [True], [False], [False], [False]]\nimport math\ndef _deep_eq(a, b, tol=1e-5):\n if isinstance(a, float) or isinstance(b, float):\n return math.isclose(a, b, rel_tol=tol, abs_tol=tol)\n if isinstance(a, (list, tuple)):\n if len(a) != len(b): return False\n return all(_deep_eq(x, y, tol) for x, y in zip(a, b))\n return a == b\n\nfor i, o in zip(_inputs, _outputs):\n assert _deep_eq(sharkovsky(*i), o[0])"}
250
214
coding
Solve the programming task below in a Python markdown code block. Read problem statements in [Hindi], [Bengali], [Mandarin Chinese], [Russian], and [Vietnamese] as well. You are given two strings $S$ and $R$. You may reorder the characters in the string $R$ in any way; let's denote the resulting string by $R_{r}$. This reordered string is *valid* if it contains all substrings of $S$, i.e. for each substring $s$ of $S$ (including $S$ itself), $R_{r}$ contains $s$ as a substring. Find the lexicographically smallest valid reordered string or determine that there is no such valid string. ------ Input ------ The first line of the input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows. The first line of each test case contains a single string $S$. The second line contains a single string $R$. ------ Output ------ For each test case, print a single line containing one string — the lexicographically smallest valid reordered string, or "Impossible" if there is no such string. ------ Constraints ------ $1 ≤ T ≤ 1,000$ $1 ≤ |S|, |R| ≤ 10^{5}$ $S$ and $R$ contain only lowercase English letters the sum of $|S|$ over all test cases does not exceed $10^{6}$ the sum of $|R|$ over all test cases does not exceed $10^{6}$ ------ Subtasks ------ Subtask #1 (50 points): $1 ≤ |S|, |R| ≤ 1,000$ $S$ and $R$ contain only the characters 'a' and 'b' the sum of $|S|$ in all test cases does not exceed $10^{4}$ the sum of $|R|$ in all test cases does not exceed $10^{4}$ Subtask #2 (50 points): original constraints ----- Sample Input 1 ------ 4 aa ababab aaa ramialsadaka said sryhieni code codeisfun ----- Sample Output 1 ------ aaabbb aaaaadiklmrs Impossible codefinsu
{"inputs": ["4\naa\nababab\naaa\nramialsadaka\nsaid\nsryhieni\ncode\ncodeisfun"], "outputs": ["aaabbb\naaaaadiklmrs\nImpossible\ncodefinsu"]}
506
56
coding
Solve the programming task below in a Python markdown code block. Sherlock is given an array of $N$ integers ($A_0,A_1...A_{N-1}$ by Watson. Now Watson asks Sherlock how many different pairs of indices $\boldsymbol{i}$ and $j$ exist such that $\boldsymbol{i}$ is not equal to $j$ but $A_i$ is equal to $A_j$. That is, Sherlock has to count the total number of pairs of indices $(i,j)$ where $A_i$=$A_j$ AND $i\neq j$. Input Format The first line contains $\mathbf{T}$, the number of test cases. $\mathbf{T}$ test cases follow. Each test case consists of two lines; the first line contains an integer $N$, the size of array, while the next line contains $N$ space separated integers. Output Format For each test case, print the required answer on a different line. Constraints $1\leq T\leq10$ $1\leq N\leq$10^5$$ $1\leq A[i]\leq$10^6$$ Sample input 2 3 1 2 3 3 1 1 2 Sample output 0 2 Explanation In the first test case, no two pair of indices exist which satisfy the given condition. In the second test case as A[0] = A[1] = 1, the pairs of indices (0,1) and (1,0) satisfy the given condition.
{"inputs": ["2\n3\n1 2 3\n3\n1 1 2\n"], "outputs": ["0\n2\n"]}
342
32
coding
Solve the programming task below in a Python markdown code block. If I give you a date, can you tell me what day that date is? For example, december 8th, 2015 is a tuesday. Your job is to write the function ```day(d)``` which takes a string representation of a date as input, in the format YYYYMMDD. The example would be "20151208". The function needs to output the string representation of the day, so in this case ```"Tuesday"```. Your function should be able to handle dates ranging from January first, 1582 (the year the Gregorian Calendar was introduced) to December 31st, 9999. You will not be given invalid dates. Remember to take leap years into account. Also feel free to reuse/extend the following starter code: ```python def day(date): ```
{"functional": "_inputs = [['20151208'], ['20140728'], ['20160229'], ['20160301'], ['19000228'], ['19000301']]\n_outputs = [['Tuesday'], ['Monday'], ['Monday'], ['Tuesday'], ['Wednesday'], ['Thursday']]\nimport math\ndef _deep_eq(a, b, tol=1e-5):\n if isinstance(a, float) or isinstance(b, float):\n return math.isclose(a, b, rel_tol=tol, abs_tol=tol)\n if isinstance(a, (list, tuple)):\n if len(a) != len(b): return False\n return all(_deep_eq(x, y, tol) for x, y in zip(a, b))\n return a == b\n\nfor i, o in zip(_inputs, _outputs):\n assert _deep_eq(day(*i), o[0])"}
192
225
coding
Solve the programming task below in a Python markdown code block. An n × n table a is defined as follows: The first row and the first column contain ones, that is: a_{i}, 1 = a_{1, }i = 1 for all i = 1, 2, ..., n. Each of the remaining numbers in the table is equal to the sum of the number above it and the number to the left of it. In other words, the remaining elements are defined by the formula a_{i}, j = a_{i} - 1, j + a_{i}, j - 1. These conditions define all the values in the table. You are given a number n. You need to determine the maximum value in the n × n table defined by the rules above. -----Input----- The only line of input contains a positive integer n (1 ≤ n ≤ 10) — the number of rows and columns of the table. -----Output----- Print a single line containing a positive integer m — the maximum value in the table. -----Examples----- Input 1 Output 1 Input 5 Output 70 -----Note----- In the second test the rows of the table look as follows: {1, 1, 1, 1, 1}, {1, 2, 3, 4, 5}, {1, 3, 6, 10, 15}, {1, 4, 10, 20, 35}, {1, 5, 15, 35, 70}.
{"inputs": ["1\n", "5\n", "2\n", "3\n", "4\n", "6\n", "7\n", "9\n"], "outputs": ["1", "70", "2", "6", "20", "252", "924", "12870"]}
345
72
coding
Solve the programming task below in a Python markdown code block. Adam is standing at point $(a,b)$ in an infinite 2D grid. He wants to know if he can reach point $(x,y)$ or not. The only operation he can do is to move to point $(a+b,b),(a,a+b),(a-b,b),\text{or}(a,b-a)$ from some point $(a,b)$. It is given that he can move to any point on this 2D grid, i.e., the points having positive or negative $\mbox{X}$(or $\mathbf{Y}$) co-ordinates. Tell Adam whether he can reach $(x,y)$ or not. Input Format The first line contains an integer, $\mathbf{T}$, followed by $\mathbf{T}$ lines, each containing $4$ space-separated integers i.e. $\boldsymbol{a}$, $\boldsymbol{b}$, $\boldsymbol{x}$ and $y$. Constraints $1\leq T\leq1000$ $1\leq a,b,x,y\leq10^{18}$ Output Format For each test case, display YES or NO that indicates if Adam can reach $(x,y)$ or not. Sample Input 3 1 1 2 3 2 1 2 3 3 3 1 1 Sample Output YES YES NO Explanation (1,1) -> (2,1) -> (2,3).
{"inputs": ["3\n1 1 2 3\n2 1 2 3\n3 3 1 1\n"], "outputs": ["YES\nYES\nNO\n"]}
325
42
coding
Solve the programming task below in a Python markdown code block. Polycarp has recently got himself a new job. He now earns so much that his old wallet can't even store all the money he has. Berland bills somehow come in lots of different sizes. However, all of them are shaped as rectangles (possibly squares). All wallets are also produced in form of rectangles (possibly squares). A bill $x \times y$ fits into some wallet $h \times w$ if either $x \le h$ and $y \le w$ or $y \le h$ and $x \le w$. Bills can overlap with each other in a wallet and an infinite amount of bills can fit into a wallet. That implies that all the bills Polycarp currently have fit into a wallet if every single one of them fits into it independently of the others. Now you are asked to perform the queries of two types: $+~x~y$ — Polycarp earns a bill of size $x \times y$; $?~h~w$ — Polycarp wants to check if all the bills he has earned to this moment fit into a wallet of size $h \times w$. It is guaranteed that there is at least one query of type $1$ before the first query of type $2$ and that there is at least one query of type $2$ in the input data. For each query of type $2$ print "YES" if all the bills he has earned to this moment fit into a wallet of given size. Print "NO" otherwise. -----Input----- The first line contains a single integer $n$ ($2 \le n \le 5 \cdot 10^5$) — the number of queries. Each of the next $n$ lines contains a query of one of these two types: $+~x~y$ ($1 \le x, y \le 10^9$) — Polycarp earns a bill of size $x \times y$; $?~h~w$ ($1 \le h, w \le 10^9$) — Polycarp wants to check if all the bills he has earned to this moment fit into a wallet of size $h \times w$. It is guaranteed that there is at least one query of type $1$ before the first query of type $2$ and that there is at least one query of type $2$ in the input data. -----Output----- For each query of type $2$ print "YES" if all the bills he has earned to this moment fit into a wallet of given size. Print "NO" otherwise. -----Example----- Input 9 + 3 2 + 2 3 ? 1 20 ? 3 3 ? 2 3 + 1 5 ? 10 10 ? 1 5 + 1 1 Output NO YES YES YES NO -----Note----- The queries of type $2$ of the example: Neither bill fits; Both bills fit (just checking that you got that bills can overlap); Both bills fit (both bills are actually the same); All bills fit (too much of free space in a wallet is not a problem); Only bill $1 \times 5$ fit (all the others don't, thus it's "NO").
{"inputs": ["2\n+ 2 2\n? 2 2\n", "2\n+ 2 2\n? 2 2\n", "2\n+ 2 2\n? 4 2\n", "2\n+ 2 1\n? 2 2\n", "2\n+ 2 2\n? 8 2\n", "2\n+ 1 1\n? 2 2\n", "2\n+ 2 2\n? 6 2\n", "2\n+ 1 2\n? 6 2\n"], "outputs": ["YES\n", "YES\n", "YES\n", "YES\n", "YES\n", "YES\n", "YES\n", "YES\n"]}
721
166
coding
Solve the programming task below in a Python markdown code block. I have the `par` value for each hole on a golf course and my stroke `score` on each hole. I have them stored as strings, because I wrote them down on a sheet of paper. Right now, I'm using those strings to calculate my golf score by hand: take the difference between my actual `score` and the `par` of the hole, and add up the results for all 18 holes. For example: * If I took 7 shots on a hole where the par was 5, my score would be: 7 - 5 = 2 * If I got a hole-in-one where the par was 4, my score would be: 1 - 4 = -3. Doing all this math by hand is really hard! Can you help make my life easier? ## Task Overview Complete the function which accepts two strings and calculates the golf score of a game. Both strings will be of length 18, and each character in the string will be a number between 1 and 9 inclusive. Also feel free to reuse/extend the following starter code: ```python def golf_score_calculator(par_string, score_string): ```
{"functional": "_inputs = [['443454444344544443', '353445334534445344'], ['123456123456123456', '123456123456123456']]\n_outputs = [[-1], [0]]\nimport math\ndef _deep_eq(a, b, tol=1e-5):\n if isinstance(a, float) or isinstance(b, float):\n return math.isclose(a, b, rel_tol=tol, abs_tol=tol)\n if isinstance(a, (list, tuple)):\n if len(a) != len(b): return False\n return all(_deep_eq(x, y, tol) for x, y in zip(a, b))\n return a == b\n\nfor i, o in zip(_inputs, _outputs):\n assert _deep_eq(golf_score_calculator(*i), o[0])"}
258
238
coding
Please solve the programming task below using a self-contained code snippet in a markdown code block. You are given a string s that consists of the digits '1' to '9' and two integers k and minLength. A partition of s is called beautiful if: s is partitioned into k non-intersecting substrings. Each substring has a length of at least minLength. Each substring starts with a prime digit and ends with a non-prime digit. Prime digits are '2', '3', '5', and '7', and the rest of the digits are non-prime. Return the number of beautiful partitions of s. Since the answer may be very large, return it modulo 109 + 7. A substring is a contiguous sequence of characters within a string.   Please complete the following python code precisely: ```python class Solution: def beautifulPartitions(self, s: str, k: int, minLength: int) -> int: ```
{"functional": "def check(candidate):\n assert candidate(s = \"23542185131\", k = 3, minLength = 2) == 3\n assert candidate(s = \"23542185131\", k = 3, minLength = 3) == 1\n assert candidate(s = \"3312958\", k = 3, minLength = 1) == 1\n\n\ncheck(Solution().beautifulPartitions)"}
196
112
coding
Solve the programming task below in a Python markdown code block. Giant chess is quite common in Geraldion. We will not delve into the rules of the game, we'll just say that the game takes place on an h × w field, and it is painted in two colors, but not like in chess. Almost all cells of the field are white and only some of them are black. Currently Gerald is finishing a game of giant chess against his friend Pollard. Gerald has almost won, and the only thing he needs to win is to bring the pawn from the upper left corner of the board, where it is now standing, to the lower right corner. Gerald is so confident of victory that he became interested, in how many ways can he win? The pawn, which Gerald has got left can go in two ways: one cell down or one cell to the right. In addition, it can not go to the black cells, otherwise the Gerald still loses. There are no other pawns or pieces left on the field, so that, according to the rules of giant chess Gerald moves his pawn until the game is over, and Pollard is just watching this process. Input The first line of the input contains three integers: h, w, n — the sides of the board and the number of black cells (1 ≤ h, w ≤ 105, 1 ≤ n ≤ 2000). Next n lines contain the description of black cells. The i-th of these lines contains numbers ri, ci (1 ≤ ri ≤ h, 1 ≤ ci ≤ w) — the number of the row and column of the i-th cell. It is guaranteed that the upper left and lower right cell are white and all cells in the description are distinct. Output Print a single line — the remainder of the number of ways to move Gerald's pawn from the upper left to the lower right corner modulo 109 + 7. Examples Input 3 4 2 2 2 2 3 Output 2 Input 100 100 3 15 16 16 15 99 88 Output 545732279
{"inputs": ["2 2 2\n2 1\n1 2\n", "3 4 2\n2 2\n2 4\n", "3 4 2\n3 2\n2 4\n", "3 7 2\n3 2\n2 4\n", "2 4 2\n2 2\n2 3\n", "3 4 2\n2 2\n2 3\n", "100000 100000 2\n1 2\n2 1\n", "100 100 3\n15 7\n16 15\n15 88\n"], "outputs": ["0\n", "2", "3", "9", "1", "2\n", "0\n", "950251154"]}
461
192
coding
Solve the programming task below in a Python markdown code block. For a permutation P of length N, we define L(P) to be the length of the longest increasing subsequence in P. That is, L(P) is the largest integer K such that there exist indices i_{1} < i_{2} < \ldots < i_{K} such that P_{i_{1}} < P_{i_{2}} < \ldots < P_{i_{K}}. Define P^{R} to be the permutation (P_{N}, P_{N-1}, \ldots, P_{1}). You are given a positive integer N. You need to output a permutation P of length N such that L(P) = L(P^{R}), or say that none exist. Note: P is said to be a permutation of length N if P is a sequence of length N consisting of N distinct integers between 1 and N. For example, (3, 1, 2) is a permutation of length 3, but (1, 4, 2), (2, 2, 3) and (2, 1) are not. ------ Input Format ------ - The first line of input contains a single integer T, denoting the number of test cases. The description of T test cases follows. - Each test case consists of a single line containing one integer N — the length of the permutation to be constructed. ------ Output Format ------ For each test case, output on a new line "YES" if there exists a valid permutation, and "NO" if there doesn't. If you outputted "YES", on the next line, output a valid permutation P as N space-separated integers, the i^{th} of which is P_{i}. You can print each letter of the string in any case (upper or lower) (for instance, strings YES, yEs, and yes will be considered identical). ------ Constraints ------ $1 ≤ T ≤ 1000$ $2 ≤ N ≤ 2 \cdot 10^{5}$ - The sum of $N$ across all test cases does not exceed $2 \cdot 10^{5}$ ----- Sample Input 1 ------ 2 2 3 ----- Sample Output 1 ------ NO YES 1 3 2 ----- explanation 1 ------ Test Case $1$: There are two permutations of length $2$ — $(1, 2)$ and $(2, 1)$. The length of the LIS of $(1, 2)$ is $2$ and the length of the LIS of $(2, 1)$ is $1$. Since these permutations are reverses of each other and have unequal LIS lengths, there is no valid permutation of length $2$. Test Case $2$: The length of the LIS of $(1, 3, 2)$ is $2$, and the length of the LIS of its reverse, $(2, 3, 1)$, is also $2$. Therefore, this is a valid permutation of length $3$.
{"inputs": ["2\n2\n3"], "outputs": ["NO\nYES\n1 3 2"]}
645
24
coding
Solve the programming task below in a Python markdown code block. Mountaineers Mr. Takahashi and Mr. Aoki recently trekked across a certain famous mountain range. The mountain range consists of N mountains, extending from west to east in a straight line as Mt. 1, Mt. 2, ..., Mt. N. Mr. Takahashi traversed the range from the west and Mr. Aoki from the east. The height of Mt. i is h_i, but they have forgotten the value of each h_i. Instead, for each i (1 ≤ i ≤ N), they recorded the maximum height of the mountains climbed up to the time they reached the peak of Mt. i (including Mt. i). Mr. Takahashi's record is T_i and Mr. Aoki's record is A_i. We know that the height of each mountain h_i is a positive integer. Compute the number of the possible sequences of the mountains' heights, modulo 10^9 + 7. Note that the records may be incorrect and thus there may be no possible sequence of the mountains' heights. In such a case, output 0. Constraints * 1 ≤ N ≤ 10^5 * 1 ≤ T_i ≤ 10^9 * 1 ≤ A_i ≤ 10^9 * T_i ≤ T_{i+1} (1 ≤ i ≤ N - 1) * A_i ≥ A_{i+1} (1 ≤ i ≤ N - 1) Input The input is given from Standard Input in the following format: N T_1 T_2 ... T_N A_1 A_2 ... A_N Output Print the number of possible sequences of the mountains' heights, modulo 10^9 + 7. Examples Input 5 1 3 3 3 3 3 3 2 2 2 Output 4 Input 5 1 1 1 2 2 3 2 1 1 1 Output 0 Input 10 1 3776 3776 8848 8848 8848 8848 8848 8848 8848 8848 8848 8848 8848 8848 8848 8848 8848 3776 5 Output 884111967 Input 1 17 17 Output 1
{"inputs": ["1\n17\n17", "5\n2 3 3 3 3\n3 3 2 2 2", "5\n1 1 1 2 2\n6 2 1 1 1", "5\n1 1 1 4 2\n6 2 1 1 1", "5\n1 1 1 4 2\n6 2 1 1 0", "5\n1 1 1 4 2\n6 0 1 1 0", "5\n1 1 1 4 2\n6 1 1 1 0", "5\n1 1 1 4 2\n6 2 1 2 0"], "outputs": ["1", "4\n", "0\n", "0\n", "0\n", "0\n", "0\n", "0\n"]}
562
207
coding
Solve the programming task below in a Python markdown code block. We have a tree with N vertices. The i-th edge connects Vertex A_i and B_i bidirectionally. Takahashi is standing at Vertex u, and Aoki is standing at Vertex v. Now, they will play a game of tag as follows: - 1. If Takahashi and Aoki are standing at the same vertex, the game ends. Otherwise, Takahashi moves to a vertex of his choice that is adjacent to his current vertex. - 2. If Takahashi and Aoki are standing at the same vertex, the game ends. Otherwise, Aoki moves to a vertex of his choice that is adjacent to his current vertex. - 3. Go back to step 1. Takahashi performs his moves so that the game ends as late as possible, while Aoki performs his moves so that the game ends as early as possible. Find the number of moves Aoki will perform before the end of the game if both Takahashi and Aoki know each other's position and strategy. It can be proved that the game is bound to end. -----Constraints----- - 2 \leq N \leq 10^5 - 1 \leq u,v \leq N - u \neq v - 1 \leq A_i,B_i \leq N - The given graph is a tree. -----Input----- Input is given from Standard Input in the following format: N u v A_1 B_1 : A_{N-1} B_{N-1} -----Output----- Print the number of moves Aoki will perform before the end of the game. -----Sample Input----- 5 4 1 1 2 2 3 3 4 3 5 -----Sample Output----- 2 If both players play optimally, the game will progress as follows: - Takahashi moves to Vertex 3. - Aoki moves to Vertex 2. - Takahashi moves to Vertex 5. - Aoki moves to Vertex 3. - Takahashi moves to Vertex 3. Here, Aoki performs two moves. Note that, in each move, it is prohibited to stay at the current vertex.
{"inputs": ["2 1 2\n1 2", "2 1 2\n1 2\n", "5 4 5\n1 2\n1 3\n2 4\n1 5", "5 4 1\n1 2\n1 3\n3 4\n3 5", "5 4 1\n1 2\n2 3\n1 4\n3 5", "5 4 5\n1 2\n1 5\n2 4\n1 5", "5 4 5\n2 2\n1 3\n1 4\n1 5", "5 5 1\n1 2\n2 3\n1 4\n3 5"], "outputs": ["0", "0\n", "2\n", "1\n", "0\n", "2\n", "1\n", "2\n"]}
473
198
coding
Solve the programming task below in a Python markdown code block. The only difference between the easy and the hard versions is the maximum value of $k$. You are given an infinite sequence of form "112123123412345$\dots$" which consist of blocks of all consecutive positive integers written one after another. The first block consists of all numbers from $1$ to $1$, the second one — from $1$ to $2$, the third one — from $1$ to $3$, $\dots$, the $i$-th block consists of all numbers from $1$ to $i$. So the first $56$ elements of the sequence are "11212312341234512345612345671234567812345678912345678910". Elements of the sequence are numbered from one. For example, the $1$-st element of the sequence is $1$, the $3$-rd element of the sequence is $2$, the $20$-th element of the sequence is $5$, the $38$-th element is $2$, the $56$-th element of the sequence is $0$. Your task is to answer $q$ independent queries. In the $i$-th query you are given one integer $k_i$. Calculate the digit at the position $k_i$ of the sequence. -----Input----- The first line of the input contains one integer $q$ ($1 \le q \le 500$) — the number of queries. The $i$-th of the following $q$ lines contains one integer $k_i$ $(1 \le k_i \le 10^{18})$ — the description of the corresponding query. -----Output----- Print $q$ lines. In the $i$-th line print one digit $x_i$ $(0 \le x_i \le 9)$ — the answer to the query $i$, i.e. $x_i$ should be equal to the element at the position $k_i$ of the sequence. -----Examples----- Input 5 1 3 20 38 56 Output 1 2 5 2 0 Input 4 2132 506 999999999999999999 1000000000000000000 Output 8 2 4 1 -----Note----- Answers on queries from the first example are described in the problem statement.
{"inputs": ["1\n9124\n", "1\n9124\n", "1\n3621\n", "1\n4320\n", "1\n2836\n", "1\n6961\n", "1\n3722\n", "1\n6297\n"], "outputs": ["4\n", "4\n", "1\n", "2\n", "7\n", "3\n", "5\n", "2\n"]}
587
110
coding
Solve the programming task below in a Python markdown code block. Our fruit guy has a bag of fruit (represented as an array of strings) where some fruits are rotten. He wants to replace all the rotten pieces of fruit with fresh ones. For example, given `["apple","rottenBanana","apple"]` the replaced array should be `["apple","banana","apple"]`. Your task is to implement a method that accepts an array of strings containing fruits should returns an array of strings where all the rotten fruits are replaced by good ones. ### Notes - If the array is null/nil/None or empty you should return empty array (`[]`). - The rotten fruit name will be in this camelcase (`rottenFruit`). - The returned array should be in lowercase. Also feel free to reuse/extend the following starter code: ```python def remove_rotten(bag_of_fruits): ```
{"functional": "_inputs = [[['apple', 'banana', 'kiwi', 'melone', 'orange']], [['rottenApple', 'rottenBanana', 'rottenApple', 'rottenPineapple', 'rottenKiwi']], [[]], [None], [['apple', 'rottenBanana', 'rottenApple', 'pineapple', 'kiwi']]]\n_outputs = [[['apple', 'banana', 'kiwi', 'melone', 'orange']], [['apple', 'banana', 'apple', 'pineapple', 'kiwi']], [[]], [[]], [['apple', 'banana', 'apple', 'pineapple', 'kiwi']]]\nimport math\ndef _deep_eq(a, b, tol=1e-5):\n if isinstance(a, float) or isinstance(b, float):\n return math.isclose(a, b, rel_tol=tol, abs_tol=tol)\n if isinstance(a, (list, tuple)):\n if len(a) != len(b): return False\n return all(_deep_eq(x, y, tol) for x, y in zip(a, b))\n return a == b\n\nfor i, o in zip(_inputs, _outputs):\n assert _deep_eq(remove_rotten(*i), o[0])"}
189
281
coding
Solve the programming task below in a Python markdown code block. Mihai has an $8 \times 8$ chessboard whose rows are numbered from $1$ to $8$ from top to bottom and whose columns are numbered from $1$ to $8$ from left to right. Mihai has placed exactly one bishop on the chessboard. The bishop is not placed on the edges of the board. (In other words, the row and column of the bishop are between $2$ and $7$, inclusive.) The bishop attacks in all directions diagonally, and there is no limit to the distance which the bishop can attack. Note that the cell on which the bishop is placed is also considered attacked. An example of a bishop on a chessboard. The squares it attacks are marked in red. Mihai has marked all squares the bishop attacks, but forgot where the bishop was! Help Mihai find the position of the bishop. -----Input----- The first line of the input contains a single integer $t$ ($1 \leq t \leq 36$) — the number of test cases. The description of test cases follows. There is an empty line before each test case. Each test case consists of $8$ lines, each containing $8$ characters. Each of these characters is either '#' or '.', denoting a square under attack and a square not under attack, respectively. -----Output----- For each test case, output two integers $r$ and $c$ ($2 \leq r, c \leq 7$) — the row and column of the bishop. The input is generated in such a way that there is always exactly one possible location of the bishop that is not on the edge of the board. -----Examples----- Input 3 .....#.. #...#... .#.#.... ..#..... .#.#.... #...#... .....#.. ......#. #.#..... .#...... #.#..... ...#.... ....#... .....#.. ......#. .......# .#.....# ..#...#. ...#.#.. ....#... ...#.#.. ..#...#. .#.....# #....... Output 4 3 2 2 4 5 -----Note----- The first test case is pictured in the statement. Since the bishop lies in the intersection row $4$ and column $3$, the correct output is 4 3.
{"inputs": ["3\n\n.....#..\n#...#...\n.#.#....\n..#.....\n.#.#....\n#...#...\n.....#..\n......#.\n\n#.#.....\n.#......\n#.#.....\n...#....\n....#...\n.....#..\n......#.\n.......#\n\n.#.....#\n..#...#.\n...#.#..\n....#...\n...#.#..\n..#...#.\n.#.....#\n#.......\n"], "outputs": ["4 3\n2 2\n4 5\n"]}
502
136
coding
Solve the programming task below in a Python markdown code block. Gerald is very particular to eight point sets. He thinks that any decent eight point set must consist of all pairwise intersections of three distinct integer vertical straight lines and three distinct integer horizontal straight lines, except for the average of these nine points. In other words, there must be three integers x_1, x_2, x_3 and three more integers y_1, y_2, y_3, such that x_1 < x_2 < x_3, y_1 < y_2 < y_3 and the eight point set consists of all points (x_{i}, y_{j}) (1 ≤ i, j ≤ 3), except for point (x_2, y_2). You have a set of eight points. Find out if Gerald can use this set? -----Input----- The input consists of eight lines, the i-th line contains two space-separated integers x_{i} and y_{i} (0 ≤ x_{i}, y_{i} ≤ 10^6). You do not have any other conditions for these points. -----Output----- In a single line print word "respectable", if the given set of points corresponds to Gerald's decency rules, and "ugly" otherwise. -----Examples----- Input 0 0 0 1 0 2 1 0 1 2 2 0 2 1 2 2 Output respectable Input 0 0 1 0 2 0 3 0 4 0 5 0 6 0 7 0 Output ugly Input 1 1 1 2 1 3 2 1 2 2 2 3 3 1 3 2 Output ugly
{"inputs": ["0 0\n0 1\n0 2\n1 0\n1 2\n2 0\n2 1\n2 2\n", "0 0\n1 0\n2 0\n3 0\n4 0\n5 0\n6 0\n7 0\n", "1 1\n1 2\n1 3\n2 1\n2 2\n2 3\n3 1\n3 2\n", "0 0\n0 0\n0 0\n0 0\n0 0\n0 0\n0 0\n0 0\n", "0 0\n1 0\n0 1\n1 1\n0 2\n1 2\n0 3\n1 3\n", "0 0\n2 1\n1 0\n0 2\n2 2\n1 0\n2 1\n0 2\n", "0 0\n2 1\n1 0\n0 2\n2 2\n1 0\n2 1\n0 2\n", "0 1\n0 1\n0 2\n1 1\n1 2\n2 1\n2 1\n2 2\n"], "outputs": ["respectable\n", "ugly\n", "ugly\n", "ugly\n", "ugly\n", "ugly\n", "ugly\n", "ugly\n"]}
388
318
coding
Solve the programming task below in a Python markdown code block. A hostel has N rooms in a straight line. It has to accommodate X people. Unfortunately, out of these X people, Y of them are infected with chickenpox. Due to safety norms, the following precaution must be taken: No person should occupy a room directly adjacent to a room occupied by a chickenpox-infected person. In particular, two chickenpox-infected people cannot occupy adjacent rooms. For example, if room 4 has a chickenpox-infected person, then nobody should occupy rooms 3 and 5. Similarly, if room 1 has a chickenpox-infected person then nobody should occupy room 2. What's the minimum value of N for which all the people can be accommodated in the hostel, following the above condition? ------ Input Format ------ - The first line of input contains a single integer T — the number of test cases. The description of T test cases follows. - The first and only line of each test case contains two integers X and Y — the total number of people and the number of chickenpox-infected people. ------ Output Format ------ For each test case, output on a new line a single integer — the minimum value of N for which all the people can be accommodated in the hostel. ------ Constraints ------ $1 ≤ T ≤ 200$ $1 ≤ X ≤ 1000$ $0 ≤ Y ≤ X$ ----- Sample Input 1 ------ 3 4 0 5 3 3 3 ----- Sample Output 1 ------ 4 8 5 ----- explanation 1 ------ Note: Below, $C$ represents a room occupied by a chickenpox-infected person, $N$ represents a room occupied by an uninfected person, and $\_$ represents an empty room. Test case $1$: One of the possible ways to accommodate the people in $4$ rooms is: $N$ $N$ $N$ $N$ Test case $2$: One of the possible ways to accommodate the people in $8$ rooms is: $C$ $\_$ $C$ $\_$ $N$ $N$ $\_$ $C$ Test case $3$: One of the possible ways to accommodate the people in $5$ rooms is: $C$ $\_$ $C$ $\_$ $C$
{"inputs": ["3\n4 0\n5 3\n3 3\n"], "outputs": ["4\n8\n5\n"]}
497
30
coding
Solve the programming task below in a Python markdown code block. Sereja showed an interesting game to his friends. The game goes like that. Initially, there is a table with an empty cup and n water mugs on it. Then all players take turns to move. During a move, a player takes a non-empty mug of water and pours all water from it into the cup. If the cup overfills, then we assume that this player lost. As soon as Sereja's friends heard of the game, they wanted to play it. Sereja, on the other hand, wanted to find out whether his friends can play the game in such a way that there are no losers. You are given the volumes of all mugs and the cup. Also, you know that Sereja has (n - 1) friends. Determine if Sereja's friends can play the game so that nobody loses. -----Input----- The first line contains integers n and s (2 ≤ n ≤ 100; 1 ≤ s ≤ 1000) — the number of mugs and the volume of the cup. The next line contains n integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10). Number a_{i} means the volume of the i-th mug. -----Output----- In a single line, print "YES" (without the quotes) if his friends can play in the described manner, and "NO" (without the quotes) otherwise. -----Examples----- Input 3 4 1 1 1 Output YES Input 3 4 3 1 3 Output YES Input 3 4 4 4 4 Output NO
{"inputs": ["2 4\n4 4\n", "2 1\n1 1\n", "2 1\n2 2\n", "2 1\n1 1\n", "2 4\n4 4\n", "2 1\n2 2\n", "2 1\n3 2\n", "2 1\n3 4\n"], "outputs": ["YES\n", "YES\n", "NO\n", "YES\n", "YES\n", "NO\n", "NO\n", "NO\n"]}
366
118
coding
Please solve the programming task below using a self-contained code snippet in a markdown code block. In English, we have a concept called root, which can be followed by some other word to form another longer word - let's call this word derivative. For example, when the root "help" is followed by the word "ful", we can form a derivative "helpful". Given a dictionary consisting of many roots and a sentence consisting of words separated by spaces, replace all the derivatives in the sentence with the root forming it. If a derivative can be replaced by more than one root, replace it with the root that has the shortest length. Return the sentence after the replacement.   Please complete the following python code precisely: ```python class Solution: def replaceWords(self, dictionary: List[str], sentence: str) -> str: ```
{"functional": "def check(candidate):\n assert candidate(dictionary = [\"cat\",\"bat\",\"rat\"], sentence = \"the cattle was rattled by the battery\") == \"the cat was rat by the bat\"\n assert candidate(dictionary = [\"a\",\"b\",\"c\"], sentence = \"aadsfasf absbs bbab cadsfafs\") == \"a a b c\"\n\n\ncheck(Solution().replaceWords)"}
169
94
coding
Solve the programming task below in a Python markdown code block. Dreamoon likes sequences very much. So he created a problem about the sequence that you can't find in OEIS: You are given two integers d, m, find the number of arrays a, satisfying the following constraints: * The length of a is n, n ≥ 1 * 1 ≤ a_1 < a_2 < ... < a_n ≤ d * Define an array b of length n as follows: b_1 = a_1, ∀ i > 1, b_i = b_{i - 1} ⊕ a_i, where ⊕ is the bitwise exclusive-or (xor). After constructing an array b, the constraint b_1 < b_2 < ... < b_{n - 1} < b_n should hold. Since the number of possible arrays may be too large, you need to find the answer modulo m. Input The first line contains an integer t (1 ≤ t ≤ 100) denoting the number of test cases in the input. Each of the next t lines contains two integers d, m (1 ≤ d, m ≤ 10^9). Note that m is not necessary the prime! Output For each test case, print the number of arrays a, satisfying all given constrains, modulo m. Example Input 10 1 1000000000 2 999999999 3 99999998 4 9999997 5 999996 6 99995 7 9994 8 993 9 92 10 1 Output 1 3 5 11 17 23 29 59 89 0
{"inputs": ["10\n1 1000000000\n2 146085669\n9 805629\n4 9999997\n5 999996\n6 99995\n9 18320\n8 993\n9 157\n7 2\n", "10\n1 1000000000\n2 999999999\n3 99999998\n4 9999997\n5 56682\n9 99995\n5 18320\n8 993\n9 92\n7 1\n", "10\n1 1000000000\n2 146085669\n6 805629\n4 9999997\n5 999996\n6 99995\n9 18320\n8 993\n9 157\n7 2\n", "10\n1 1000000000\n2 999999999\n3 99999998\n4 9999997\n5 56682\n6 99995\n5 18320\n8 993\n9 92\n7 1\n", "10\n1 1000000000\n2 999999999\n3 99999998\n4 9999997\n5 999996\n6 99995\n5 9994\n8 993\n9 92\n10 1\n", "10\n1 1000000000\n2 999999999\n3 99999998\n4 9999997\n5 999996\n6 99995\n9 18320\n8 993\n9 92\n7 1\n", "10\n1 1000000000\n2 999999999\n3 99999998\n4 9999997\n5 999996\n6 99995\n7 9994\n8 145\n9 92\n10 1\n", "10\n1 1000000000\n2 999999999\n3 99999998\n3 9999997\n5 999996\n6 99995\n9 18320\n8 993\n9 92\n7 1\n"], "outputs": ["1\n3\n89\n11\n17\n23\n89\n59\n89\n1\n", "1\n3\n5\n11\n17\n89\n17\n59\n89\n0\n", "1\n3\n23\n11\n17\n23\n89\n59\n89\n1\n", "1\n3\n5\n11\n17\n23\n17\n59\n89\n0\n", "1\n3\n5\n11\n17\n23\n17\n59\n89\n0\n", "1\n3\n5\n11\n17\n23\n89\n59\n89\n0\n", "1\n3\n5\n11\n17\n23\n29\n59\n89\n0\n", "1\n3\n5\n5\n17\n23\n89\n59\n89\n0\n"]}
404
955
coding
Solve the programming task below in a Python markdown code block. ## Problem There are `n` apples that need to be divided into four piles. We need two mysterious number `x` and `y`. Let The number of first pile equals to `x+y`, the number of second pile equals to `x-y`, the number of third pile equals to `x*y`, the number of fourth pile equals to `x/y`. We need to calculate how many apples are there in each pile. Of course, there won't be so many unknowns. We know the total number of apples(`n`) and the second mysterious number(`y`). For example: there are 48 apples need to divided into four piles. y=3. that is, 1st pile should be x+3, 2nd pile should be x-3, 3rd pile should be x*3, 4th pile should be x/3. Do you know how much `x` is? `x` should be 9, because: ``` (9 + 3) + (9 - 3) + (9 * 3) + (9 / 3) = 12 + 6 + 27 + 3 = 48 ``` So, 48 apples should be divided into `12, 6, 27, 3`. ## Task Complete function `fourPiles()`/`four_piles()` that accepts two arguments `n` and `y`, return an array contains the number of for piles. Each element in the result array should be a positive integer. If can not divide, please return `[]`. ## Examples ``` fourPiles 48 3 -- [12,6,27,3] //The elements are arranged in sequence according to: // x+y,x-y,x*y,x/y fourPiles 100 4 -- [20,12,64,4] -- Verify correctness: -- x=16,y=4 (16+4) + (16-4) + (16*4) + (16/4) -- 100 -- Edge case: fourPiles 25 4 -- [] -- [8,0,16,1] is not a correct answer fourPiles 24 4 -- [] -- can not divide ``` Also feel free to reuse/extend the following starter code: ```python def four_piles(n,y): ```
{"functional": "_inputs = [[48, 3], [100, 4], [25, 4], [24, 4]]\n_outputs = [[[12, 6, 27, 3]], [[20, 12, 64, 4]], [[]], [[]]]\nimport math\ndef _deep_eq(a, b, tol=1e-5):\n if isinstance(a, float) or isinstance(b, float):\n return math.isclose(a, b, rel_tol=tol, abs_tol=tol)\n if isinstance(a, (list, tuple)):\n if len(a) != len(b): return False\n return all(_deep_eq(x, y, tol) for x, y in zip(a, b))\n return a == b\n\nfor i, o in zip(_inputs, _outputs):\n assert _deep_eq(four_piles(*i), o[0])"}
539
212
coding
Solve the programming task below in a Python markdown code block. Hands that shed innocent blood! There are n guilty people in a line, the i-th of them holds a claw with length L_{i}. The bell rings and every person kills some of people in front of him. All people kill others at the same time. Namely, the i-th person kills the j-th person if and only if j < i and j ≥ i - L_{i}. You are given lengths of the claws. You need to find the total number of alive people after the bell rings. -----Input----- The first line contains one integer n (1 ≤ n ≤ 10^6) — the number of guilty people. Second line contains n space-separated integers L_1, L_2, ..., L_{n} (0 ≤ L_{i} ≤ 10^9), where L_{i} is the length of the i-th person's claw. -----Output----- Print one integer — the total number of alive people after the bell rings. -----Examples----- Input 4 0 1 0 10 Output 1 Input 2 0 0 Output 2 Input 10 1 1 3 0 0 0 2 1 0 3 Output 3 -----Note----- In first sample the last person kills everyone in front of him.
{"inputs": ["1\n0\n", "1\n1\n", "1\n1\n", "1\n0\n", "1\n2\n", "1\n3\n", "1\n4\n", "2\n0 0\n"], "outputs": ["1\n", "1\n", "1\n", "1\n", "1\n", "1\n", "1\n", "2\n"]}
291
88
coding
Please solve the programming task below using a self-contained code snippet in a markdown code block. You are given an n x n binary matrix grid. You are allowed to change at most one 0 to be 1. Return the size of the largest island in grid after applying this operation. An island is a 4-directionally connected group of 1s.   Please complete the following python code precisely: ```python class Solution: def largestIsland(self, grid: List[List[int]]) -> int: ```
{"functional": "def check(candidate):\n assert candidate(grid = [[1,0],[0,1]]) == 3\n assert candidate(grid = [[1,1],[1,0]]) == 4\n assert candidate(grid = [[1,1],[1,1]]) == 4\n\n\ncheck(Solution().largestIsland)"}
105
75
coding
Solve the programming task below in a Python markdown code block. Vasya came up with his own weather forecasting method. He knows the information about the average air temperature for each of the last n days. Assume that the average air temperature for each day is integral. Vasya believes that if the average temperatures over the last n days form an arithmetic progression, where the first term equals to the average temperature on the first day, the second term equals to the average temperature on the second day and so on, then the average temperature of the next (n + 1)-th day will be equal to the next term of the arithmetic progression. Otherwise, according to Vasya's method, the temperature of the (n + 1)-th day will be equal to the temperature of the n-th day. Your task is to help Vasya predict the average temperature for tomorrow, i. e. for the (n + 1)-th day. -----Input----- The first line contains a single integer n (2 ≤ n ≤ 100) — the number of days for which the average air temperature is known. The second line contains a sequence of integers t_1, t_2, ..., t_{n} ( - 1000 ≤ t_{i} ≤ 1000) — where t_{i} is the average temperature in the i-th day. -----Output----- Print the average air temperature in the (n + 1)-th day, which Vasya predicts according to his method. Note that the absolute value of the predicted temperature can exceed 1000. -----Examples----- Input 5 10 5 0 -5 -10 Output -15 Input 4 1 1 1 1 Output 1 Input 3 5 1 -5 Output -5 Input 2 900 1000 Output 1100 -----Note----- In the first example the sequence of the average temperatures is an arithmetic progression where the first term is 10 and each following terms decreases by 5. So the predicted average temperature for the sixth day is - 10 - 5 = - 15. In the second example the sequence of the average temperatures is an arithmetic progression where the first term is 1 and each following terms equals to the previous one. So the predicted average temperature in the fifth day is 1. In the third example the average temperatures do not form an arithmetic progression, so the average temperature of the fourth day equals to the temperature of the third day and equals to - 5. In the fourth example the sequence of the average temperatures is an arithmetic progression where the first term is 900 and each the following terms increase by 100. So predicted average temperature in the third day is 1000 + 100 = 1100.
{"inputs": ["2\n1 2\n", "2\n1 2\n", "2\n2 2\n", "2\n8 2\n", "2\n4 2\n", "2\n16 2\n", "3\n2 5 8\n", "3\n2 4 8\n"], "outputs": ["3\n", "3", "2\n", "-4\n", "0\n", "-12\n", "11\n", "8\n"]}
610
108
coding
Solve the programming task below in a Python markdown code block. Find out the maximum sub-array of non negative numbers from an array. The sub-array should be continuous. That is, a sub-array created by choosing the second and fourth element and skipping the third element is invalid. Maximum sub-array is defined in terms of the sum of the elements in the sub-array. Sub-array A is greater than sub-array B if sum(A) > sum(B). NOTE 1 :If there is a tie, then compare with segment's length and return segment which has maximum length NOTE 2: If there is still a tie, then return the segment with minimum starting index. -----Input----- The first line contains the number of test cases. Each test cases contains an integer N. next line consists of N integers, the elements of the array. -----Output----- Print out the maximum sub-array as stated above. -----Constraints----- - 1 ≤ T ≤ 100 - 1 ≤ N ≤ 105 - 1 ≤ Ai ≤ 105 -----Example----- Input: 1 6 1 2 5 -7 2 3 Output: 1 2 5
{"inputs": ["1\n6\n1 2 5 -7 2 3"], "outputs": ["1 2 5"]}
262
30
coding
Solve the programming task below in a Python markdown code block. Let's denote the $f(x)$ function for a string $x$ as the number of distinct characters that the string contains. For example $f({abc}) = 3$, $f({bbbbb}) = 1$, and $f({babacaba}) = 3$. Given a string $s$, split it into two non-empty strings $a$ and $b$ such that $f(a) + f(b)$ is the maximum possible. In other words, find the maximum possible value of $f(a) + f(b)$ such that $a + b = s$ (the concatenation of string $a$ and string $b$ is equal to string $s$). -----Input----- The input consists of multiple test cases. The first line contains an integer $t$ ($1 \leq t \leq 10^4$) — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $n$ ($2 \leq n \leq 2\cdot10^5$) — the length of the string $s$. The second line contains the string $s$, consisting of lowercase English letters. It is guaranteed that the sum of $n$ over all test cases does not exceed $2\cdot10^5$. -----Output----- For each test case, output a single integer — the maximum possible value of $f(a) + f(b)$ such that $a + b = s$. -----Examples----- Input 5 2 aa 7 abcabcd 5 aaaaa 10 paiumoment 4 aazz Output 2 7 2 10 3 -----Note----- For the first test case, there is only one valid way to split ${aa}$ into two non-empty strings ${a}$ and ${a}$, and $f({a}) + f({a}) = 1 + 1 = 2$. For the second test case, by splitting ${abcabcd}$ into ${abc}$ and ${abcd}$ we can get the answer of $f({abc}) + f({abcd}) = 3 + 4 = 7$ which is maximum possible. For the third test case, it doesn't matter how we split the string, the answer will always be $2$.
{"inputs": ["5\n2\naa\n7\nabcabcd\n5\naaaaa\n10\npaiumoment\n4\naazz\n"], "outputs": ["2\n7\n2\n10\n3\n"]}
505
49
coding
Solve the programming task below in a Python markdown code block. You are given the sequence of Nucleotides of one strand of DNA through a string S of length N. S contains the character A, T, C, and G only. Chef knows that: A is complementary to T. T is complementary to A. C is complementary to G. G is complementary to C. Using the string S, determine the sequence of the complementary strand of the DNA. ------ Input Format ------ - First line will contain T, number of test cases. Then the test cases follow. - First line of each test case contains an integer N - denoting the length of string S. - Second line contains N characters denoting the string S. ------ Output Format ------ For each test case, output the string containing N characters - sequence of nucleotides of the complementary strand. ------ Constraints ------ $1 ≤ T ≤ 100$ $1 ≤ N ≤ 100$ $S$ contains A, T, C, and G only ----- Sample Input 1 ------ 4 4 ATCG 4 GTCC 5 AAAAA 3 TAC ----- Sample Output 1 ------ TAGC CAGG TTTTT ATG ----- explanation 1 ------ Test case $1$: Based on the rules, the complements of A, T, C, and G are T, A, G, and C respectively. Thus, the complementary string of the given string ATCG is TAGC. Test case $2$: Based on the rules, the complements of G, T, and C are C, A, and G respectively. Thus, the complementary string of the given string GTCC is CAGG. Test case $3$: Based on the rules, the complement of A is T. Thus, the complementary string of the given string AAAAA is TTTTT. Test case $4$: Based on the rules, the complements of T, A, and C are A, T, and G respectively. Thus, the complementary string of the given string TAC is ATG.
{"inputs": ["4\n4\nATCG\n4\nGTCC\n5\nAAAAA\n3\nTAC\n"], "outputs": ["TAGC\nCAGG\nTTTTT\nATG\n"]}
440
46
coding
Please solve the programming task below using a self-contained code snippet in a markdown code block. Given a string s of lower and upper case English letters. A good string is a string which doesn't have two adjacent characters s[i] and s[i + 1] where: 0 <= i <= s.length - 2 s[i] is a lower-case letter and s[i + 1] is the same letter but in upper-case or vice-versa. To make the string good, you can choose two adjacent characters that make the string bad and remove them. You can keep doing this until the string becomes good. Return the string after making it good. The answer is guaranteed to be unique under the given constraints. Notice that an empty string is also good.   Please complete the following python code precisely: ```python class Solution: def makeGood(self, s: str) -> str: ```
{"functional": "def check(candidate):\n assert candidate(s = \"leEeetcode\") == \"leetcode\"\n assert candidate(s = \"abBAcC\") == \"\"\n assert candidate(s = \"s\") == \"s\"\n\n\ncheck(Solution().makeGood)"}
183
63
coding
Solve the programming task below in a Python markdown code block. Share price =========== You spent all your saved money to buy some shares. You bought it for `invested`, and want to know how much it's worth, but all the info you can quickly get are just the change the shares price made in percentages. Your task: ---------- Write the function `sharePrice()` that calculates, and returns the current price of your share, given the following two arguments: - `invested`(number), the amount of money you initially invested in the given share - `changes`(array of numbers), contains your shares daily movement percentages The returned number, should be in string format, and it's precision should be fixed at 2 decimal numbers. Have fun! >**Hint:** Try to write the function in a functional manner! Also feel free to reuse/extend the following starter code: ```python def share_price(invested, changes): ```
{"functional": "_inputs = [[100, []], [100, [-50, 50]], [100, [-50, 100]], [100, [-20, 30]], [1000, [0, 2, 3, 6]]]\n_outputs = [['100.00'], ['75.00'], ['100.00'], ['104.00'], ['1113.64']]\nimport math\ndef _deep_eq(a, b, tol=1e-5):\n if isinstance(a, float) or isinstance(b, float):\n return math.isclose(a, b, rel_tol=tol, abs_tol=tol)\n if isinstance(a, (list, tuple)):\n if len(a) != len(b): return False\n return all(_deep_eq(x, y, tol) for x, y in zip(a, b))\n return a == b\n\nfor i, o in zip(_inputs, _outputs):\n assert _deep_eq(share_price(*i), o[0])"}
194
254
coding
Solve the programming task below in a Python markdown code block. The `depth` of an integer `n` is defined to be how many multiples of `n` it is necessary to compute before all `10` digits have appeared at least once in some multiple. example: ``` let see n=42 Multiple value digits comment 42*1 42 2,4 42*2 84 8 4 existed 42*3 126 1,6 2 existed 42*4 168 - all existed 42*5 210 0 2,1 existed 42*6 252 5 2 existed 42*7 294 9 2,4 existed 42*8 336 3 6 existed 42*9 378 7 3,8 existed ``` Looking at the above table under `digits` column you can find all the digits from `0` to `9`, Hence it required `9` multiples of `42` to get all the digits. So the depth of `42` is `9`. Write a function named `computeDepth` which computes the depth of its integer argument.Only positive numbers greater than zero will be passed as an input. Also feel free to reuse/extend the following starter code: ```python def compute_depth(n): ```
{"functional": "_inputs = [[8], [13], [7], [25], [42], [1]]\n_outputs = [[12], [8], [10], [36], [9], [10]]\nimport math\ndef _deep_eq(a, b, tol=1e-5):\n if isinstance(a, float) or isinstance(b, float):\n return math.isclose(a, b, rel_tol=tol, abs_tol=tol)\n if isinstance(a, (list, tuple)):\n if len(a) != len(b): return False\n return all(_deep_eq(x, y, tol) for x, y in zip(a, b))\n return a == b\n\nfor i, o in zip(_inputs, _outputs):\n assert _deep_eq(compute_depth(*i), o[0])"}
337
192
coding
Solve the programming task below in a Python markdown code block. ## Your Story "A *piano* in the home meant something." - *Fried Green Tomatoes at the Whistle Stop Cafe* You've just realized a childhood dream by getting a beautiful and beautiful-sounding upright piano from a friend who was leaving the country. You immediately started doing things like playing "Heart and Soul" over and over again, using one finger to pick out any melody that came into your head, requesting some sheet music books from the library, signing up for some MOOCs like Developing Your Musicianship, and wondering if you will think of any good ideas for writing piano-related katas and apps. Now you're doing an exercise where you play the very first (leftmost, lowest in pitch) key on the 88-key keyboard, which (as shown below) is white, with the little finger on your left hand, then the second key, which is black, with the ring finger on your left hand, then the third key, which is white, with the middle finger on your left hand, then the fourth key, also white, with your left index finger, and then the fifth key, which is black, with your left thumb. Then you play the sixth key, which is white, with your right thumb, and continue on playing the seventh, eighth, ninth, and tenth keys with the other four fingers of your right hand. Then for the eleventh key you go back to your left little finger, and so on. Once you get to the rightmost/highest, 88th, key, you start all over again with your left little finger on the first key. Your thought is that this will help you to learn to move smoothly and with uniform pressure on the keys from each finger to the next and back and forth between hands. You're not saying the names of the notes while you're doing this, but instead just counting each key press out loud (not starting again at 1 after 88, but continuing on to 89 and so forth) to try to keep a steady rhythm going and to see how far you can get before messing up. You move gracefully and with flourishes, and between screwups you hear, see, and feel that you are part of some great repeating progression between low and high notes and black and white keys. ## Your Function The function you are going to write is not actually going to help you with your piano playing, but just explore one of the patterns you're experiencing: Given the number you stopped on, was it on a black key or a white key? For example, in the description of your piano exercise above, if you stopped at 5, your left thumb would be on the fifth key of the piano, which is black. Or if you stopped at 92, you would have gone all the way from keys 1 to 88 and then wrapped around, so that you would be on the fourth key, which is white. Your function will receive an integer between 1 and 10000 (maybe you think that in principle it would be cool to count up to, say, a billion, but considering how many years it would take it is just not possible) and return the string "black" or "white" -- here are a few more examples: ``` 1 "white" 12 "black" 42 "white" 100 "black" 2017 "white" ``` Have fun! And if you enjoy this kata, check out the sequel: Piano Kata, Part 2 Also feel free to reuse/extend the following starter code: ```python def black_or_white_key(key_press_count): ```
{"functional": "_inputs = [[1], [5], [12], [42], [88], [89], [92], [100], [111], [200], [2017]]\n_outputs = [['white'], ['black'], ['black'], ['white'], ['white'], ['white'], ['white'], ['black'], ['white'], ['black'], ['white']]\nimport math\ndef _deep_eq(a, b, tol=1e-5):\n if isinstance(a, float) or isinstance(b, float):\n return math.isclose(a, b, rel_tol=tol, abs_tol=tol)\n if isinstance(a, (list, tuple)):\n if len(a) != len(b): return False\n return all(_deep_eq(x, y, tol) for x, y in zip(a, b))\n return a == b\n\nfor i, o in zip(_inputs, _outputs):\n assert _deep_eq(black_or_white_key(*i), o[0])"}
769
231
coding
Solve the programming task below in a Python markdown code block. Madoka wants to enter to "Novosibirsk State University", but in the entrance exam she came across a very difficult task: Given an integer $n$, it is required to calculate $\sum{\operatorname{lcm}(c, \gcd(a, b))}$, for all triples of positive integers $(a, b, c)$, where $a + b + c = n$. In this problem $\gcd(x, y)$ denotes the greatest common divisor of $x$ and $y$, and $\operatorname{lcm}(x, y)$ denotes the least common multiple of $x$ and $y$. Solve this problem for Madoka and help her to enter to the best university! -----Input----- The first and the only line contains a single integer $n$ ($3 \le n \le 10^5$). -----Output----- Print exactly one interger — $\sum{\operatorname{lcm}(c, \gcd(a, b))}$. Since the answer can be very large, then output it modulo $10^9 + 7$. -----Examples----- Input 3 Output 1 Input 5 Output 11 Input 69228 Output 778304278 -----Note----- In the first example, there is only one suitable triple $(1, 1, 1)$. So the answer is $\operatorname{lcm}(1, \gcd(1, 1)) = \operatorname{lcm}(1, 1) = 1$. In the second example, $\operatorname{lcm}(1, \gcd(3, 1)) + \operatorname{lcm}(1, \gcd(2, 2)) + \operatorname{lcm}(1, \gcd(1, 3)) + \operatorname{lcm}(2, \gcd(2, 1)) + \operatorname{lcm}(2, \gcd(1, 2)) + \operatorname{lcm}(3, \gcd(1, 1)) = \operatorname{lcm}(1, 1) + \operatorname{lcm}(1, 2) + \operatorname{lcm}(1, 1) + \operatorname{lcm}(2, 1) + \operatorname{lcm}(2, 1) + \operatorname{lcm}(3, 1) = 1 + 2 + 1 + 2 + 2 + 3 = 11$
{"inputs": ["3\n", "5\n", "4\n", "6\n", "7\n", "8\n", "9\n", "47\n"], "outputs": ["1\n", "11\n", "4\n", "20\n", "42\n", "60\n", "100\n", "32596\n"]}
539
81
coding
Solve the programming task below in a Python markdown code block. Joisino is about to compete in the final round of a certain programming competition. In this contest, there are N problems, numbered 1 through N. Joisino knows that it takes her T_i seconds to solve problem i(1≦i≦N). Also, there are M kinds of drinks offered to the contestants, numbered 1 through M. If Joisino takes drink i(1≦i≦M), her brain will be stimulated and the time it takes for her to solve problem P_i will become X_i seconds. It does not affect the time to solve the other problems. A contestant is allowed to take exactly one of the drinks before the start of the contest. For each drink, Joisino wants to know how many seconds it takes her to solve all the problems if she takes that drink. Here, assume that the time it takes her to solve all the problems is equal to the sum of the time it takes for her to solve individual problems. Your task is to write a program to calculate it instead of her. -----Constraints----- - All input values are integers. - 1≦N≦100 - 1≦T_i≦10^5 - 1≦M≦100 - 1≦P_i≦N - 1≦X_i≦10^5 -----Input----- The input is given from Standard Input in the following format: N T_1 T_2 ... T_N M P_1 X_1 P_2 X_2 : P_M X_M -----Output----- For each drink, calculate how many seconds it takes Joisino to solve all the problems if she takes that drink, and print the results, one per line. -----Sample Input----- 3 2 1 4 2 1 1 2 3 -----Sample Output----- 6 9 If Joisino takes drink 1, the time it takes her to solve each problem will be 1, 1 and 4 seconds, respectively, totaling 6 seconds. If Joisino takes drink 2, the time it takes her to solve each problem will be 2, 3 and 4 seconds, respectively, totaling 9 seconds.
{"inputs": ["3\n2 1 4\n2\n1 1\n0 3", "3\n2 1 4\n2\n1 1\n0 6", "3\n2 1 4\n2\n1 0\n2 3", "3\n2 1 4\n2\n1 0\n0 3", "3\n1 1 4\n2\n1 1\n0 6", "3\n2 0 4\n2\n1 0\n0 3", "3\n1 1 0\n2\n1 1\n0 6", "3\n1 1 0\n2\n1 1\n0 8"], "outputs": ["6\n6\n", "6\n9\n", "5\n9\n", "5\n6\n", "6\n8\n", "4\n5\n", "2\n8\n", "2\n10\n"]}
477
207
coding
Solve the programming task below in a Python markdown code block. You are teaching students to generate strings consisting of unique lowercase latin characters (a-z). You give an example reference string $s$ to the students. You notice that your students just copy paste the reference string instead of creating their own string. So, you tweak the requirements for strings submitted by the students. Let us define a function F(s, t) where s and t are strings as the number of characters that are same in both the strings. Note that the position doesn't matter. Here are a few examples of F(s, t): F("abc", "def") = 0 F("abc", "acb") = 3 F("back", "abcd") = 3 Now you ask your students to output a string t with lowercase unique characters of the same length as $s$, such that F(s, t) $\leq k$ where you are also given the value of $k$. If there are multiple such strings, you ask them to output the lexicographically smallest possible string. If no such string is possible, output the string "NOPE" without quotes. -----Input:----- - The first line will contain $T$, the number of testcases. Then the testcases follow. - Each testcase contains of a single line of input, which contains a string $s$ and an integer $k$. -----Output:----- For each testcase, output in a single line the lexicographically smallest string t such that F(s, t) <= k or "NOPE" without quotes if no such string exists. -----Constraints----- - $1 \leq T \leq 10000$ - $1 \leq $length of string s $(|s|) \leq 26$ - $s$ only consists of characters $a$ to $z$ - There are no repeating characters in s - $0 \leq k \leq |s|$ -----Sample Input:----- 4 helowrd 0 background 0 abcdefghijklmnopqrstuvwxyz 0 b 1 -----Sample Output:----- abcfgij efhijlmpqs NOPE a
{"inputs": ["4\nhelowrd 0\nbackground 0\nabcdefghijklmnopqrstuvwxyz 0\nb 1"], "outputs": ["abcfgij\nefhijlmpqs\nNOPE\na"]}
456
44
coding
Solve the programming task below in a Python markdown code block. [BasE91](http://base91.sourceforge.net/) is a method for encoding binary as ASCII characters. It is more efficient than Base64 and needs 91 characters to represent the encoded data. The following ASCII charakters are used: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789' '!#$%&()*+,./:;<=>?@[]^_`{|}~"' Create two functions that encode strings to basE91 string and decodes the other way round. b91encode('test') = 'fPNKd' b91decode('fPNKd') = 'test' b91decode('>OwJh>Io0Tv!8PE') = 'Hello World!' b91encode('Hello World!') = '>OwJh>Io0Tv!8PE' Input strings are valid. Also feel free to reuse/extend the following starter code: ```python def b91decode(strng): ```
{"functional": "_inputs = [['fPNKd'], ['>OwJh>Io0Tv!8PE']]\n_outputs = [['test'], ['Hello World!']]\nimport math\ndef _deep_eq(a, b, tol=1e-5):\n if isinstance(a, float) or isinstance(b, float):\n return math.isclose(a, b, rel_tol=tol, abs_tol=tol)\n if isinstance(a, (list, tuple)):\n if len(a) != len(b): return False\n return all(_deep_eq(x, y, tol) for x, y in zip(a, b))\n return a == b\n\nfor i, o in zip(_inputs, _outputs):\n assert _deep_eq(b91decode(*i), o[0])"}
232
178
coding
Please solve the programming task below using a self-contained code snippet in a markdown code block. You are climbing a staircase. It takes n steps to reach the top. Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?   Please complete the following python code precisely: ```python class Solution: def climbStairs(self, n: int) -> int: ```
{"functional": "def check(candidate):\n assert candidate(n = 2) == 2\n assert candidate(n = 3) == 3\n\n\ncheck(Solution().climbStairs)"}
88
45
coding
Solve the programming task below in a Python markdown code block. You are given an array $a_{1}, a_{2}, \ldots, a_{n}$. You can remove at most one subsegment from it. The remaining elements should be pairwise distinct. In other words, at most one time you can choose two integers $l$ and $r$ ($1 \leq l \leq r \leq n$) and delete integers $a_l, a_{l+1}, \ldots, a_r$ from the array. Remaining elements should be pairwise distinct. Find the minimum size of the subsegment you need to remove to make all remaining elements distinct. -----Input----- The first line of the input contains a single integer $n$ ($1 \le n \le 2000$) — the number of elements in the given array. The next line contains $n$ spaced integers $a_{1}, a_{2}, \ldots, a_{n}$ ($1 \le a_{i} \le 10^{9}$) — the elements of the array. -----Output----- Print a single integer — the minimum size of the subsegment you need to remove to make all elements of the array pairwise distinct. If no subsegment needs to be removed, print $0$. -----Examples----- Input 3 1 2 3 Output 0 Input 4 1 1 2 2 Output 2 Input 5 1 4 1 4 9 Output 2 -----Note----- In the first example all the elements are already distinct, therefore no subsegment needs to be removed. In the second example you can remove the subsegment from index $2$ to $3$. In the third example you can remove the subsegments from index $1$ to $2$, or from index $2$ to $3$, or from index $3$ to $4$.
{"inputs": ["2\n2 1\n", "2\n2 1\n", "2\n3 1\n", "2\n6 1\n", "3\n1 2 3\n", "3\n1 2 1\n", "3\n1 2 0\n", "3\n1 2 3\n"], "outputs": ["0\n", "0", "0\n", "0\n", "0\n", "1\n", "0\n", "0"]}
412
108
coding
Solve the programming task below in a Python markdown code block. You are given two integers $n$ and $k$. Your task is to find if $n$ can be represented as a sum of $k$ distinct positive odd (not divisible by $2$) integers or not. You have to answer $t$ independent test cases. -----Input----- The first line of the input contains one integer $t$ ($1 \le t \le 10^5$) — the number of test cases. The next $t$ lines describe test cases. The only line of the test case contains two integers $n$ and $k$ ($1 \le n, k \le 10^7$). -----Output----- For each test case, print the answer — "YES" (without quotes) if $n$ can be represented as a sum of $k$ distinct positive odd (not divisible by $2$) integers and "NO" otherwise. -----Example----- Input 6 3 1 4 2 10 3 10 2 16 4 16 5 Output YES YES NO YES YES NO -----Note----- In the first test case, you can represent $3$ as $3$. In the second test case, the only way to represent $4$ is $1+3$. In the third test case, you cannot represent $10$ as the sum of three distinct positive odd integers. In the fourth test case, you can represent $10$ as $3+7$, for example. In the fifth test case, you can represent $16$ as $1+3+5+7$. In the sixth test case, you cannot represent $16$ as the sum of five distinct positive odd integers.
{"inputs": ["1\n707 44\n", "1\n2 65536\n", "1\n2 65536\n", "1\n2 15317\n", "1\n3 15317\n", "1\n1 15317\n", "1\n0 15317\n", "1\n0 26405\n"], "outputs": ["NO\n", "NO\n", "NO\n", "NO\n", "NO\n", "NO\n", "NO\n", "NO\n"]}
382
133