task_type
stringclasses
1 value
problem
stringlengths
209
3.39k
answer
stringlengths
35
6.15k
problem_tokens
int64
60
774
answer_tokens
int64
12
2.04k
coding
Solve the programming task below in a Python markdown code block. Write a comparator for a list of phonetic words for the letters of the [greek alphabet](https://en.wikipedia.org/wiki/Greek_alphabet). A comparator is: > *a custom comparison function of two arguments (iterable elements) which should return a negative, zero or positive number depending on whether the first argument is considered smaller than, equal to, or larger than the second argument* *(source: https://docs.python.org/2/library/functions.html#sorted)* The greek alphabet is preloded for you as `greek_alphabet`: ```python greek_alphabet = ( 'alpha', 'beta', 'gamma', 'delta', 'epsilon', 'zeta', 'eta', 'theta', 'iota', 'kappa', 'lambda', 'mu', 'nu', 'xi', 'omicron', 'pi', 'rho', 'sigma', 'tau', 'upsilon', 'phi', 'chi', 'psi', 'omega') ``` ## Examples ```python greek_comparator('alpha', 'beta') < 0 greek_comparator('psi', 'psi') == 0 greek_comparator('upsilon', 'rho') > 0 ``` Also feel free to reuse/extend the following starter code: ```python def greek_comparator(lhs, rhs): ```
{"functional": "_inputs = [['chi', 'chi']]\n_outputs = [[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(greek_comparator(*i), o[0])"}
303
159
coding
Solve the programming task below in a Python markdown code block. To participate in a prize draw each one gives his/her firstname. Each letter of a firstname has a value which is its rank in the English alphabet. `A` and `a` have rank `1`, `B` and `b` rank `2` and so on. The *length* of the firstname is added to the *sum* of these ranks hence a number `som`. An array of random weights is linked to the firstnames and each `som` is multiplied by its corresponding weight to get what they call a `winning number`. Example: ``` names: "COLIN,AMANDBA,AMANDAB,CAROL,PauL,JOSEPH" weights: [1, 4, 4, 5, 2, 1] PauL -> som = length of firstname + 16 + 1 + 21 + 12 = 4 + 50 -> 54 The *weight* associated with PauL is 2 so PauL's *winning number* is 54 * 2 = 108. ``` Now one can sort the firstnames in decreasing order of the `winning numbers`. When two people have the same `winning number` sort them *alphabetically* by their firstnames. ### Task: - parameters: `st` a string of firstnames, `we` an array of weights, `n` a rank - return: the firstname of the participant whose rank is `n` (ranks are numbered from 1) ### Example: ``` names: "COLIN,AMANDBA,AMANDAB,CAROL,PauL,JOSEPH" weights: [1, 4, 4, 5, 2, 1] n: 4 The function should return: "PauL" ``` # Notes: - The weight array is at least as long as the number of names, it can be longer. - If `st` is empty return "No participants". - If n is greater than the number of participants then return "Not enough participants". - See Examples Test Cases for more examples. Also feel free to reuse/extend the following starter code: ```python def rank(st, we, n): ```
{"functional": "_inputs = [['Addison,Jayden,Sofia,Michael,Andrew,Lily,Benjamin', [4, 2, 1, 4, 3, 1, 2], 4], ['Elijah,Chloe,Elizabeth,Matthew,Natalie,Jayden', [1, 3, 5, 5, 3, 6], 2], ['Aubrey,Olivai,Abigail,Chloe,Andrew,Elizabeth', [3, 1, 4, 4, 3, 2], 4], ['Lagon,Lily', [1, 5], 2], ['Elijah,Michael,Avery,Sophia,Samantha', [2, 1, 5, 2, 2], 3], ['William,Willaim,Olivia,Olivai,Lily,Lyli', [1, 1, 1, 1, 1, 1], 1], ['Addison,Jayden,Sofia,Michael,Andrew,Lily,Benjamin', [4, 2, 1, 4, 3, 1, 2], 8], ['', [4, 2, 1, 4, 3, 1, 2], 6], ['Addison,William,Jayden', [3, 5, 6], 1], ['Joshua,Grace,Isabella', [1, 5, 4], 1], ['Elijah,Addison', [3, 6], 2], ['Willaim,Liam,Daniel,Alexander', [6, 4, 6, 2], 2], ['Avery,Olivai,Sophia,Michael,Elizabeth,Willaim,Liam', [5, 5, 3, 2, 1, 3, 6], 5], ['Liam,Madison,Lyli,Jacob,Matthew,Michael', [2, 6, 5, 5, 3, 4], 6], ['Sophia,Robert,Abigail,Grace,Lagon', [1, 2, 2, 6, 4], 5], ['Samantha,Ella', [5, 6], 1], ['Aubrey,Jayden', [3, 4], 2], ['Jacob,Elijah', [4, 3], 1]]\n_outputs = [['Benjamin'], ['Matthew'], ['Abigail'], ['Lagon'], ['Sophia'], ['Willaim'], ['Not enough participants'], ['No participants'], ['William'], ['Isabella'], ['Elijah'], ['Daniel'], ['Sophia'], ['Liam'], ['Sophia'], ['Samantha'], ['Aubrey'], ['Elijah']]\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(rank(*i), o[0])"}
497
734
coding
Solve the programming task below in a Python markdown code block. Ganesh lives in Gopalmath. He is looking for Jojo. So he decides to collect Aadhar Card Information of all the citizens of India from UIDAI. Someone told Ganesh that the sum of all the digits of Jojo’s Aadhar number is divisible by 10 and it is greater than zero. After finding all Aadhar numbers which are divisible by 10, Jojo’s Aadhar number is $N$th smallest Aadhar number. Hence, Ganesh wants to find Jojo’s Aadhar number which satisfies all of the above conditions. (In this chaotic world, Aadhar numbers can be any natural number.) However, Guruji refused Ganesh to carry out this task, because he is weak in Maths. Therefore, Ganesh assigns this task to Paritoshbhai who possesses excellent Mathematical skills. Since Paritoshbhai is busy in his jewellery business, help him in this task. -----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 and only line of each test case contains a single integer N. -----Output:----- For each test case, print a single line containing Aadhar number of Jojo. -----Constraints----- - $1 \leq T \leq 1000$ - $1 \leq N \leq 10^{100,000}$ -----Sample Input:----- 1 3 -----Sample Output:----- 37
{"inputs": ["1\n3"], "outputs": ["37"]}
332
15
coding
Please solve the programming task below using a self-contained code snippet in a markdown code block. Winston was given the above mysterious function func. He has an integer array arr and an integer target and he wants to find the values l and r that make the value |func(arr, l, r) - target| minimum possible. Return the minimum possible value of |func(arr, l, r) - target|. Notice that func should be called with the values l and r where 0 <= l, r < arr.length.   Please complete the following python code precisely: ```python class Solution: def closestToTarget(self, arr: List[int], target: int) -> int: ```
{"functional": "def check(candidate):\n assert candidate(arr = [9,12,3,7,15], target = 5) == 2\n assert candidate(arr = [1000000,1000000,1000000], target = 1) == 999999\n assert candidate(arr = [1,2,4,8,16], target = 0) == 0\n\n\ncheck(Solution().closestToTarget)"}
141
117
coding
Solve the programming task below in a Python markdown code block. Our hardworking chef is bored of sleeping in his restaurants. He has decided to settle down. The first thing he must do is to find a suitable location to build a palatial home. Think of the city as a two-dimensional grid. There are N restaurants in the city. Each of the chef's restaurant is a point denoted by (X , Y). A house can be located at a grid point (R, S) if the sum of the distances between this point and each of the restaurants is as small as possible. Find the number of possible house locations in the city to help out chef build a home. More than one restaurant can be located at the same point. Houses and restaurants can be located at the same point. Every house must have integer co-ordinates. In other words, R and S are integers. The distance between two points (A,B) and (C,D) is |A-C| + |B-D|. Here |X| is the absolute function. ------ Input ------ First line in the input contains T, number of test cases. First line of each test case contains N, number of restaurants. Each of the next N lines contain two integers X and Y separated by a space. T ≤ 100 N ≤ 10^{3} -10^{8} ≤ X ≤10^{8} -10^{8} ≤ Y ≤10^{8} ------ Output ------ The number of possible locations (grid points) where houses can be built. ----- Sample Input 1 ------ 3 5 0 0 -1 0 1 0 0 1 0 -1 5 31 11 30 -41 20 14 25 18 25 38 2 0 0 1 1 ----- Sample Output 1 ------ 1 1 4
{"inputs": ["3\n5\n0 0\n0 0\n1 0\n0 1\n0 -1\n5\n31 3\n30 -6\n20 15\n25 18\n25 38\n1\n0 0\n1 1", "3\n5\n0 0\n0 0\n1 0\n0 1\n0 -1\n5\n31 5\n30 -6\n20 15\n25 18\n25 38\n1\n0 0\n1 1", "3\n5\n0 0\n-1 0\n1 0\n0 1\n0 -1\n5\n4 7\n30 -41\n20 8\n26 18\n25 38\n2\n0 0\n1 1", "3\n5\n0 0\n0 0\n1 0\n0 1\n0 -1\n5\n31 5\n30 -6\n26 15\n25 18\n25 38\n1\n0 0\n1 1", "3\n5\n0 0\n-1 0\n1 0\n0 1\n0 -1\n5\n4 7\n30 -41\n20 8\n26 18\n25 58\n2\n0 0\n1 1", "3\n5\n0 0\n-1 0\n1 0\n1 1\n0 -1\n5\n4 7\n30 -41\n20 8\n26 18\n25 58\n2\n0 0\n1 1", "3\n5\n0 0\n0 0\n1 0\n0 1\n0 -1\n5\n31 3\n30 -41\n20 15\n25 18\n25 38\n1\n0 0\n1 1", "3\n5\n0 -1\n0 0\n0 0\n0 1\n0 -1\n5\n31 8\n52 -41\n27 1\n25 9\n27 60\n2\n-1 0\n1 4"], "outputs": ["1\n1\n1\n", "1\n1\n1\n", "1\n1\n4\n", "1\n1\n1\n", "1\n1\n4\n", "1\n1\n4\n", "1\n1\n1\n", "1\n1\n15\n"]}
423
592
coding
Solve the programming task below in a Python markdown code block. A permutation is a sequence of integers from 1 to n of length n containing each number exactly once. For example, (1), (4, 3, 5, 1, 2), (3, 2, 1) are permutations, and (1, 1), (4, 3, 1), (2, 3, 4) are not. There are many tasks on permutations. Today you are going to solve one of them. Let’s imagine that somebody took several permutations (perhaps, with a different number of elements), wrote them down consecutively as one array and then shuffled the resulting array. The task is to restore the initial permutations if it is possible. Input The first line contains an integer n (1 ≤ n ≤ 105). The next line contains the mixed array of n integers, divided with a single space. The numbers in the array are from 1 to 105. Output If this array can be split into several permutations so that every element of the array belongs to exactly one permutation, print in the first line the number of permutations. The second line should contain n numbers, corresponding to the elements of the given array. If the i-th element belongs to the first permutation, the i-th number should be 1, if it belongs to the second one, then its number should be 2 and so on. The order of the permutations’ numbering is free. If several solutions are possible, print any one of them. If there’s no solution, print in the first line - 1. Examples Input 9 1 2 3 1 2 1 4 2 5 Output 3 3 1 2 1 2 2 2 3 2 Input 4 4 3 2 1 Output 1 1 1 1 1 Input 4 1 2 2 3 Output -1 Note In the first sample test the array is split into three permutations: (2, 1), (3, 2, 1, 4, 5), (1, 2). The first permutation is formed by the second and the fourth elements of the array, the second one — by the third, the fifth, the sixth, the seventh and the ninth elements, the third one — by the first and the eigth elements. Clearly, there are other splitting variants possible.
{"inputs": ["1\n1\n", "1\n2\n", "1\n3\n", "1\n5\n", "1\n4\n", "1\n6\n", "3\n2 1 1\n", "3\n4 1 1\n"], "outputs": ["1\n1 ", "-1", "-1\n", "-1\n", "-1\n", "-1\n", "2\n1 1 2 ", "-1\n"]}
527
99
coding
Solve the programming task below in a Python markdown code block. Read problems statements in [Russian] and [Bengali]. Chef opened a company which manufactures cars and bikes. Each car requires 4 tyres while each bike requires 2 tyres. Chef has a total of N tyres (N is even). He wants to manufacture maximum number of cars from these tyres and then manufacture bikes from the remaining tyres. Chef's friend went to Chef to purchase a bike. If Chef's company has manufactured even a single bike then Chef's friend will be able to purchase it. Determine whether he will be able to purchase the bike or not. ------ Input Format ------ - The first line contains an integer T denoting the number of test cases. The T test cases then follow. - The first line of each test case contains an integer N denoting the number of tyres. ------ Output Format ------ For each test case, output YES or NO depending on whether Chef's friend will be able to purchase the bike or not. Output is case insensitive. ------ Constraints ------ $1 ≤ T ≤ 100$ $2 ≤ N ≤ 1000$ $N$ is even ----- Sample Input 1 ------ 3 8 2 6 ----- Sample Output 1 ------ NO YES YES ----- explanation 1 ------ - For the first test case Chef, will manufacture $2$ cars and will thus use all the $8$ tyres and thus could not manufacture any bike. - For the second test case, Chef cannot manufacture any car since there are not enough tyres and will thus manufacture only a single bike which will be purchased by Chef's friend. - For the third test case, Chef will manufacture $1$ car and thus use $4$ tyres. From the remaining $2$ tyres, Chef can manufacture a single bike which will be purchased by Chef's friend.
{"inputs": ["3\n8\n2\n6\n"], "outputs": ["NO\nYES\nYES"]}
387
23
coding
Solve the programming task below in a Python markdown code block. Chef has two integers A and B. Chef wants to find the minimum value of \texttt{lcm}(A, X) - \texttt{gcd}(B, X) where X is any positive integer. Help him determine this value. Note: \texttt{gcd}(P, Q) denotes the [greatest common divisor] of P and Q and \texttt{lcm}(P, Q) denotes the [least common multiple] of P and Q. ------ 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 two space-separated integers A and B — the integers mentioned in the statement. ------ Output Format ------ For each test case, output the minimum value of \texttt{lcm}(A, X) - \texttt{gcd}(B, X). ------ Constraints ------ $1 ≤ T ≤ 10^{5}$ $1 ≤A, B ≤10^{9}$ ----- Sample Input 1 ------ 3 12 15 5 50 9 11 ----- Sample Output 1 ------ 9 0 8 ----- explanation 1 ------ Test case $1$: For $X = 6$: $\texttt{lcm}(12, 6) - \texttt{gcd}(15, 6) = 12 - 3 = 9$ which is the minimum value required. Test case $2$: For $X = 50$: $\texttt{lcm}(5, 50) - \texttt{gcd}(50, 50) = 50 - 50 = 0$ which is the minimum value required. Test case $3$: For $X = 1$: $\texttt{lcm}(9, 1) - \texttt{gcd}(11, 1) = 9 - 1 = 8$ which is the minimum value required.
{"inputs": ["3\n12 15\n5 50\n9 11\n"], "outputs": ["9\n0\n8\n"]}
439
34
coding
Solve the programming task below in a Python markdown code block. A string with length $L$ is called rich if $L \ge 3$ and there is a character which occurs in this string strictly more than $L/2$ times. You are given a string $S$ and you should answer $Q$ queries on this string. In each query, you are given a substring $S_L, S_{L+1}, \ldots, S_R$. Consider all substrings of this substring. You have to determine whether at least one of them is rich. -----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 two space-separated integers $N$ and $Q$. - The second line contains a single string $S$ with length $N$. - Each of the next $Q$ lines contains two space-separated integers $L$ and $R$ describing a query. -----Output----- For each query, print a single line containing the string "YES" if the given substring contains a rich substring or "NO" if it does not contain any rich substring. -----Constraints----- - $1 \le T \le 10$ - $1 \le N, Q \le 10^5$ - $1 \le L \le R \le N$ - $S$ contains only lowercase English letters -----Example Input----- 1 10 2 helloworld 1 3 1 10 -----Example Output----- NO YES
{"inputs": ["1\n10 2\nhelloworld\n1 3\n1 10"], "outputs": ["NO\nYES"]}
338
31
coding
Solve the programming task below in a Python markdown code block. Alice and Bob play 5-in-a-row game. They have a playing field of size 10 × 10. In turns they put either crosses or noughts, one at a time. Alice puts crosses and Bob puts noughts. In current match they have made some turns and now it's Alice's turn. She wonders if she can put cross in such empty cell that she wins immediately. Alice wins if some crosses in the field form line of length not smaller than 5. This line can be horizontal, vertical and diagonal. -----Input----- You are given matrix 10 × 10 (10 lines of 10 characters each) with capital Latin letters 'X' being a cross, letters 'O' being a nought and '.' being an empty cell. The number of 'X' cells is equal to the number of 'O' cells and there is at least one of each type. There is at least one empty cell. It is guaranteed that in the current arrangement nobody has still won. -----Output----- Print 'YES' if it's possible for Alice to win in one turn by putting cross in some empty cell. Otherwise print 'NO'. -----Examples----- Input XX.XX..... .....OOOO. .......... .......... .......... .......... .......... .......... .......... .......... Output YES Input XXOXX..... OO.O...... .......... .......... .......... .......... .......... .......... .......... .......... Output NO
{"inputs": ["XX.XX.....\n.....OOOO.\n..........\n..........\n..........\n..........\n..........\n..........\n..........\n..........\n", "XXOXX.....\nOO.O......\n..........\n..........\n..........\n..........\n..........\n..........\n..........\n..........\n", "XO........\n.XO.......\n..XO......\n....O.....\n....X.....\n..........\n..........\n..........\n..........\n..........\n", "..X....XX.\n..........\n..........\nX..O..OO..\n....O.....\nX..O.....O\nO....OX..X\n..X....X.X\nO........O\n..........\n", "O.......O.\n.....O.X..\n......O...\n....X.O...\n.O.O.....X\n.XO.....XX\n...X...X.O\n........O.\n........O.\n.X.X.....X\n", "....OX....\n..........\n.O..X...X.\nXXO..XO..O\nO.......X.\n...XX.....\n..O.O...OX\n.........X\n.....X..OO\n........O.\n", "..O..X.X..\n.O..X...O.\n........O.\n...O..O...\nX.XX....X.\n..O....O.X\n..X.X....O\n......X..X\nO.........\n..X.O...OO\n", "..........\n..........\n..X.......\n..O.......\n..........\n..........\n..........\n..........\n..........\n..........\n"], "outputs": ["YES\n", "NO\n", "YES\n", "NO\n", "NO\n", "NO\n", "NO\n", "NO\n"]}
320
403
coding
Solve the programming task below in a Python markdown code block. You are given a regular N-gon with vertices at (cos(2πi / N), sin(2πi / N)), ∀ i ∈ [0,N-1]. Some of these vertices are blocked and all others are unblocked. We consider triangles with vertices at the vertices of N-gon and with at least one vertex at unblocked point. Can you find how many pairs of such triangles have equal area? Input Format The first line of input contains single integer T - number of testcases. 2T lines follow. Each testcase has two lines. The first line of testcase contains a single integer N - the number of vertices in N-gon. The second line contains string S with length N. If S[j] equals '1' it means that the vertex (cos(2πj / N), sin(2πj / N)) is unblocked, and if S[j] equals '0' it means that the vertex (cos(2πj / N), sin(2πj / N)) is blocked. Output Format For each testcase output single line with an answer. Constraints 1 <= T <= 100 3 <= N <= 10^{4} There will be no more than 50 blocked vertices in each of the testcase. Sample Input 1 4 1111 Sample Output 6 Explanation The testcase given is a square and there are 4 triangles that have the same area. So, the number of pairs are 4C2 = 6.
{"inputs": ["1\n4\n1111\n"], "outputs": ["6\n"]}
334
21
coding
Solve the programming task below in a Python markdown code block. Recently, a start up by two students of a state university of city F gained incredible popularity. Now it's time to start a new company. But what do we call it? The market analysts came up with a very smart plan: the name of the company should be identical to its reflection in a mirror! In other words, if we write out the name of the company on a piece of paper in a line (horizontally, from left to right) with large English letters, then put this piece of paper in front of the mirror, then the reflection of the name in the mirror should perfectly match the line written on the piece of paper. There are many suggestions for the company name, so coming up to the mirror with a piece of paper for each name wouldn't be sensible. The founders of the company decided to automatize this process. They asked you to write a program that can, given a word, determine whether the word is a 'mirror' word or not. -----Input----- The first line contains a non-empty name that needs to be checked. The name contains at most 10^5 large English letters. The name will be written with the next sans serif font: $\text{ABCDEFGHI JKLMNOPQRSTUVWXYZ}$ -----Output----- Print 'YES' (without the quotes), if the given name matches its mirror reflection. Otherwise, print 'NO' (without the quotes). -----Examples----- Input AHA Output YES Input Z Output NO Input XO Output NO
{"inputs": ["Z\n", "A\n", "B\n", "C\n", "D\n", "E\n", "F\n", "G\n"], "outputs": ["NO\n", "YES\n", "NO\n", "NO\n", "NO\n", "NO\n", "NO\n", "NO\n"]}
323
70
coding
Please solve the programming task below using a self-contained code snippet in a markdown code block. Given an integer array nums which is sorted in ascending order and all of its elements are unique and given also an integer k, return the kth missing number starting from the leftmost number of the array.   Please complete the following python code precisely: ```python class Solution: def missingElement(self, nums: List[int], k: int) -> int: ```
{"functional": "def check(candidate):\n assert candidate(nums = [4,7,9,10], k = 1) == 5\n assert candidate(nums = [4,7,9,10], k = 3) == 8\n assert candidate(nums = [1,2,4], k = 3) == 6\n\n\ncheck(Solution().missingElement)"}
93
88
coding
Solve the programming task below in a Python markdown code block. You are given two positive integers N and K. You have to perform the following operation exactly K times: - For the current value of N, choose any positive integer D such that D is a [divisor] of N and multiply D with N. Formally, N := (N * D) such that D is a divisor of current value of N. Print the sum of all distinct values of the final N you can receive after performing the above operation exactly K times. Since the answer can be large, print it modulo 10^{9} + 7. ------ Input Format ------ - The first line of input will contain a single integer T, denoting the number of test cases. - Each test case contains two space-separated integers N and K respectively, the initial number and the number of operations. ------ Output Format ------ For each test case, output on a new line the sum of all distinct values of the final N you can receive after performing the given operation exactly K times. Since the answer can be large, print it modulo 10^{9} + 7. ------ Constraints ------ $1 ≤ T ≤ 1000$ $1 ≤ N ≤ 10^{7}$ $1 ≤ K ≤ 10^{5}$ ----- Sample Input 1 ------ 3 1 5 2 2 10 1 ----- Sample Output 1 ------ 1 30 180 ----- explanation 1 ------ Test case $1$: $1$ is the only divisor of $1$. So, the value remains unchanged after the operations. Thus, there is only one distinct value after $5$ operations, which is $1$. Test case $2$: - Operation $1$: Initially, $N = 2$ has divisors $1$ and $2$. Thus, after $1$ operation, $N$ can be either $2\cdot 1 = 2$ or $2\cdot 2 = 4$. - Operation $2$: If $N=2$, the divisors are $1$ and $2$ which can lead to the final values as $2\cdot 1 = 2$ and $2\cdot 2 = 4$. If $N = 4$, the divisors are $1, 2, $ and $4$. Thus, the final values can be $4\cdot 1 = 4, 4\cdot 2 = 8, $ and $4\cdot 4 = 16$ . The distinct values that can be obtained after applying the operation $2$ times on $N = 2$ are $\{2, 4, 8, 16\}$, and $2 + 4 + 8 + 16 = 30$. Test case $3$: The numbers $10 = 10 \cdot 1$, $20 = 10 \cdot 2$, $50 = 10 \cdot 5$ and $100 = 10 \cdot 10$ can be obtained after applying the operation $1$ time on $N=10$, and $10 + 20 + 50 + 100 = 180$.
{"inputs": ["3\n1 5\n2 2\n10 1"], "outputs": ["1\n30\n180"]}
701
32
coding
Solve the programming task below in a Python markdown code block. _A mad sociopath scientist just came out with a brilliant invention! He extracted his own memories to forget all the people he hates! Now there's a lot of information in there, so he needs your talent as a developer to automatize that task for him._ > You are given the memories as a string containing people's surname and name (comma separated). The scientist marked one occurrence of each of the people he hates by putting a '!' right before their name. **Your task is to destroy all the occurrences of the marked people. One more thing ! Hate is contagious, so you also need to erase any memory of the person that comes after any marked name!** --- Examples --- --- Input: ``` "Albert Einstein, !Sarah Connor, Marilyn Monroe, Abraham Lincoln, Sarah Connor, Sean Connery, Marilyn Monroe, Bjarne Stroustrup, Manson Marilyn, Monroe Mary" ``` Output: ``` "Albert Einstein, Abraham Lincoln, Sean Connery, Bjarne Stroustrup, Manson Marilyn, Monroe Mary" ``` => We must remove every memories of Sarah Connor because she's marked, but as a side-effect we must also remove all the memories about Marilyn Monroe that comes right after her! Note that we can't destroy the memories of Manson Marilyn or Monroe Mary, so be careful! Also feel free to reuse/extend the following starter code: ```python def select(memory): ```
{"functional": "_inputs = [['Bryan Joubert'], ['Jesse Cox, !Selena Gomez'], ['!Eleena Daru, Obi-Wan Kenobi, Eleena Daru, Jar-Jar Binks'], ['Digital Daggers, !Kiny Nimaj, Rack Istley, Digital Daggers, Digital Daggers'], ['Albert Einstein, !Sarah Connor, Marilyn Monroe, Abraham Lincoln, Sarah Connor, Sean Connery, Marilyn Monroe, Bjarne Stroustrup, Manson Marilyn, Monroe Mary'], ['!Partha Ashanti, !Mindaugas Burton, Stacy Thompson, Amor Hadrien, !Ahtahkakoop Sothy, Partha Ashanti, Uzi Griffin, Partha Ashanti, !Serhan Eutimio, Amor Hadrien, Noor Konstantin'], ['!Code Wars, !Doug Smith, !Cyril Lemaire, !Codin Game']]\n_outputs = [['Bryan Joubert'], ['Jesse Cox'], ['Jar-Jar Binks'], ['Digital Daggers, Digital Daggers, Digital Daggers'], ['Albert Einstein, Abraham Lincoln, Sean Connery, Bjarne Stroustrup, Manson Marilyn, Monroe Mary'], ['Uzi Griffin, Noor Konstantin'], ['']]\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(select(*i), o[0])"}
299
404
coding
Please solve the programming task below using a self-contained code snippet in a markdown code block. A tree is an undirected graph in which any two vertices are connected by exactly one path. In other words, any connected graph without simple cycles is a tree. Given a tree of n nodes labelled from 0 to n - 1, and an array of n - 1 edges where edges[i] = [ai, bi] indicates that there is an undirected edge between the two nodes ai and bi in the tree, you can choose any node of the tree as the root. When you select a node x as the root, the result tree has height h. Among all possible rooted trees, those with minimum height (i.e. min(h))  are called minimum height trees (MHTs). Return a list of all MHTs' root labels. You can return the answer in any order. The height of a rooted tree is the number of edges on the longest downward path between the root and a leaf.   Please complete the following python code precisely: ```python class Solution: def findMinHeightTrees(self, n: int, edges: List[List[int]]) -> List[int]: ```
{"functional": "def check(candidate):\n assert candidate(n = 4, edges = [[1,0],[1,2],[1,3]]) == [1]\n assert candidate(n = 6, edges = [[3,0],[3,1],[3,2],[3,4],[5,4]]) == [3,4]\n\n\ncheck(Solution().findMinHeightTrees)"}
255
87
coding
Solve the programming task below in a Python markdown code block. ## Check Digits Some numbers are more important to get right during data entry than others: a common example is product codes. To reduce the possibility of mistakes, product codes can be crafted in such a way that simple errors are detected. This is done by calculating a single-digit value based on the product number, and then appending that digit to the product number to arrive at the product code. When the product code is checked, the check digit value is stripped off and recalculated. If the supplied value does not match the recalculated value, the product code is rejected. A simple scheme for generating self-check digits, described here, is called Modulus 11 Self-Check. ## Calculation method Each digit in the product number is assigned a multiplication factor. The factors are assigned ***from right to left***, starting at `2` and counting up. For numbers longer than six digits, the factors restart at `2` after `7` is reached. The product of each digit and its factor is calculated, and the products summed. For example: ```python digit : 1 6 7 7 0 3 6 2 5 factor : 4 3 2 7 6 5 4 3 2 --- --- --- --- --- --- --- --- --- 4 + 18 + 14 + 49 + 0 + 15 + 24 + 6 + 10 = 140 ``` Then the sum of the products is divided by the prime number `11`. The remainder is inspected, and: * if the remainder is `0`, the check digit is also `0` * if the remainder is `1`, the check digit is replaced by an uppercase `X` * for all others, the remainder is subtracted from `11` The result is the **check digit**. ## Your task Your task is to implement this algorithm and return the input number with the correct check digit appended. ## Examples ```python input: "036532" product sum = 2*2 + 3*3 + 5*4 + 6*5 + 3*6 + 0*7 = 81 remainder = 81 mod 11 = 4 check digit = 11 - 4 = 7 output: "0365327" ``` Also feel free to reuse/extend the following starter code: ```python def add_check_digit(number): ```
{"functional": "_inputs = [['036532'], ['12388878'], ['111111111'], ['9735597355'], ['2356'], ['6789']]\n_outputs = [['0365327'], ['123888782'], ['1111111118'], ['97355973550'], ['23566'], ['6789X']]\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(add_check_digit(*i), o[0])"}
573
261
coding
Solve the programming task below in a Python markdown code block. Chef Watson uses a social network called ChefBook, which has a new feed consisting of posts by his friends. Each post can be characterized by f - the identifier of the friend who created the post, p - the popularity of the post(which is pre-calculated by ChefBook platform using some machine learning algorithm) and s - the contents of the post which is a string of lower and uppercase English alphabets. Also, Chef has some friends, which he has marked as special. The algorithm used by ChefBook for determining the order of posts in news feed is as follows: - Posts of special friends should be shown first, irrespective of popularity. Among all such posts the popular ones should be shown earlier. - Among all other posts, popular posts should be shown earlier. Given, a list of identifiers of Chef's special friends and a list of posts, you have to implement this algorithm for engineers of ChefBook and output the correct ordering of posts in the new feed. -----Input----- First line contains N, number of special friends of Chef and M, the number of posts. Next line contains N integers A1, A2, ..., AN denoting the identifiers of special friends of Chef. Each of the next M lines contains a pair of integers and a string denoting f, p and s, identifier of the friend who created the post, the popularity of the post and the contents of the post, respectively. It is guaranteed that no two posts have same popularity, but the same friend might make multiple posts. -----Output----- Output correct ordering of posts in news feed in M lines. Output only the contents of a post. -----Constraints----- - 1 ≤ N, M ≤ 103 - 1 ≤ Ai, f, p ≤ 105 - 1 ≤ length(s) ≤ 100 -----Example----- Input: 2 4 1 2 1 1 WhoDoesntLoveChefBook 2 2 WinterIsComing 3 10 TheseViolentDelightsHaveViolentEnds 4 3 ComeAtTheKingBestNotMiss Output: WinterIsComing WhoDoesntLoveChefBook TheseViolentDelightsHaveViolentEnds ComeAtTheKingBestNotMiss -----Explanation----- First we should show posts created by friends with identifiers 1 and 2. Among the posts by these friends, the one with more popularity should be shown first. Among remaining posts, we show those which are more popular first.
{"inputs": ["2 4\n1 2\n1 1 WhoDoesntLoveChefBook\n2 2 WinterIsComing\n3 10 TheseViolentDelightsHaveViolentEnds\n4 3 ComeAtTheKingBestNotMiss"], "outputs": ["WinterIsComing\nWhoDoesntLoveChefBook\nTheseViolentDelightsHaveViolentEnds\nComeAtTheKingBestNotMiss"]}
525
89
coding
Solve the programming task below in a Python markdown code block. Write a function that reverses the bits in an integer. For example, the number `417` is `110100001` in binary. Reversing the binary is `100001011` which is `267`. You can assume that the number is not negative. Also feel free to reuse/extend the following starter code: ```python def reverse_bits(n): ```
{"functional": "_inputs = [[417], [267], [0], [2017], [1023], [1024]]\n_outputs = [[267], [417], [0], [1087], [1023], [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(reverse_bits(*i), o[0])"}
105
207
coding
Solve the programming task below in a Python markdown code block. Every Turkish citizen has an identity number whose validity can be checked by these set of rules: - It is an 11 digit number - First digit can't be zero - Take the sum of 1st, 3rd, 5th, 7th and 9th digit and multiply it by 7. Then subtract the sum of 2nd, 4th, 6th and 8th digits from this value. Modulus 10 of the result should be equal to 10th digit. - Sum of first ten digits' modulus 10 should be equal to eleventh digit. Example: 10167994524 // 1+1+7+9+5= 23 // "Take the sum of 1st, 3rd, 5th, 7th and 9th digit..." // 23 * 7= 161 // "...and multiply it by 7" // 0+6+9+4 = 19 // "Take the sum of 2nd, 4th, 6th and 8th digits..." // 161 - 19 = 142 // "...and subtract from first value" // "Modulus 10 of the result should be equal to 10th digit" 10167994524 ^ = 2 = 142 % 10 // 1+0+1+6+7+9+9+4+5+2 = 44 // "Sum of first ten digits' modulus 10 should be equal to eleventh digit" 10167994524 ^ = 4 = 44 % 10 Your task is to write a function to check the validity of a given number. Return `true` or `false` accordingly. Note: The input can be a string in some cases. Also feel free to reuse/extend the following starter code: ```python def check_valid_tr_number(number): ```
{"functional": "_inputs = [[6923522112], [692352217312], ['x5810a78432'], [36637640050], [12762438338], ['03868894286'], [10000000146], [19415235426], [16691067984], [72097107542], [57040492705]]\n_outputs = [[False], [False], [False], [True], [False], [False], [True], [True], [False], [True], [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(check_valid_tr_number(*i), o[0])"}
479
326
coding
Solve the programming task below in a Python markdown code block. Takahashi is a member of a programming competition site, ButCoder. Each member of ButCoder is assigned two values: Inner Rating and Displayed Rating. The Displayed Rating of a member is equal to their Inner Rating if the member has participated in 10 or more contests. Otherwise, the Displayed Rating will be their Inner Rating minus 100 \times (10 - K) when the member has participated in K contests. Takahashi has participated in N contests, and his Displayed Rating is R. Find his Inner Rating. -----Constraints----- - All values in input are integers. - 1 \leq N \leq 100 - 0 \leq R \leq 4111 -----Input----- Input is given from Standard Input in the following format: N R -----Output----- Print his Inner Rating. -----Sample Input----- 2 2919 -----Sample Output----- 3719 Takahashi has participated in 2 contests, which is less than 10, so his Displayed Rating is his Inner Rating minus 100 \times (10 - 2) = 800. Thus, Takahashi's Inner Rating is 2919 + 800 = 3719.
{"inputs": ["0 6", "2 1", "3 1", "3 0", "1 0", "1 2", "2 2", "2 4"], "outputs": ["1006\n", "801\n", "701\n", "700\n", "900\n", "902\n", "802\n", "804\n"]}
286
95
coding
Please solve the programming task below using a self-contained code snippet in a markdown code block. Given a 0-indexed integer array nums of size n, find the maximum difference between nums[i] and nums[j] (i.e., nums[j] - nums[i]), such that 0 <= i < j < n and nums[i] < nums[j]. Return the maximum difference. If no such i and j exists, return -1.   Please complete the following python code precisely: ```python class Solution: def maximumDifference(self, nums: List[int]) -> int: ```
{"functional": "def check(candidate):\n assert candidate(nums = [7,1,5,4]) == 4\n assert candidate(nums = [9,4,3,2]) == -1\n assert candidate(nums = [1,5,2,10]) == 9\n\n\ncheck(Solution().maximumDifference)"}
119
74
coding
Solve the programming task below in a Python markdown code block. Alice has a grid with $2$ rows and $n$ columns. She fully covers the grid using $n$ dominoes of size $1 \times 2$ — Alice may place them vertically or horizontally, and each cell should be covered by exactly one domino. Now, she decided to show one row of the grid to Bob. Help Bob and figure out what the other row of the grid looks like! -----Input----- The input consists of multiple test cases. The first line contains an integer $t$ ($1 \leq t \leq 5000$) — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $n$ ($1 \leq n \leq 100$) — the width of the grid. The second line of each test case contains a string $s$ consisting of $n$ characters, each of which is either L, R, U, or D, representing the left, right, top, or bottom half of a domino, respectively (see notes for better understanding). This string represents one of the rows of the grid. Additional constraint on the input: each input corresponds to at least one valid tiling. -----Output----- For each test case, output one string — the other row of the grid, using the same format as the input string. If there are multiple answers, print any. -----Examples----- Input 4 1 U 2 LR 5 LRDLR 6 UUUUUU Output D LR LRULR DDDDDD -----Note----- In the first test case, Alice shows Bob the top row, the whole grid may look like: In the second test case, Alice shows Bob the bottom row, the whole grid may look like: In the third test case, Alice shows Bob the bottom row, the whole grid may look like: In the fourth test case, Alice shows Bob the top row, the whole grid may look like:
{"inputs": ["4\n1\nU\n2\nLR\n5\nLRDLR\n6\nUUUUUU\n"], "outputs": ["D\nLR\nLRULR\nDDDDDD\n"]}
432
44
coding
Solve the programming task below in a Python markdown code block. A palindrome is a word that reads the same forward and backward. Given a string s, you need to make it a palindrome by adding 0 or more characters to the end of s, and remember, we want the palindrome to be as short as possible. INPUT First line is T, the number of test cases. T strings follow, every string s needs to be converted to palindrome. OUTPUT Print the shortest possible length of a palindrome that John can generate. CONSTRAINTS 1 ≤ T ≤ 50 s will contain between 1 and 50 characters, inclusive, palindrome can be larger in length. Each character of s will be a lowercase letter ('a' - 'z'). SAMPLE INPUT 3 abab abacaba qwerty SAMPLE OUTPUT 5 7 11
{"inputs": ["6\nabdfhdyrbdbsdfghjkllkjhgfds\nzazazazazazazazazazazazazazazazazazazazazazazazaza\nbacba\na\nadwuaaxcnleegluqvsczaguujoppchwecusmevz\nkoikijiikmmkmonkiinnjlijmiimnniokikimikkkkjkmiinii"], "outputs": ["38\n51\n9\n1\n77\n95"]}
184
120
coding
Please solve the programming task below using a self-contained code snippet in a markdown code block. Given a signed 32-bit integer x, return x with its digits reversed. If reversing x causes the value to go outside the signed 32-bit integer range [-231, 231 - 1], then return 0. Assume the environment does not allow you to store 64-bit integers (signed or unsigned).   Please complete the following python code precisely: ```python class Solution: def reverse(self, x: int) -> int: ```
{"functional": "def check(candidate):\n assert candidate(x = 123) == 321\n assert candidate(x = -123) == -321\n assert candidate(x = 120) == 21\n assert candidate(x = 0) == 0\n\n\ncheck(Solution().reverse)"}
118
77
coding
Solve the programming task below in a Python markdown code block. Let T be arbitrary binary tree — tree, every vertex of which has no more than two children. Given tree is rooted, so there exists only one vertex which doesn't have a parent — it's the root of a tree. Every vertex has an integer number written on it. Following algorithm is run on every value from the tree T: Set pointer to the root of a tree. Return success if the value in the current vertex is equal to the number you are looking for Go to the left child of the vertex if the value in the current vertex is greater than the number you are looking for Go to the right child of the vertex if the value in the current vertex is less than the number you are looking for Return fail if you try to go to the vertex that doesn't exist Here is the pseudo-code of the described algorithm: bool find(TreeNode t, int x) { if (t == null) return false; if (t.value == x) return true; if (x < t.value) return find(t.left, x); else return find(t.right, x); } find(root, x); The described algorithm works correctly if the tree is binary search tree (i.e. for each node the values of left subtree are less than the value in the node, the values of right subtree are greater than the value in the node). But it can return invalid result if tree is not a binary search tree. Since the given tree is not necessarily a binary search tree, not all numbers can be found this way. Your task is to calculate, how many times the search will fail being running on every value from the tree. If the tree has multiple vertices with the same values on them then you should run algorithm on every one of them separately. -----Input----- First line contains integer number n (1 ≤ n ≤ 10^5) — number of vertices in the tree. Each of the next n lines contains 3 numbers v, l, r (0 ≤ v ≤ 10^9) — value on current vertex, index of the left child of the vertex and index of the right child of the vertex, respectively. If some child doesn't exist then number - 1 is set instead. Note that different vertices of the tree may contain the same values. -----Output----- Print number of times when search algorithm will fail. -----Examples----- Input 3 15 -1 -1 10 1 3 5 -1 -1 Output 2 Input 8 6 2 3 3 4 5 12 6 7 1 -1 8 4 -1 -1 5 -1 -1 14 -1 -1 2 -1 -1 Output 1 -----Note----- In the example the root of the tree in vertex 2. Search of numbers 5 and 15 will return fail because on the first step algorithm will choose the subtree which doesn't contain numbers you are looking for.
{"inputs": ["1\n0 -1 -1\n", "1\n0 -1 -1\n", "1\n1 -1 -1\n", "1\n4277071 -1 -1\n", "1\n73706168 -1 -1\n", "1\n493041212 -1 -1\n", "1\n815121916 -1 -1\n", "1\n901418150 -1 -1\n"], "outputs": ["0\n", "0\n", "0\n", "0\n", "0\n", "0\n", "0\n", "0\n"]}
640
155
coding
Solve the programming task below in a Python markdown code block. There is an integer $n$ without zeros in its decimal representation. Alice and Bob are playing a game with this integer. Alice starts first. They play the game in turns. On her turn, Alice must swap any two digits of the integer that are on different positions. Bob on his turn always removes the last digit of the integer. The game ends when there is only one digit left. You have to find the smallest integer Alice can get in the end, if she plays optimally. -----Input----- The input consists of multiple test cases. The first line contains a single integer $t$ ($1 \le t \le 10^4$) — the number of test cases. Description of the test cases follows. The first and the only line of each test case contains the integer $n$ ($10 \le n \le 10^9$) — the integer for the game. $n$ does not have zeros in its decimal representation. -----Output----- For each test case output a single integer — the smallest integer Alice can get in the end of the game. -----Examples----- Input 3 12 132 487456398 Output 2 1 3 -----Note----- In the first test case Alice has to swap $1$ and $2$. After that Bob removes the last digit, $1$, so the answer is $2$. In the second test case Alice can swap $3$ and $1$: $312$. After that Bob deletes the last digit: $31$. Then Alice swaps $3$ and $1$: $13$ and Bob deletes $3$, so the answer is $1$.
{"inputs": ["3\n12\n132\n487456398\n"], "outputs": ["2\n1\n3\n"]}
365
35
coding
Solve the programming task below in a Python markdown code block. Introduction to Disjunctions In logic and mathematics, a disjunction is an operation on 2 or more propositions. A disjunction is true if and only if 1 or more of its operands is true. In programming, we typically denote a disjunction using "||", but in logic we typically use "v". Example of disjunction: p = 1 > 2 = false q = 2 < 3 = true therefore p v q is true In a programming language, we might write this as: var p = 1 > 2; // false var q = 2 < 3; // true var result = p || q; // true The above example demonstrates an inclusive disjunction (meaning it includes cases where both operands are true). Disjunctions can also be exlusive. An exclusive disjunction is typically represented by "⊻" and is true if and only if both operands have opposite values. p = 1 < 2 = true q = 2 < 3 = true therefore p ⊻ q is false This can become confusing when dealing with more than 2 operands. r = 3 < 4 = true p ⊻ q ⊻ r = ??? We handle these situations by evaluating the expression from left to right. p ⊻ q = false (p ⊻ q) ⊻ r = true Directions: For this kata, your task is to implement a function that performs a disjunction operation on 2 or more propositions. Should take a boolean array as its first parameter and a single boolean as its second parameter, which, if true, should indicate that the disjunction should be exclusive as opposed to inclusive. Should return true or false. Also feel free to reuse/extend the following starter code: ```python def disjunction(operands, is_exclusive): ```
{"functional": "_inputs = [[[False, True, True], False], [[False, True, False], False], [[False, True, True, True], True], [[True, True, True], False], [[True, True, True, True], False]]\n_outputs = [[True], [True], [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(disjunction(*i), o[0])"}
403
212
coding
Solve the programming task below in a Python markdown code block. Given time in 24-hour format, convert it to words. ``` For example: 13:00 = one o'clock 13:09 = nine minutes past one 13:15 = quarter past one 13:29 = twenty nine minutes past one 13:30 = half past one 13:31 = twenty nine minutes to two 13:45 = quarter to two 00:48 = twelve minutes to one 00:08 = eight minutes past midnight 12:00 = twelve o'clock 00:00 = midnight Note: If minutes == 0, use 'o'clock'. If minutes <= 30, use 'past', and for minutes > 30, use 'to'. ``` More examples in test cases. Good luck! Also feel free to reuse/extend the following starter code: ```python def solve(time): ```
{"functional": "_inputs = [['13:00'], ['13:09'], ['13:15'], ['13:29'], ['13:30'], ['13:31'], ['13:45'], ['13:59'], ['00:48'], ['00:08'], ['12:00'], ['00:00'], ['19:01'], ['07:01'], ['01:59'], ['12:01'], ['00:01'], ['11:31'], ['23:31'], ['11:45'], ['11:59'], ['23:45'], ['23:59'], ['01:45']]\n_outputs = [[\"one o'clock\"], ['nine minutes past one'], ['quarter past one'], ['twenty nine minutes past one'], ['half past one'], ['twenty nine minutes to two'], ['quarter to two'], ['one minute to two'], ['twelve minutes to one'], ['eight minutes past midnight'], [\"twelve o'clock\"], ['midnight'], ['one minute past seven'], ['one minute past seven'], ['one minute to two'], ['one minute past twelve'], ['one minute past midnight'], ['twenty nine minutes to twelve'], ['twenty nine minutes to midnight'], ['quarter to twelve'], ['one minute to twelve'], ['quarter to midnight'], ['one minute to midnight'], ['quarter to two']]\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(solve(*i), o[0])"}
216
460
coding
Solve the programming task below in a Python markdown code block. Note: This kata is inspired by [Convert a Number to a String!](http://www.codewars.com/kata/convert-a-number-to-a-string/). Try that one too. ## Description We need a function that can transform a string into a number. What ways of achieving this do you know? Note: Don't worry, all inputs will be strings, and every string is a perfectly valid representation of an integral number. ## Examples ```python stringToNumber("1234") == 1234 stringToNumber("605" ) == 605 stringToNumber("1405") == 1405 stringToNumber("-7" ) == -7 ``` Also feel free to reuse/extend the following starter code: ```python def string_to_number(s): ```
{"functional": "_inputs = [['4']]\n_outputs = [[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(string_to_number(*i), o[0])"}
191
155
coding
Solve the programming task below in a Python markdown code block. Bob has a server farm crunching numbers. He has `nodes` servers in his farm. His company has a lot of work to do. The work comes as a number `workload` which indicates how many jobs there are. Bob wants his servers to get an equal number of jobs each. If that is impossible, he wants the first servers to receive more jobs. He also wants the jobs sorted, so that the first server receives the first jobs. The way this works, Bob wants an array indicating which jobs are going to which servers. Can you help him distribute all this work as evenly as possible onto his servers? Example ------- Bob has `2` servers and `4` jobs. The first server should receive job 0 and 1 while the second should receive 2 and 3. ``` distribute(2, 4) # => [[0, 1], [2, 3]] ``` On a different occasion Bob has `3` servers and `3` jobs. Each should get just one. ``` distribute(3, 3) # => [[0], [1], [2]] ``` A couple of days go by and Bob sees a spike in jobs. Now there are `10`, but he hasn't got more than `4` servers available. He boots all of them. This time the first and second should get a job more than the third and fourth. ``` distribute(4, 10) # => [[0, 1, 2], [3, 4, 5], [6, 7], [8, 9]] ``` Input ----- Don't worry about invalid inputs. That is, `nodes > 0` and `workload > 0` and both will always be integers. Also feel free to reuse/extend the following starter code: ```python def distribute(nodes, workload): ```
{"functional": "_inputs = [[2, 4], [3, 3], [3, 9], [2, 5], [4, 10], [4, 5], [1, 1], [2, 1], [5, 4], [5, 1]]\n_outputs = [[[[0, 1], [2, 3]]], [[[0], [1], [2]]], [[[0, 1, 2], [3, 4, 5], [6, 7, 8]]], [[[0, 1, 2], [3, 4]]], [[[0, 1, 2], [3, 4, 5], [6, 7], [8, 9]]], [[[0, 1], [2], [3], [4]]], [[[0]]], [[[0], []]], [[[0], [1], [2], [3], []]], [[[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(distribute(*i), o[0])"}
406
355
coding
Solve the programming task below in a Python markdown code block. The chef is trying to decode some pattern problems, Chef wants your help to code it. Chef has one number K to form a new pattern. Help the chef to code this pattern problem. -----Input:----- - First-line will contain $T$, the number of test cases. Then the test cases follow. - Each test case contains a single line of input, one integer $K$. -----Output:----- For each test case, output as the pattern. -----Constraints----- - $1 \leq T \leq 10$ - $1 \leq K \leq 10$ -----Sample Input:----- 4 1 2 3 4 -----Sample Output:----- 0 0 1 1 0 1 1 2 3 5 0 1 1 2 3 5 8 13 21 34 -----EXPLANATION:----- No need, else pattern can be decode easily.
{"inputs": ["4\n1\n2\n3\n4"], "outputs": ["0\n0\n1 1\n0\n1 1\n2 3 5\n0\n1 1\n2 3 5\n8 13 21 34"]}
217
61
coding
Solve the programming task below in a Python markdown code block. Alice and Bob are meeting after a long time. As usual they love to play some math games. This times Alice takes the call and decides the game. The game is very simple, Alice says out an integer and Bob has to say whether the number is prime or not. Bob as usual knows the logic but since Alice doesn't give Bob much time to think, so Bob decides to write a computer program. Help Bob accomplish this task by writing a computer program which will calculate whether the number is prime or not . ------ Input ------ The first line of the input contains an integer T, the number of testcases. T lines follow. Each of the next T lines contains an integer N which has to be tested for primality. ------ Output ------ For each test case output in a separate line, "yes" if the number is prime else "no." ------ Constraints ------ $1 ≤ T ≤ 20$ $1 ≤ N ≤ 100000$ ----- Sample Input 1 ------ 5 23 13 20 1000 99991 ----- Sample Output 1 ------ yes yes no no yes
{"inputs": ["5\n14\n3\n28\n1000\n849", "5\n32\n19\n20\n1100\n793", "5\n32\n28\n20\n1100\n793", "5\n32\n31\n20\n1100\n793", "5\n10\n31\n20\n1100\n793", "5\n10\n31\n20\n1101\n793", "5\n14\n22\n28\n1010\n849", "5\n10\n31\n39\n1100\n793"], "outputs": ["no\nyes\nno\nno\nno\n", "no\nyes\nno\nno\nno\n", "no\nno\nno\nno\nno\n", "no\nyes\nno\nno\nno\n", "no\nyes\nno\nno\nno\n", "no\nyes\nno\nno\nno\n", "no\nno\nno\nno\nno\n", "no\nyes\nno\nno\nno\n"]}
260
269
coding
Solve the programming task below in a Python markdown code block. You are given an array $a$ consisting of $n$ integers. Initially all elements of $a$ are either $0$ or $1$. You need to process $q$ queries of two kinds: 1 x : Assign to $a_x$ the value $1 - a_x$. 2 k : Print the $k$-th largest value of the array. As a reminder, $k$-th largest value of the array $b$ is defined as following: Sort the array in the non-increasing order, return $k$-th element from it. For example, the second largest element in array $[0, 1, 0, 1]$ is $1$, as after sorting in non-increasing order it becomes $[1, 1, 0, 0]$, and the second element in this array is equal to $1$. -----Input----- The first line contains two integers $n$ and $q$ ($1 \le n, q \le 10^5$) — the length of the given array and the number of queries. The second line contains $n$ integers $a_1, a_2, a_3, \dots, a_n$ ($0 \le a_i \le 1$) — elements of the initial array. Each of the following $q$ lines contains two integers. The first integer is $t$ ($1 \le t \le 2$) — the type of query. If $t = 1$ the second integer is $x$ ($1 \le x \le n$) — the position of the modified number. You have to assign to $a_x$ the value $1 - a_x$. If $t = 2$ the second integer is $k$ ($1 \le k \le n$) — you need to print the $k$-th largest value of the array. It's guaranteed that there will be at least one query of the second type (satisfying $t = 2$). -----Output----- For each query of the second type, print a single integer — the answer to the query. -----Examples----- Input 5 5 1 1 0 1 0 2 3 1 2 2 3 2 1 2 5 Output 1 0 1 0 -----Note----- Initially $a = [1, 1, 0, 1, 0]$. The first operation is printing the third largest value, which is $1$. The second operation is assigning $a_2$ the value $0$, $a$ becomes $[1, 0, 0, 1, 0]$. The third operation is printing the third largest value, it is $0$. The fourth operation is printing the first largest value, it is $1$. The last operation is printing the fifth largest value, it is $0$.
{"inputs": ["1 1\n0\n2 1\n", "1 1\n0\n2 1\n", "5 5\n1 1 0 1 0\n2 3\n1 2\n2 3\n2 1\n2 5\n", "5 5\n0 1 0 1 0\n2 3\n1 2\n2 3\n2 1\n2 5\n", "5 5\n1 1 1 1 0\n2 3\n1 2\n2 3\n2 1\n2 5\n", "5 5\n1 1 1 1 0\n2 3\n1 2\n2 3\n2 1\n2 2\n", "5 5\n0 1 0 0 0\n2 3\n1 2\n2 3\n2 1\n2 3\n", "5 5\n1 1 1 1 0\n2 5\n1 2\n2 3\n2 1\n2 5\n"], "outputs": ["0\n", "0\n", "1\n0\n1\n0\n", "0\n0\n1\n0\n", "1\n1\n1\n0\n", "1\n1\n1\n1\n", "0\n0\n0\n0\n", "0\n1\n1\n0\n"]}
633
314
coding
Solve the programming task below in a Python markdown code block. The pizza store wants to know how long each order will take. They know: - Prepping a pizza takes 3 mins - Cook a pizza takes 10 mins - Every salad takes 3 mins to make - Every appetizer takes 5 mins to make - There are 2 pizza ovens - 5 pizzas can fit in a oven - Prepping for a pizza must be done before it can be put in the oven - There are two pizza chefs and one chef for appitizers and salads combined - The two pizza chefs can work on the same pizza Write a function, order, which will tell the company how much time the order will take. See example tests for details. Also feel free to reuse/extend the following starter code: ```python def order(pizzas, salads, appetizers): ```
{"functional": "_inputs = [[2, 0, 0], [3, 1, 2], [0, 3, 2], [13, 0, 0], [6, 2, 4], [6, 1, 3], [5, 3, 4]]\n_outputs = [[13], [14.5], [19], [39.5], [26], [19], [29]]\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(order(*i), o[0])"}
187
243
coding
Solve the programming task below in a Python markdown code block. Tanya wants to go on a journey across the cities of Berland. There are n cities situated along the main railroad line of Berland, and these cities are numbered from 1 to n. Tanya plans her journey as follows. First of all, she will choose some city c_1 to start her journey. She will visit it, and after that go to some other city c_2 > c_1, then to some other city c_3 > c_2, and so on, until she chooses to end her journey in some city c_k > c_{k - 1}. So, the sequence of visited cities [c_1, c_2, ..., c_k] should be strictly increasing. There are some additional constraints on the sequence of cities Tanya visits. Each city i has a beauty value b_i associated with it. If there is only one city in Tanya's journey, these beauty values imply no additional constraints. But if there are multiple cities in the sequence, then for any pair of adjacent cities c_i and c_{i + 1}, the condition c_{i + 1} - c_i = b_{c_{i + 1}} - b_{c_i} must hold. For example, if n = 8 and b = [3, 4, 4, 6, 6, 7, 8, 9], there are several three possible ways to plan a journey: * c = [1, 2, 4]; * c = [3, 5, 6, 8]; * c = [7] (a journey consisting of one city is also valid). There are some additional ways to plan a journey that are not listed above. Tanya wants her journey to be as beautiful as possible. The beauty value of the whole journey is the sum of beauty values over all visited cities. Can you help her to choose the optimal plan, that is, to maximize the beauty value of the journey? Input The first line contains one integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the number of cities in Berland. The second line contains n integers b_1, b_2, ..., b_n (1 ≤ b_i ≤ 4 ⋅ 10^5), where b_i is the beauty value of the i-th city. Output Print one integer — the maximum beauty of a journey Tanya can choose. Examples Input 6 10 7 1 9 10 15 Output 26 Input 1 400000 Output 400000 Input 7 8 9 26 11 12 29 14 Output 55 Note The optimal journey plan in the first example is c = [2, 4, 5]. The optimal journey plan in the second example is c = [1]. The optimal journey plan in the third example is c = [3, 6].
{"inputs": ["2\n2 2\n", "2\n1 2\n", "2\n2 1\n", "2\n1 1\n", "2\n3 1\n", "2\n1 0\n", "2\n2 0\n", "2\n1 -1\n"], "outputs": ["2\n", "3\n", "2\n", "1\n", "3\n", "1\n", "2\n", "1\n"]}
655
102
coding
Solve the programming task below in a Python markdown code block. This kata is based on a [variation](https://www.codewars.com/kata/happy-numbers-5) of *Happy Numbers* by TySlothrop. It is advisable to complete it first to grasp the idea and then move on to this one. ___ Hello, my dear friend, and welcome to another *Happy Numbers* kata! What? You're not interested in them anymore? They are all the same? But what if I say that this one is a *performance version*... ___ # Your task: Write a function `performant_numbers` which takes a number `n` as an argument and returns a list of all *happy numbers* from `1` to `n` inclusive. For example: ``` performant_numbers(10) => [1, 7, 10] performant_numbers(50) => [1, 7, 10, 13, 19, 23, 28, 31, 32, 44, 49] performant_numbers(100) => [1, 7, 10, 13, 19, 23, 28, 31, 32, 44, 49, 68, 70, 79, 82, 86, 91, 94, 97, 100] ``` # Test suite: * `5000` tests with number `n` being up to `300000` * The reference solution takes around `4.9` seconds to calculate the result * you are not allowed to hardcode the sequence: you'll have to compute it (max length of the code: 1700 characters) ___ Will you take up the challenge? Also feel free to reuse/extend the following starter code: ```python def performant_numbers(n, happy_list=sorted(happy_set)): ```
{"functional": "_inputs = [[10], [50], [100]]\n_outputs = [[[1, 7, 10]], [[1, 7, 10, 13, 19, 23, 28, 31, 32, 44, 49]], [[1, 7, 10, 13, 19, 23, 28, 31, 32, 44, 49, 68, 70, 79, 82, 86, 91, 94, 97, 100]]]\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(performant_numbers(*i), o[0])"}
443
294
coding
Solve the programming task below in a Python markdown code block. The height of the student was measured at the medical examination. Create a program that takes height data as input, creates a frequency distribution, and outputs it. The frequency distribution is divided into 6 classes in 5 cm increments, and the number of people is indicated by * (half-width asterisk). However, if the frequency (number of people) of that class is 0, output only the class heading. Input The input is given in the following format: n h1 h2 :: hn The number of students n (1 ≤ n ≤ 40) is given to the first line, and the real number hi (150.0 ≤ hi ≤ 190.0, up to the first decimal place) representing the height of the i-th person is given to each line after the second line. .. Output Display the frequency distribution in the following format. Line 1 Heading "1:" followed by * for people less than 165.0 cm * 2nd line Heading "2:" followed by people 165.0 cm or more and less than 170.0 cm * 3rd line Heading "3:" followed by the number of people from 170.0 cm or more to less than 175.0 cm * 4th line Heading "4:" followed by the number of people from 175.0 cm to less than 180.0 cm * Line 5 Heading "5:" followed by the number of people between 180.0 cm and 185.0 cm * Line 6 Heading "6:" followed by * for people over 185.0 cm * Examples Input 4 180.3 168.2 165.5 175.3 Output 1: 2:** 3: 4:* 5:* 6: Input 21 179.4 171.5 156.6 173.0 169.4 181.2 172.4 170.0 163.6 165.9 173.5 168.2 162.5 172.0 175.1 172.3 167.5 175.9 186.2 168.0 178.6 Output 1:*** 2:***** 3:******* 4:**** 5:* 6:*
{"inputs": ["4\n180.3\n168.2\n165.5\n175.3", "4\n180.3\n168.42932428490565\n165.5\n175.3", "4\n180.68754203533285\n168.42932428490565\n165.5\n175.3", "4\n180.95536695412983\n168.42932428490565\n165.5\n175.3", "4\n180.95536695412983\n168.42932428490565\n165.65038418972082\n175.3", "4\n186.487152384495\n176.25755947274573\n175.0305181428357\n181.06399491806826", "4\n183.02435253237\n171.21815440638807\n167.02186521790964\n175.91022475280127", "4\n184.5675474968178\n172.0731721880196\n169.1447810110061\n176.55319829388554"], "outputs": ["1:\n2:**\n3:\n4:*\n5:*\n6:", "1:\n2:**\n3:\n4:*\n5:*\n6:\n", "1:\n2:**\n3:\n4:*\n5:*\n6:\n", "1:\n2:**\n3:\n4:*\n5:*\n6:\n", "1:\n2:**\n3:\n4:*\n5:*\n6:\n", "1:\n2:\n3:\n4:**\n5:*\n6:*\n", "1:\n2:*\n3:*\n4:*\n5:*\n6:\n", "1:\n2:*\n3:*\n4:*\n5:*\n6:\n"]}
564
657
coding
Solve the programming task below in a Python markdown code block. Analyzing the mistakes people make while typing search queries is a complex and an interesting work. As there is no guaranteed way to determine what the user originally meant by typing some query, we have to use different sorts of heuristics. Polycarp needed to write a code that could, given two words, check whether they could have been obtained from the same word as a result of typos. Polycarpus suggested that the most common typo is skipping exactly one letter as you type a word. Implement a program that can, given two distinct words S and T of the same length n determine how many words W of length n + 1 are there with such property that you can transform W into both S, and T by deleting exactly one character. Words S and T consist of lowercase English letters. Word W also should consist of lowercase English letters. -----Input----- The first line contains integer n (1 ≤ n ≤ 100 000) — the length of words S and T. The second line contains word S. The third line contains word T. Words S and T consist of lowercase English letters. It is guaranteed that S and T are distinct words. -----Output----- Print a single integer — the number of distinct words W that can be transformed to S and T due to a typo. -----Examples----- Input 7 reading trading Output 1 Input 5 sweet sheep Output 0 Input 3 toy try Output 2 -----Note----- In the first sample test the two given words could be obtained only from word "treading" (the deleted letters are marked in bold). In the second sample test the two given words couldn't be obtained from the same word by removing one letter. In the third sample test the two given words could be obtained from either word "tory" or word "troy".
{"inputs": ["1\na\nb\n", "1\nz\ny\n", "2\nab\nac\n", "2\nba\nca\n", "2\nac\ncb\n", "2\nab\nba\n", "2\ner\nre\n", "3\ntoy\ntry\n"], "outputs": ["2\n", "2\n", "2\n", "2\n", "1\n", "2\n", "2\n", "2\n"]}
398
104
coding
Please solve the programming task below using a self-contained code snippet in a markdown code block. You are given two positive 0-indexed integer arrays nums1 and nums2, both of length n. The sum of squared difference of arrays nums1 and nums2 is defined as the sum of (nums1[i] - nums2[i])2 for each 0 <= i < n. You are also given two positive integers k1 and k2. You can modify any of the elements of nums1 by +1 or -1 at most k1 times. Similarly, you can modify any of the elements of nums2 by +1 or -1 at most k2 times. Return the minimum sum of squared difference after modifying array nums1 at most k1 times and modifying array nums2 at most k2 times. Note: You are allowed to modify the array elements to become negative integers.   Please complete the following python code precisely: ```python class Solution: def minSumSquareDiff(self, nums1: List[int], nums2: List[int], k1: int, k2: int) -> int: ```
{"functional": "def check(candidate):\n assert candidate(nums1 = [1,2,3,4], nums2 = [2,10,20,19], k1 = 0, k2 = 0) == 579\n assert candidate(nums1 = [1,4,10,12], nums2 = [5,8,6,9], k1 = 1, k2 = 1) == 43\n\n\ncheck(Solution().minSumSquareDiff)"}
229
115
coding
Solve the programming task below in a Python markdown code block. There are N computers and N sockets in a one-dimensional world. The coordinate of the i-th computer is a_i, and the coordinate of the i-th socket is b_i. It is guaranteed that these 2N coordinates are pairwise distinct. Snuke wants to connect each computer to a socket using a cable. Each socket can be connected to only one computer. In how many ways can he minimize the total length of the cables? Compute the answer modulo 10^9+7. Constraints * 1 ≤ N ≤ 10^5 * 0 ≤ a_i, b_i ≤ 10^9 * The coordinates are integers. * The coordinates are pairwise distinct. Input The input is given from Standard Input in the following format: N a_1 : a_N b_1 : b_N Output Print the number of ways to minimize the total length of the cables, modulo 10^9+7. Examples Input 2 0 10 20 30 Output 2 Input 3 3 10 8 7 12 5 Output 1
{"inputs": ["2\n-1\n1\n7\n78", "2\n1\n11\n4\n68", "2\n0\n2\n3\n312", "2\n0\n2\n20\n48", "2\n2\n11\n4\n68", "2\n1\n2\n3\n312", "2\n0\n2\n20\n56", "2\n0\n2\n21\n78"], "outputs": ["2\n", "1\n", "2\n", "2\n", "1\n", "2\n", "2\n", "2\n"]}
255
142
coding
Solve the programming task below in a Python markdown code block. Berland has a long and glorious history. To increase awareness about it among younger citizens, King of Berland decided to compose an anthem. Though there are lots and lots of victories in history of Berland, there is the one that stand out the most. King wants to mention it in the anthem as many times as possible. He has already composed major part of the anthem and now just needs to fill in some letters. King asked you to help him with this work. The anthem is the string s of no more than 10^5 small Latin letters and question marks. The most glorious victory is the string t of no more than 10^5 small Latin letters. You should replace all the question marks with small Latin letters in such a way that the number of occurrences of string t in string s is maximal. Note that the occurrences of string t in s can overlap. Check the third example for clarification. -----Input----- The first line contains string of small Latin letters and question marks s (1 ≤ |s| ≤ 10^5). The second line contains string of small Latin letters t (1 ≤ |t| ≤ 10^5). Product of lengths of strings |s|·|t| won't exceed 10^7. -----Output----- Output the maximum number of occurrences of string t you can achieve by replacing all the question marks in string s with small Latin letters. -----Examples----- Input winlose???winl???w?? win Output 5 Input glo?yto?e??an? or Output 3 Input ??c????? abcab Output 2 -----Note----- In the first example the resulting string s is "winlosewinwinlwinwin" In the second example the resulting string s is "glorytoreorand". The last letter of the string can be arbitrary. In the third example occurrences of string t are overlapping. String s with maximal number of occurrences of t is "abcabcab".
{"inputs": ["a\nb\n", "a\nb\n", "a\nc\n", "ddddd\nd\n", "ww?ww\nw\n", "?????\nn\n", "ww?ww\nw\n", "?????\nn\n"], "outputs": ["0\n", "0", "0\n", "5\n", "5\n", "5\n", "5", "5"]}
426
88
coding
Solve the programming task below in a Python markdown code block. Do the following for a four-digit number N consisting of numbers 0-9. 1. Let L be the number obtained as a result of arranging the numerical values ​​of each of the N digits in descending order. 2. Let S be the number obtained as a result of arranging the numerical values ​​of each of the N digits in ascending order. 3. Let the difference L-S be the new N (end of one operation) 4. Repeat from 1. for the new N At this time, it is known that any four-digit number will eventually become 6174, unless all digits are the same number (0000, 1111, etc.). For example, when N = 2012 First time (N = 2012): L = 2210, S = 0122, L-S = 2088 Second time (N = 2088): L = 8820, S = 0288, L-S = 8532 Third time (N = 8532): L = 8532, S = 2358, L-S = 6174 And reach 6174 in 3 operations. Write a program that calculates how many operations will reach 6174 given a four-digit number consisting of the numbers 0-9. input The input consists of multiple datasets. The end of the input is indicated by 0000 on one line. Each dataset is given in the following format: N The dataset is one line and N (1 ≤ N ≤ 9999) indicates a four-digit number. If N <1000, the upper digit is padded with zeros. The number of datasets does not exceed 10000. output The number of operations to reach 6174 for each data set is output on one line. However, if a number with all the same digits is given as input, NA is output. Example Input 6174 2012 3333 0000 Output 0 3 NA
{"inputs": ["6174\n3729\n90\n0000", "6174\n990\n3333\n0000", "6174\n503\n4924\n0000", "6174\n3985\n3333\n0000", "6174\n1779\n3333\n0000", "6174\n1779\n2211\n0000", "6174\n2012\n3078\n0000", "6174\n3985\n5889\n0000"], "outputs": ["0\n3\n4\n", "0\n4\nNA\n", "0\n5\n4\n", "0\n3\nNA\n", "0\n6\nNA\n", "0\n6\n4\n", "0\n3\n2\n", "0\n3\n4\n"]}
480
234
coding
Solve the programming task below in a Python markdown code block. In my town ,there live a coder named Chef . He is a cool programmer . One day , he participate in a programming contest ,the contest give him only one problem . If he can’t solve the problem ,the problem setter will kill him . But the round allow you to help Chef. Can you save the life of Chef from problem setter ? :p You are given two point of a straightline in X and Y axis and they are A(x1 , y1) and B(x2 ,y2) . Problem setter will give you another point C(x3 , y3) . If C exist in AB straightline ,then print “YES” . Otherwise ,print “NO” in first line and print the minimum distance from C to AB straightline in second line . Please , save the life of Chef . Note : It is not possible that A and B point is similar . -----Input:----- The first line of the input contains a single integer t (1≤t≤100) — the number of test cases . Each test case starts with four integers( x1, y1 , x2 , y2 ) in first line . Next line contains a single number q ,the number of queries . Each query contains two integers ( x3 ,y3 ) -----Output:----- Print , q number of “YES” or “NO” (as it mentioned above) in each test case .For every test case , print “Test case : i ” ( 1<= i <=T ) -----Constraints----- -1000 <= x1 , y1 , x2 , y2 , x3 , y3 <= 1000 -----Sample Input:----- 2 3 5 6 5 2 4 5 6 8 3 4 7 10 1 7 4 -----Sample Output:----- Test case : 1 YES NO 3.000000 Test case : 2 NO 3.328201
{"inputs": ["2\n3 5 6 5\n2\n4 5\n6 8\n3 4 7 10\n1\n7 4"], "outputs": ["Test case : 1\nYES\nNO\n3.000000\nTest case : 2\nNO\n3.328201"]}
444
88
coding
Solve the programming task below in a Python markdown code block. Write function alternateCase which switch every letter in string from upper to lower and from lower to upper. E.g: Hello World -> hELLO wORLD Also feel free to reuse/extend the following starter code: ```python def alternateCase(s): ```
{"functional": "_inputs = [['ABC'], [''], [' '], ['Hello World'], ['cODEwARS'], ['i LIKE MAKING KATAS VERY MUCH'], ['HuMpTy DuMpTy SaT On A WaLl'], ['aBracaDabRa'], ['Hickory DICKORY dock'], ['Jack JUMPED over THE CaNdLeStIcK']]\n_outputs = [['abc'], [''], [' '], ['hELLO wORLD'], ['CodeWars'], ['I like making katas very much'], ['hUmPtY dUmPtY sAt oN a wAlL'], ['AbRACAdABrA'], ['hICKORY dickory DOCK'], ['jACK jumped OVER the cAnDlEsTiCk']]\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(alternateCase(*i), o[0])"}
66
305
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 length n. A split at an index i where 0 <= i <= n - 2 is called valid if the product of the first i + 1 elements and the product of the remaining elements are coprime. For example, if nums = [2, 3, 3], then a split at the index i = 0 is valid because 2 and 9 are coprime, while a split at the index i = 1 is not valid because 6 and 3 are not coprime. A split at the index i = 2 is not valid because i == n - 1. Return the smallest index i at which the array can be split validly or -1 if there is no such split. Two values val1 and val2 are coprime if gcd(val1, val2) == 1 where gcd(val1, val2) is the greatest common divisor of val1 and val2.   Please complete the following python code precisely: ```python class Solution: def findValidSplit(self, nums: List[int]) -> int: ```
{"functional": "def check(candidate):\n assert candidate(nums = [4,7,8,15,3,5]) == 2\n assert candidate(nums = [4,7,15,8,3,5]) == -1\n\n\ncheck(Solution().findValidSplit)"}
255
66
coding
Solve the programming task below in a Python markdown code block. Mike is trying rock climbing but he is awful at it. There are n holds on the wall, i-th hold is at height a_{i} off the ground. Besides, let the sequence a_{i} increase, that is, a_{i} < a_{i} + 1 for all i from 1 to n - 1; we will call such sequence a track. Mike thinks that the track a_1, ..., a_{n} has difficulty $d = \operatorname{max}_{1 \leq i \leq n - 1}(a_{i + 1} - a_{i})$. In other words, difficulty equals the maximum distance between two holds that are adjacent in height. Today Mike decided to cover the track with holds hanging on heights a_1, ..., a_{n}. To make the problem harder, Mike decided to remove one hold, that is, remove one element of the sequence (for example, if we take the sequence (1, 2, 3, 4, 5) and remove the third element from it, we obtain the sequence (1, 2, 4, 5)). However, as Mike is awful at climbing, he wants the final difficulty (i.e. the maximum difference of heights between adjacent holds after removing the hold) to be as small as possible among all possible options of removing a hold. The first and last holds must stay at their positions. Help Mike determine the minimum difficulty of the track after removing one hold. -----Input----- The first line contains a single integer n (3 ≤ n ≤ 100) — the number of holds. The next line contains n space-separated integers a_{i} (1 ≤ a_{i} ≤ 1000), where a_{i} is the height where the hold number i hangs. The sequence a_{i} is increasing (i.e. each element except for the first one is strictly larger than the previous one). -----Output----- Print a single number — the minimum difficulty of the track after removing a single hold. -----Examples----- Input 3 1 4 6 Output 5 Input 5 1 2 3 4 5 Output 2 Input 5 1 2 3 7 8 Output 4 -----Note----- In the first sample you can remove only the second hold, then the sequence looks like (1, 6), the maximum difference of the neighboring elements equals 5. In the second test after removing every hold the difficulty equals 2. In the third test you can obtain sequences (1, 3, 7, 8), (1, 2, 7, 8), (1, 2, 3, 8), for which the difficulty is 4, 5 and 5, respectively. Thus, after removing the second element we obtain the optimal answer — 4.
{"inputs": ["3\n1 4 6\n", "3\n2 4 6\n", "3\n1 4 6\n", "3\n2 7 1000\n", "5\n1 2 3 4 5\n", "5\n1 2 3 7 8\n", "3\n30 61 381\n", "3\n30 55 539\n"], "outputs": ["5\n", "4\n", "5\n", "998\n", "2\n", "4\n", "351\n", "509\n"]}
621
143
coding
Solve the programming task below in a Python markdown code block. Write a function `getDrinkByProfession`/`get_drink_by_profession()` that receives as input parameter a string, and produces outputs according to the following table: Input Output "Jabroni" "Patron Tequila" "School Counselor" "Anything with Alcohol"  "Programmer"  "Hipster Craft Beer"  "Bike Gang Member" "Moonshine"   "Politician" "Your tax dollars"   "Rapper" "Cristal"   *anything else* "Beer"  Note: *anything else* is the default case: if the input to the function is not any of the values in the table, then the return value should be "Beer." Make sure you cover the cases where certain words do not show up with correct capitalization. For example, getDrinkByProfession("pOLitiCIaN") should still return "Your tax dollars". Also feel free to reuse/extend the following starter code: ```python def get_drink_by_profession(param): ```
{"functional": "_inputs = [['jabrOni'], ['scHOOl counselor'], ['prOgramMer'], ['bike ganG member'], ['poLiTiCian'], ['rapper'], ['pundit'], ['Pug'], ['jabrOnI'], ['scHOOl COUnselor'], ['prOgramMeR'], ['bike GanG member'], ['poLiTiCiAN'], ['RAPPer'], ['punDIT'], ['pUg']]\n_outputs = [['Patron Tequila'], ['Anything with Alcohol'], ['Hipster Craft Beer'], ['Moonshine'], ['Your tax dollars'], ['Cristal'], ['Beer'], ['Beer'], ['Patron Tequila'], ['Anything with Alcohol'], ['Hipster Craft Beer'], ['Moonshine'], ['Your tax dollars'], ['Cristal'], ['Beer'], ['Beer']]\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(get_drink_by_profession(*i), o[0])"}
236
320
coding
Solve the programming task below in a Python markdown code block. Zonal Computing Olympiad 2012, 26 Nov 2011 We consider sequences of opening and closing brackets with two types of brackets, () and []. A bracket sequence is well-bracketed if we can pair up each opening bracket with a matching closing bracket in the usual sense. For instance, the sequences (), [] ([]) and []([]) are well-bracketed, while (, ()], (], )( and [(]) are not well-bracketed. In the last case, each opening bracket has a matching closing bracket and vice versa, but the intervals spanned by the different types of brackets intersect each other instead of being contained one within the other. The alternating depth of a well-bracketed sequence tells us the maximum number of times we switch between the two types of brackets when we have inner matched brackets enclosed within outer matched brackets. For instance, the alternating depth of (), [[[]]] and ()[][] is 1, the alternating depth of [()] and ()([]) is 2, the alternating depth of ([()]) and [()][(([]))] is 3, and so on. Given a well-bracketed sequence, we are interested in computing three quantities. - The alternating depth of the sequence. - The maximum number of symbols between any pair of matched brackets of the type ( and ), including both the outer brackets. - The maximum number of symbols between any pair of matched brackets of the type [ and ], including both the outer brackets. For instance, the alternating depth of (([]))[[[()]]] is 2, the maximum number of symbols between a matched pair () is 6 and the maximum number of symbols between a matched pair [] is 8. -----Input format----- The input consists of two lines. The first line is a single integer N, the length of the bracket sequence. Positions in the sequence are numbered 1,2,…,N. The second line is a sequence of N space-separated integers that encode the bracket expression as follows: 1 denotes an opening bracket (, 2 denotes a closing bracket ), 3 denotes an opening bracket [ and 4 denotes a closing bracket ]. Nothing other than 1, 2, 3 or 4 appears in the second line of input and the corresponding expression is guaranteed to be well-bracketed. -----Output format----- Your program should print 3 space-separated integers in a line, denoting the three quantities asked for in the following order: alternating depth, length of the maximum sequence between matching () brackets and length of the maximum sequence between matching [] brackets. -----Testdata----- You may assume that 2 ≤ N ≤ 105. In 30% of the test cases, 2 ≤ N ≤ 103. - Subtask 1 (30 marks) - Subtask 2 (70 marks) -----Sample Input----- 14 1 1 3 4 2 2 3 3 3 1 2 4 4 4 -----Sample Output----- 2 6 8
{"inputs": ["14\n1 1 3 4 2 2 3 3 3 1 2 4 4 4"], "outputs": ["2 6 8"]}
649
45
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 and a positive integer x. You are initially at position 0 in the array and you can visit other positions according to the following rules: If you are currently in position i, then you can move to any position j such that i < j. For each position i that you visit, you get a score of nums[i]. If you move from a position i to a position j and the parities of nums[i] and nums[j] differ, then you lose a score of x. Return the maximum total score you can get. Note that initially you have nums[0] points.   Please complete the following python code precisely: ```python class Solution: def maxScore(self, nums: List[int], x: int) -> int: ```
{"functional": "def check(candidate):\n assert candidate(nums = [2,3,6,1,9,2], x = 5) == 13\n assert candidate(nums = [2,4,6,8], x = 3) == 20\n\n\ncheck(Solution().maxScore)"}
182
71
coding
Solve the programming task below in a Python markdown code block. Laurel and Hardy have $n$ piles of chocolates with each pile containing some number of chocolates. The piles are arranged from left to right in a non decreasing order based on the number of chocolates in each pile. They play the following game. For every continuous subsequence of chocolate piles (at least 2 piles form a subsequence), Laurel and Hardy will play game on this subsequence of chocolate piles, Laurel plays first, and they play in turn. In one move, the player can choose one of the piles and remove at least one chocolate from it, but the non-decreasing order of the chocolate piles must be maintained. The last person to make a valid move wins. How many continuous subsequences of chocolate piles will Laurel win if both of them play optimally? The number of chocolates of each pile will be recovered after the game ends for each subsequences. Input Format The first line contains an integer $n$ denoting the number of piles. The second line contains the number of chocolates in each pile, arranged from left to right and separated by a single space between them. Constraints $2$ ≤ $n$ ≤ $\textbf{100000}$ $\mbox{I}$ ≤ $chocolates$ $\mbox{in}$ $\textit{each}$ $\textbf{pile}$ ≤ $\mathbf{10^{9}}$ Output Format A single integer denoting the number of continuous subsequences of chocolate piles in which Laurel will win. Sample Input 5 1 1 2 2 3 Sample Output 5 Explanation Of the 10 continuous-sub-sequence of chocolate piles, Laurel loses in [1,1], [1,1,2], [1,1,2,2], [1,2,2,3], [2,2] and wins in [1,1,2,2,3], [1,2], [1,2,2], [2,2,3] and [2,3] and hence 5.
{"inputs": ["5\n1 1 2 2 3\n"], "outputs": ["5\n"]}
446
24
coding
Solve the programming task below in a Python markdown code block. Vasya is sitting on an extremely boring math class. To have fun, he took a piece of paper and wrote out n numbers on a single line. After that, Vasya began to write out different ways to put pluses ("+") in the line between certain digits in the line so that the result was a correct arithmetic expression; formally, no two pluses in such a partition can stand together (between any two adjacent pluses there must be at least one digit), and no plus can stand at the beginning or the end of a line. For example, in the string 100500, ways 100500 (add no pluses), 1+00+500 or 10050+0 are correct, and ways 100++500, +1+0+0+5+0+0 or 100500+ are incorrect. The lesson was long, and Vasya has written all the correct ways to place exactly k pluses in a string of digits. At this point, he got caught having fun by a teacher and he was given the task to calculate the sum of all the resulting arithmetic expressions by the end of the lesson (when calculating the value of an expression the leading zeros should be ignored). As the answer can be large, Vasya is allowed to get only its remainder modulo 109 + 7. Help him! Input The first line contains two integers, n and k (0 ≤ k < n ≤ 105). The second line contains a string consisting of n digits. Output Print the answer to the problem modulo 109 + 7. Examples Input 3 1 108 Output 27 Input 3 2 108 Output 9 Note In the first sample the result equals (1 + 08) + (10 + 8) = 27. In the second sample the result equals 1 + 0 + 8 = 9.
{"inputs": ["1 0\n5\n", "1 0\n8\n", "1 0\n3\n", "3 1\n108\n", "3 2\n108\n", "5 2\n39923\n", "5 2\n20409\n", "5 2\n59455\n"], "outputs": ["5\n", "8\n", "3\n", "27\n", "9\n", "2667\n", "792\n", "2409\n"]}
445
127
coding
Solve the programming task below in a Python markdown code block. In Republic of Atcoder, there are N prefectures, and a total of M cities that belong to those prefectures. City i is established in year Y_i and belongs to Prefecture P_i. You can assume that there are no multiple cities that are established in the same year. It is decided to allocate a 12-digit ID number to each city. If City i is the x-th established city among the cities that belong to Prefecture i, the first six digits of the ID number of City i is P_i, and the last six digits of the ID number is x. Here, if P_i or x (or both) has less than six digits, zeros are added to the left until it has six digits. Find the ID numbers for all the cities. Note that there can be a prefecture with no cities. -----Constraints----- - 1 \leq N \leq 10^5 - 1 \leq M \leq 10^5 - 1 \leq P_i \leq N - 1 \leq Y_i \leq 10^9 - Y_i are all different. - All values in input are integers. -----Input----- Input is given from Standard Input in the following format: N M P_1 Y_1 : P_M Y_M -----Output----- Print the ID numbers for all the cities, in ascending order of indices (City 1, City 2, ...). -----Sample Input----- 2 3 1 32 2 63 1 12 -----Sample Output----- 000001000002 000002000001 000001000001 - As City 1 is the second established city among the cities that belong to Prefecture 1, its ID number is 000001000002. - As City 2 is the first established city among the cities that belong to Prefecture 2, its ID number is 000002000001. - As City 3 is the first established city among the cities that belong to Prefecture 1, its ID number is 000001000001.
{"inputs": ["1 1\n1 852958660\n", "2 3\n1 32\n2 63\n1 6", "4 3\n2 5\n2 49\n2 12", "4 3\n2 5\n4 49\n1 12", "2 3\n2 4\n1 7\n2 528", "5 2\n1 63\n4 63\n0 9", "2 3\n1 32\n2 63\n1 4", "2 3\n2 39\n2 0\n1 12"], "outputs": ["000001000001\n", "000001000002\n000002000001\n000001000001\n", "000002000001\n000002000003\n000002000002\n", "000002000001\n000004000001\n000001000001\n", "000002000001\n000001000001\n000002000002\n", "000001000001\n000004000001\n", "000001000002\n000002000001\n000001000001\n", "000002000002\n000002000001\n000001000001\n"]}
504
446
coding
Solve the programming task below in a Python markdown code block. Kepler’s Law states that the planets move around the sun in elliptical orbits with the sun at one focus. Kepler's 3rd law is The Law of Periods, according to which: The square of the time period of the planet is directly proportional to the cube of the semimajor axis of its orbit. You are given the Time periods (T_{1}, T_{2}) and Semimajor Axes (R_{1}, R_{2}) of two planets orbiting the same star. Please determine if the Law of Periods is satisfied or not, i.e, if the [constant of proportionality] of both planets is the same. Print "Yes" (without quotes) if the law is satisfied, else print "No". ------ 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 a single line of input, containing four space-separated integers T_{1}, T_{2}, R_{1}, R_{2}. ------ Output Format ------ For each test case, output a single line containing one string — "Yes" or "No" (without quotes); the answer to the problem. You may print each character of the answer in uppercase or lowercase (for example, the strings "yEs", "yes", "Yes" and "YES" will all be treated as identical). ------ Constraints ------ $1 ≤ T ≤ 10^{4}$ $1 ≤ T_{1},T_{2} ≤ 10$ $1 ≤ R_{1},R_{2} ≤ 10$ ------ subtasks ------ Subtask 1(100 points): Original constraints ----- Sample Input 1 ------ 3 1 1 1 1 1 2 3 4 1 8 2 8 ----- Sample Output 1 ------ Yes No Yes ----- explanation 1 ------ - Test Case $1$: $1^{2}/1^{3} = 1^{2}/1^{3}$ - Test Case $2$: $1^{2}/3^{3} \neq 2^{2}/4^{3}$ - Test Case $3$: $1^{2}/2^{3} = 8^{2}/8^{3}$
{"inputs": ["3\n1 1 1 1\n1 2 3 4\n1 8 2 8"], "outputs": ["Yes\nNo\nYes"]}
504
40
coding
Please solve the programming task below using a self-contained code snippet in a markdown code block. Given an array of strings words and an integer k, return the k most frequent strings. Return the answer sorted by the frequency from highest to lowest. Sort the words with the same frequency by their lexicographical order.   Please complete the following python code precisely: ```python class Solution: def topKFrequent(self, words: List[str], k: int) -> List[str]: ```
{"functional": "def check(candidate):\n assert candidate(words = [\"i\",\"love\",\"leetcode\",\"i\",\"love\",\"coding\"], k = 2) == [\"i\",\"love\"]\n assert candidate(words = [\"the\",\"day\",\"is\",\"sunny\",\"the\",\"the\",\"the\",\"sunny\",\"is\",\"is\"], k = 4) == [\"the\",\"is\",\"sunny\",\"day\"]\n\n\ncheck(Solution().topKFrequent)"}
98
103
coding
Solve the programming task below in a Python markdown code block. # Task: We define the "self reversed power sequence" as one shown below: Implement a function that takes 2 arguments (`ord max` and `num dig`), and finds the smallest term of the sequence whose index is less than or equal to `ord max`, and has exactly `num dig` number of digits. If there is a number with correct amount of digits, the result should be an array in the form: ```python [True, smallest found term] [False, -1] ``` ## Input range: ```python ord_max <= 1000 ``` ___ ## Examples: ```python min_length_num(5, 10) == [True, 10] # 10th term has 5 digits min_length_num(7, 11) == [False, -1] # no terms before the 13th one have 7 digits min_length_num(7, 14) == [True, 13] # 13th term is the first one which has 7 digits ``` Which you can see in the table below: ``` n-th Term Term Value 1 0 2 1 3 3 4 8 5 22 6 65 7 209 8 732 9 2780 10 11377 11 49863 12 232768 13 1151914 14 6018785 ``` ___ Enjoy it and happy coding!! Also feel free to reuse/extend the following starter code: ```python def min_length_num(num_dig, ord_max): ```
{"functional": "_inputs = [[5, 10], [7, 11], [7, 14], [8, 16], [10, 20]]\n_outputs = [[[True, 10]], [[False, -1]], [[True, 13]], [[True, 15]], [[True, 17]]]\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(min_length_num(*i), o[0])"}
406
219
coding
Solve the programming task below in a Python markdown code block. Chef is playing a game with two of his friends. In this game, each player chooses an integer between $1$ and $P$ inclusive. Let's denote the integers chosen by Chef, friend 1 and friend 2 by $i$, $j$ and $k$ respectively; then, Chef's score is (((Nmodi)modj)modk)modN.(((Nmodi)modj)modk)modN.(((N\,\mathrm{mod}\,i)\,\mathrm{mod}\,j)\,\mathrm{mod}\,k)\,\mathrm{mod}\,N\,. Chef wants to obtain the maximum possible score. Let's denote this maximum score by $M$. Find the number of ways to choose the triple $(i,j,k)$ so that Chef's score is equal to $M$. -----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 and only line of each test case contains two space-separated integers $N$ and $P$. -----Output----- For each test case, print a single line containing one integer — the number of ways to obtain the maximum score. -----Constraints----- - $1 \le T \le 10^6$ - $1 \le N \le P \le 10^6$ -----Subtasks----- Subtask #1 (10 points): - $1 \le T \le 100$ - $1 \le N \le P \le 100$ Subtask #2 (90 points): original constraints -----Example Input----- 2 4 4 3 4 -----Example Output----- 9 13 -----Explanation----- Example case 1: Chef's maximum possible score is $M = 1$. All possible values of $(i, j, k)$ such that the score is $1$ are $(3, 2, 2)$, $(3, 2, 3)$, $(3, 2, 4)$, $(3, 3, 2)$, $(3, 3, 3)$, $(3, 3, 4)$, $(3, 4, 2)$, $(3, 4, 3)$, $(3, 4, 4)$.
{"inputs": ["2\n4 4\n3 4"], "outputs": ["9\n13"]}
515
23
coding
Solve the programming task below in a Python markdown code block. William has an array of $n$ integers $a_1, a_2, \dots, a_n$. In one move he can swap two neighboring items. Two items $a_i$ and $a_j$ are considered neighboring if the condition $|i - j| = 1$ is satisfied. William wants you to calculate the minimal number of swaps he would need to perform to make it so that the array does not contain two neighboring items with the same parity. -----Input----- Each test contains multiple test cases. The first line contains the number of test cases $t$ ($1 \le t \le 10^4$). Description of the test cases follows. The first line of each test case contains an integer $n$ $(1 \le n \le 10^5)$ which is the total number of items in William's array. The second line contains $n$ integers $a_1, a_2, \dots, a_n$ $(1 \le a_i \le 10^9)$ which are William's array. It is guaranteed that the sum of $n$ over all test cases does not exceed $10^5$. -----Output----- For each test case output the minimal number of operations needed or $-1$ if it is impossible to get the array to a state when no neighboring numbers have the same parity. -----Examples----- Input 5 3 6 6 1 1 9 6 1 1 1 2 2 2 2 8 6 6 6 2 3 4 5 1 Output 1 0 3 -1 2 -----Note----- In the first test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $[6, 1, 6]$ In the second test case the array initially does not contain two neighboring items of the same parity. In the third test case the following sequence of operations would satisfy the requirements: swap(3, 4). Array after performing the operation: $[1, 1, 2, 1, 2, 2]$ swap(2, 3). Array after performing the operation: $[1, 2, 1, 1, 2, 2]$ swap(4, 5). Array after performing the operation: $[1, 2, 1, 2, 1, 2]$ In the fourth test case it is impossible to satisfy the requirements. In the fifth test case the following sequence of operations would satisfy the requirements: swap(2, 3). Array after performing the operation: $[6, 3, 2, 4, 5, 1]$ swap(4, 5). Array after performing the operation: $[6, 3, 2, 5, 4, 1]$
{"inputs": ["1\n3\n1 1 1\n", "1\n3\n1 1 1\n", "1\n3\n1 1 0\n", "1\n3\n0 3 0\n", "1\n3\n1 2 0\n", "1\n3\n1 3 0\n", "1\n3\n0 3 1\n", "1\n3\n0 2 1\n"], "outputs": ["-1\n", "-1\n", "1\n", "0\n", "1\n", "1\n", "1\n", "1\n"]}
631
135
coding
Please solve the programming task below using a self-contained code snippet in a markdown code block. A valid IP address consists of exactly four integers separated by single dots. Each integer is between 0 and 255 (inclusive) and cannot have leading zeros. For example, "0.1.2.201" and "192.168.1.1" are valid IP addresses, but "0.011.255.245", "192.168.1.312" and "192.168@1.1" are invalid IP addresses. Given a string s containing only digits, return all possible valid IP addresses that can be formed by inserting dots into s. You are not allowed to reorder or remove any digits in s. You may return the valid IP addresses in any order.   Please complete the following python code precisely: ```python class Solution: def restoreIpAddresses(self, s: str) -> List[str]: ```
{"functional": "def check(candidate):\n assert candidate(s = \"25525511135\") == [\"255.255.11.135\",\"255.255.111.35\"]\n assert candidate(s = \"0000\") == [\"0.0.0.0\"]\n assert candidate(s = \"101023\") == [\"1.0.10.23\",\"1.0.102.3\",\"10.1.0.23\",\"10.10.2.3\",\"101.0.2.3\"]\n\n\ncheck(Solution().restoreIpAddresses)"}
214
165
coding
Solve the programming task below in a Python markdown code block. John is developing a system to report fuel usage but needs help with the coding. First, he needs you to write a function that, given the actual consumption (in l/100 km) and remaining amount of petrol (in l), will give you how many kilometers you'll be able to drive. Second, he needs you to write a function that, given a distance (in km), a consumption (in l/100 km), and an amount of petrol (in l), will return one of the following: If you can't make the distance without refueling, it should return the message "You will need to refuel". If you can make the distance, the function will check every 100 km and produce an array with [1:kilometers already driven. 2: kilometers till end. 3: remaining amount of petrol] and return all the arrays inside another array ([[after 100km], [after 200km], [after 300km]...]) PLEASE NOTE: any of the values with decimals that you return should be rounded to 2 decimals. Also feel free to reuse/extend the following starter code: ```python def total_kilometers(cons, petrol): ```
{"functional": "_inputs = [[10, 60], [8, 0], [6.4, 54], [9.3, 87.3], [11.7, 63.4]]\n_outputs = [[600], [0], [843.75], [938.71], [541.88]]\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(total_kilometers(*i), o[0])"}
269
228
coding
Solve the programming task below in a Python markdown code block. Tree is a connected graph without cycles. A leaf of a tree is any vertex connected with exactly one other vertex. You are given a tree with n vertices and a root in the vertex 1. There is an ant in each leaf of the tree. In one second some ants can simultaneously go to the parent vertex from the vertex they were in. No two ants can be in the same vertex simultaneously except for the root of the tree. Find the minimal time required for all ants to be in the root of the tree. Note that at start the ants are only in the leaves of the tree. Input The first line contains integer n (2 ≤ n ≤ 5·105) — the number of vertices in the tree. Each of the next n - 1 lines contains two integers xi, yi (1 ≤ xi, yi ≤ n) — the ends of the i-th edge. It is guaranteed that you are given the correct undirected tree. Output Print the only integer t — the minimal time required for all ants to be in the root of the tree. Examples Input 12 1 2 1 3 1 4 2 5 2 6 3 7 3 8 3 9 8 10 8 11 8 12 Output 6 Input 2 2 1 Output 1
{"inputs": ["2\n2 1\n", "10\n1 3\n4 3\n10 4\n5 6\n6 2\n5 2\n7 5\n7 8\n7 9\n", "10\n1 3\n4 3\n10 4\n5 5\n6 2\n5 2\n7 5\n7 8\n7 9\n", "10\n1 3\n4 3\n10 4\n7 5\n6 2\n5 2\n7 5\n7 8\n7 9\n", "10\n1 3\n4 3\n10 6\n7 5\n6 2\n5 2\n7 5\n7 8\n7 9\n", "10\n1 3\n4 3\n9 4\n10 6\n6 2\n5 2\n7 6\n8 8\n7 9\n", "10\n1 3\n4 2\n10 4\n8 6\n6 2\n5 2\n7 6\n7 8\n7 9\n", "10\n1 3\n4 3\n10 4\n5 6\n6 2\n5 3\n7 5\n7 8\n7 9\n"], "outputs": ["1", "3\n", "3\n", "3\n", "2\n", "7\n", "1\n", "6\n"]}
301
339
coding
Solve the programming task below in a Python markdown code block. You are standing at point $(0,0)$ on an infinite plane. In one step, you can move from some point $(x_f,y_f)$ to any point $(x_t,y_t)$ as long as the Euclidean distance, $\sqrt{(x_f-x_t)^2+(y_f-y_t)^2}$, between the two points is either $\boldsymbol{a}$ or $\boldsymbol{b}$. In other words, each step you take must be exactly $\boldsymbol{a}$ or $\boldsymbol{b}$ in length. You are given $\textit{q}$ queries in the form of $\boldsymbol{a}$, $\boldsymbol{b}$, and $\boldsymbol{d}$. For each query, print the minimum number of steps it takes to get from point $(0,0)$ to point $\left(d,0\right)$ on a new line. Input Format The first line contains an integer, $\textit{q}$, denoting the number of queries you must process. Each of the $\textit{q}$ subsequent lines contains three space-separated integers describing the respective values of $\boldsymbol{a}$, $\boldsymbol{b}$, and $\boldsymbol{d}$ for a query. Constraints $1\leq q\leq10^5$ $1\leq a<b\leq10^9$ $0\leq d\leq10^9$ Output Format For each query, print the minimum number of steps necessary to get to point $\left(d,0\right)$ on a new line. Sample Input 0 3 2 3 1 1 2 0 3 4 11 Sample Output 0 2 0 3 Explanation 0 We perform the following $q=3$ queries: One optimal possible path requires two steps of length $\boldsymbol{a}=2$: $(0,0)\underset{2}{\longrightarrow}(\frac{1}{2},\frac{\sqrt{15}}{2})\underset{2}{\longrightarrow}(1,0)$. Thus, we print the number of steps, $2$, on a new line. The starting and destination points are both $(0,0)$, so we needn't take any steps. Thus, we print $\mbox{0}$ on a new line. One optimal possible path requires two steps of length $\boldsymbol{b}=4$ and one step of length $\boldsymbol{a}=3$: $(0,0)\underset{4}{\longrightarrow}(4,0)\underset{4}{\longrightarrow}(8,0)\underset{3}{\longrightarrow}(11,0)$. Thus, we print $3$ on a new line.
{"inputs": ["3\n2 3 1\n1 2 0\n3 4 11\n"], "outputs": ["2\n0\n3\n"]}
602
37
coding
Solve the programming task below in a Python markdown code block. Complete the function which takes two arguments and returns all numbers which are divisible by the given divisor. First argument is an array of `numbers` and the second is the `divisor`. ## Example ```python divisible_by([1, 2, 3, 4, 5, 6], 2) == [2, 4, 6] ``` Also feel free to reuse/extend the following starter code: ```python def divisible_by(numbers, divisor): ```
{"functional": "_inputs = [[[1, 2, 3, 4, 5, 6], 2], [[1, 2, 3, 4, 5, 6], 3], [[0, 1, 2, 3, 4, 5, 6], 4], [[0], 4], [[1, 3, 5], 2], [[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 1]]\n_outputs = [[[2, 4, 6]], [[3, 6]], [[0, 4]], [[0]], [[]], [[0, 1, 2, 3, 4, 5, 6, 7, 8, 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(divisible_by(*i), o[0])"}
115
330
coding
Please solve the programming task below using a self-contained code snippet in a markdown code block. Given an integer array nums and a positive integer k, return the most competitive subsequence of nums of size k. An array's subsequence is a resulting sequence obtained by erasing some (possibly zero) elements from the array. We define that a subsequence a is more competitive than a subsequence b (of the same length) if in the first position where a and b differ, subsequence a has a number less than the corresponding number in b. For example, [1,3,4] is more competitive than [1,3,5] because the first position they differ is at the final number, and 4 is less than 5.   Please complete the following python code precisely: ```python class Solution: def mostCompetitive(self, nums: List[int], k: int) -> List[int]: ```
{"functional": "def check(candidate):\n assert candidate(nums = [3,5,2,6], k = 2) == [2,6]\n assert candidate(nums = [2,4,3,3,5,4,9,6], k = 4) == [2,3,3,4]\n\n\ncheck(Solution().mostCompetitive)"}
188
84
coding
Solve the programming task below in a Python markdown code block. There is a game that uses numbers called "Fizz Buzz". In this game, multiple players count the numbers one by one, starting with 1, and each player says only one number after the previous player. At that time, you must say "Fizz" if it is divisible by 3, "Buzz" if it is divisible by 5, and "FizzBuzz" if it is divisible by both. For example, the first 16 statements are as follows: 1, 2, Fizz, 4, Buzz, Fizz, 7, 8, Fizz, Buzz, 11, Fizz, 13, 14, FizzBuzz, 16, ・ ・ ・ Taro decided to play "Fizz Buzz" with his friends. Taro and his colleagues decided the rules as follows. "The wrong person will drop out. The next person will start with the next number after the wrong number. That is, if you say 1, 2, 3, you made a mistake with 3, so you will start with 4." I play the game according to this rule, but because I am not used to the game, I sometimes do not notice that I made a mistake, and I cannot make a fair decision. So you decided to create a program that outputs the remaining people at the end of the set number of remarks so that Taro and his friends can enjoy this game. Create a program that inputs the number of players, the number of times spoken during the game, and each statement, and outputs the number of the remaining players at the end of the input in ascending order. However, the players are numbered from 1, and the order of speaking is also from the first player, and when the speaking is completed, the first player will speak again. If the player in turn has already dropped out, the next player will speak. Also, the program must ignore subsequent statements when the player is alone. Input A sequence of multiple datasets is given as input. The end of the input is indicated by two lines of zeros. Each dataset is given in the following format: m n s1 s2 :: sn The first line gives the number of players m (2 ≤ m ≤ 1000) and the number of remarks n (1 ≤ n ≤ 10000). The next n lines are given the i-th statement s1. si is an integer, Fizz, Buzz, or a string (up to 8 characters) that indicates FizzBuzz. The number of datasets does not exceed 50. Output For each input dataset, the number of the player remaining when the specified number of remarks is input is output in ascending order. Example Input 5 7 1 2 Fizz 4 Buzz 6 7 3 5 1 2 3 4 5 0 0 Output 2 3 4 5 1
{"inputs": ["5 7\n1\n0\nFizz\n4\nBuzz\n6\n7\n3 5\n1\n2\n3\n4\n5\n0 0", "5 7\n1\n0\nFizz\n4\nBuzz\n6\n2\n3 5\n1\n2\n3\n4\n5\n0 0", "5 7\n1\n0\nFizz\n2\nBuzz\n6\n2\n3 5\n1\n2\n4\n4\n8\n0 0", "5 7\n1\n0\nFizz\n2\nzuzB\n6\n2\n3 5\n1\n2\n4\n4\n8\n0 0", "5 7\n1\n2\nFizz\n4\nBuzz\n6\n7\n3 5\n1\n1\n3\n4\n5\n0 0", "5 7\n1\n0\nFizz\n2\nzuzB\n6\n2\n3 5\n1\n2\n4\n5\n8\n0 0", "5 7\n1\n0\nFizz\n2\nzuzB\n2\n2\n3 5\n2\n1\n4\n4\n8\n0 0", "5 7\n1\n1\nFizz\n4\nBu{z\n6\n7\n3 5\n1\n2\n3\n4\n5\n0 0"], "outputs": ["3 4 5\n1\n", "4 5\n1\n", "5\n1\n", "3\n1\n", "2 3 4 5\n1\n", "3\n2\n", "3\n3\n", "3 4\n1\n"]}
629
372
coding
Solve the programming task below in a Python markdown code block. During their New Year holidays, Alice and Bob play the following game using an array $a$ of $n$ integers: Players take turns, Alice moves first. Each turn a player chooses any element and removes it from the array. If Alice chooses even value, then she adds it to her score. If the chosen value is odd, Alice's score does not change. Similarly, if Bob chooses odd value, then he adds it to his score. If the chosen value is even, then Bob's score does not change. If there are no numbers left in the array, then the game ends. The player with the highest score wins. If the scores of the players are equal, then a draw is declared. For example, if $n = 4$ and $a = [5, 2, 7, 3]$, then the game could go as follows (there are other options): On the first move, Alice chooses $2$ and get two points. Her score is now $2$. The array $a$ is now $[5, 7, 3]$. On the second move, Bob chooses $5$ and get five points. His score is now $5$. The array $a$ is now $[7, 3]$. On the third move, Alice chooses $7$ and get no points. Her score is now $2$. The array $a$ is now $[3]$. On the last move, Bob chooses $3$ and get three points. His score is now $8$. The array $a$ is empty now. Since Bob has more points at the end of the game, he is the winner. You want to find out who will win if both players play optimally. Note that there may be duplicate numbers in the array. -----Input----- The first line contains an integer $t$ ($1 \le t \le 10^4$) — the number of test cases. Then $t$ test cases follow. The first line of each test case contains an integer $n$ ($1 \le n \le 2 \cdot 10^5$) — the number of elements in the array $a$. The next line contains $n$ integers $a_1, a_2, \ldots, a_n$ ($1 \le a_i \le 10^9$) — the array $a$ used to play the game. 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 on a separate line: "Alice" if Alice wins with the optimal play; "Bob" if Bob wins with the optimal play; "Tie", if a tie is declared during the optimal play. -----Examples----- Input 4 4 5 2 7 3 3 3 2 1 4 2 2 2 2 2 7 8 Output Bob Tie Alice Alice -----Note----- None
{"inputs": ["2\n3\n1 1 234872\n4\n5 2 7 3\n", "2\n3\n1 1 234872\n4\n5 2 7 3\n", "2\n3\n1 1 234872\n4\n5 2 7 2\n", "2\n3\n1 1 199277\n4\n2 0 7 3\n", "2\n3\n1 1 234872\n4\n1 0 7 2\n", "2\n3\n1 1 199277\n4\n2 0 7 1\n", "2\n3\n1 2 234872\n4\n5 2 7 2\n", "2\n3\n2 1 234872\n4\n5 2 7 3\n"], "outputs": ["Alice\nBob\n", "Alice\nBob\n", "Alice\nBob\n", "Bob\nBob\n", "Alice\nTie\n", "Bob\nTie\n", "Alice\nBob\n", "Alice\nBob\n"]}
650
272
coding
Solve the programming task below in a Python markdown code block. Cities on a map are connected by a number of roads. The number of roads between each city is in an array and city ${0}$ is the starting location. The number of roads from city ${0}$ to city ${1}$ is the first value in the array, from city ${1}$ to city $2$ is the second, and so on. How many paths are there from city ${0}$ to the last city in the list, modulo $1234567$? Example $n=4$ $routes=[3,4,5]$ There are $3$ roads to city ${1}$, ${4}$ roads to city $2$ and $5$ roads to city $3$. The total number of roads is $3\times4\times5\mod1234567=60$. Note Pass all the towns T_{i} for i=1 to n-1 in numerical order to reach T_{n}. Function Description Complete the connectingTowns function in the editor below. connectingTowns has the following parameters: int n: the number of towns int routes[n-1]: the number of routes between towns Returns int: the total number of routes, modulo 1234567. Input Format The first line contains an integer T, T test-cases follow. Each test-case has 2 lines. The first line contains an integer N (the number of towns). The second line contains N - 1 space separated integers where the i^{th} integer denotes the number of routes, N_{i}, from the town T_{i} to T_{i+1} Constraints 1 <= T<=1000 2< N <=100 1 <= routes[i] <=1000 Sample Input 2 3 1 3 4 2 2 2 Sample Output 3 8 Explanation Case 1: 1 route from T_{1} to T_{2}, 3 routes from T_{2} to T_{3}, hence only 3 routes. Case 2: There are 2 routes from each city to the next, hence 2 * 2 * 2 = 8.
{"inputs": ["2\n3\n1 3\n4\n2 2 2\n"], "outputs": ["3\n8\n"]}
499
30
coding
Solve the programming task below in a Python markdown code block. There is a strange counter. At the first second, it displays the number $3$. Each second, the number displayed by decrements by $\mbox{1}$ until it reaches $\mbox{1}$. In next second, the timer resets to $2\times\textbf{the initial number for the prior cycle}$ and continues counting down. The diagram below shows the counter values for each time $\boldsymbol{\boldsymbol{t}}$ in the first three cycles: Find and print the value displayed by the counter at time $\boldsymbol{\boldsymbol{t}}$. Function Description Complete the strangeCounter function in the editor below. strangeCounter has the following parameter(s): int t: an integer Returns int: the value displayed at time $\boldsymbol{\boldsymbol{t}}$ Input Format A single integer, the value of $\boldsymbol{\boldsymbol{t}}$. Constraints $1\leq t\leq10^{12}$ Subtask $1\leq t\leq10^5$ for $60\%$ of the maximum score. Sample Input 4 Sample Output 6 Explanation Time $t=4$ marks the beginning of the second cycle. It is double the number displayed at the beginning of the first cycle:$2\times3=6$. This is shown in the diagram in the problem statement.
{"inputs": ["4\n"], "outputs": ["6\n"]}
311
14
coding
Please solve the programming task below using a self-contained code snippet in a markdown code block. Given a list of non-negative integers nums, arrange them such that they form the largest number and return it. Since the result may be very large, so you need to return a string instead of an integer.   Please complete the following python code precisely: ```python class Solution: def largestNumber(self, nums: List[int]) -> str: ```
{"functional": "def check(candidate):\n assert candidate(nums = [10,2]) == \"210\"\n assert candidate(nums = [3,30,34,5,9]) == \"9534330\"\n\n\ncheck(Solution().largestNumber)"}
90
67
coding
Solve the programming task below in a Python markdown code block. Read problems statements in Mandarin Chinese, Russian and Vietnamese as well. Andrash study in Uzhland National University. Now is the time of exam results. Andrash similar to other students, hopes that this scores in the exam could fetch him a scholarship/stipendium for his studies. There are following simple rules to receive stipendium: University follows 5 point grading system. In an exam, a student can receive any score from 2 to 5. 2 is called an F grade, meaning that student has failed that exam. Student should not have fail any of the exams. Student must obtain a full score in some of his/her exams to show that he/she is excellent in some of the subjects. He/She must have a grade point average not less than 4.0 You are given information regarding the exams and how Andrash performed in those. Can you help him figure out whether he will receive the stipendium or not!! ------ Input ------ The first line of input contains a single integer T denoting the number of test cases. This will be followed by T test cases. The first line of each test case contains an integer N denoting the number of examinations. The next line of each test case contains N space separated integers denoting Andrash's score for each exam. ------ Output ------ For each of the T test cases, output a single line - "Yes" (without quotes) if Andrash will receive stipendium, or "No" (without quotes) - otherwise. ------ ------ Constraints ----- $ 1 ≤ T ≤ 40 $ $ Let A[i] denote Andrash's score for i-th exam $ Subtask #1: 20 points $1 ≤ N ≤ 100 $ $2 ≤ A[i] ≤ 5$ Subtask #2: 20 points $ 1 ≤ N ≤ 10^{5} $ $ 3 ≤ A[i] ≤ 5 $ Subtask #3: 60 points $ 1 ≤ N ≤ 10^{5} $ $ 2 ≤ A[i] ≤ 5 $ ----- Sample Input 1 ------ 2 5 3 5 4 4 3 5 3 4 4 4 5 ----- Sample Output 1 ------ No Yes ----- explanation 1 ------ Example case 1. Student's average grade point score is 3.8 which makes him/her unqualified for obtaining the stipend. Example case 2. Student satisfies all the criteria for getting stipend.
{"inputs": ["2\n5\n3 5 4 4 3\n5\n3 4 4 4 5"], "outputs": ["No\nYes"]}
552
38
coding
Solve the programming task below in a Python markdown code block. The HR manager was disappointed again. The last applicant failed the interview the same way as 24 previous ones. "Do I give such a hard task?" — the HR manager thought. "Just raise number 5 to the power of n and get last two digits of the number. Yes, of course, n can be rather big, and one cannot find the power using a calculator, but we need people who are able to think, not just follow the instructions." Could you pass the interview in the machine vision company in IT City? -----Input----- The only line of the input contains a single integer n (2 ≤ n ≤ 2·10^18) — the power in which you need to raise number 5. -----Output----- Output the last two digits of 5^{n} without spaces between them. -----Examples----- Input 2 Output 25
{"inputs": ["2\n", "7\n", "7\n", "3\n", "5\n", "8\n", "6\n", "9\n"], "outputs": ["25", "25", "25\n", "25\n", "25\n", "25\n", "25\n", "25\n"]}
193
76
coding
Solve the programming task below in a Python markdown code block. For this kata, you are given three points ```(x1,y1,z1)```, ```(x2,y2,z2)```, and ```(x3,y3,z3)``` that lie on a straight line in 3-dimensional space. You have to figure out which point lies in between the other two. Your function should return 1, 2, or 3 to indicate which point is the in-between one. Also feel free to reuse/extend the following starter code: ```python def middle_point(x1, y1, z1, x2, y2, z2, x3, y3, z3): ```
{"functional": "_inputs = [[1, 2, 3, 4, 5, 6, 7, 8, 9], [0, 2, 0, 6, -2, 8, 3, 0, 4], [0.25, 0.5, 0.75, 3.25, -0.5, -0.25, 1.0, 0.25, 0.5], [1, 0, 4, 5, 0, 6, -7, 0, 0], [-1, 0, 2, -2, 4, -1, -3, 8, -4]]\n_outputs = [[2], [3], [3], [1], [2]]\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(middle_point(*i), o[0])"}
150
322
coding
Please solve the programming task below using a self-contained code snippet in a markdown code block. A value-equal string is a string where all characters are the same. For example, "1111" and "33" are value-equal strings. In contrast, "123" is not a value-equal string. Given a digit string s, decompose the string into some number of consecutive value-equal substrings where exactly one substring has a length of 2 and the remaining substrings have a length of 3. Return true if you can decompose s according to the above rules. Otherwise, return false. A substring is a contiguous sequence of characters in a string.   Please complete the following python code precisely: ```python class Solution: def isDecomposable(self, s: str) -> bool: ```
{"functional": "def check(candidate):\n assert candidate(s = \"000111000\") == False\n assert candidate(s = \"00011111222\") == True\n assert candidate(s = \"01110002223300\") == False\n\n\ncheck(Solution().isDecomposable)"}
173
85
coding
Solve the programming task below in a Python markdown code block. You have $a$ coins of value $n$ and $b$ coins of value $1$. You always pay in exact change, so you want to know if there exist such $x$ and $y$ that if you take $x$ ($0 \le x \le a$) coins of value $n$ and $y$ ($0 \le y \le b$) coins of value $1$, then the total value of taken coins will be $S$. You have to answer $q$ independent test cases. -----Input----- The first line of the input contains one integer $q$ ($1 \le q \le 10^4$) — the number of test cases. Then $q$ test cases follow. The only line of the test case contains four integers $a$, $b$, $n$ and $S$ ($1 \le a, b, n, S \le 10^9$) — the number of coins of value $n$, the number of coins of value $1$, the value $n$ and the required total value. -----Output----- For the $i$-th test case print the answer on it — YES (without quotes) if there exist such $x$ and $y$ that if you take $x$ coins of value $n$ and $y$ coins of value $1$, then the total value of taken coins will be $S$, and NO otherwise. You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES will all be recognized as positive answer). -----Example----- Input 4 1 2 3 4 1 2 3 6 5 2 6 27 3 3 5 18 Output YES NO NO YES
{"inputs": ["1\n2 2 3 55\n", "1\n2 2 3 43\n", "1\n2 2 3 33\n", "1\n2 2 4 33\n", "1\n2 4 4 33\n", "1\n2 4 5 33\n", "1\n2 8 5 33\n", "1\n1 8 5 33\n"], "outputs": ["NO\n", "NO\n", "NO\n", "NO\n", "NO\n", "NO\n", "NO\n", "NO\n"]}
398
142
coding
Please solve the programming task below using a self-contained code snippet in a markdown code block. You are given a sorted unique integer array nums. A range [a,b] is the set of all integers from a to b (inclusive). Return the smallest sorted list of ranges that cover all the numbers in the array exactly. That is, each element of nums is covered by exactly one of the ranges, and there is no integer x such that x is in one of the ranges but not in nums. Each range [a,b] in the list should be output as: "a->b" if a != b "a" if a == b   Please complete the following python code precisely: ```python class Solution: def summaryRanges(self, nums: List[int]) -> List[str]: ```
{"functional": "def check(candidate):\n assert candidate(nums = [0,1,2,4,5,7]) == [\"0->2\",\"4->5\",\"7\"]\n assert candidate(nums = [0,2,3,4,6,8,9]) == [\"0\",\"2->4\",\"6\",\"8->9\"]\n\n\ncheck(Solution().summaryRanges)"}
161
89
coding
Please solve the programming task below using a self-contained code snippet in a markdown code block. There are n people standing in a queue, and they numbered from 0 to n - 1 in left to right order. You are given an array heights of distinct integers where heights[i] represents the height of the ith person. A person can see another person to their right in the queue if everybody in between is shorter than both of them. More formally, the ith person can see the jth person if i < j and min(heights[i], heights[j]) > max(heights[i+1], heights[i+2], ..., heights[j-1]). Return an array answer of length n where answer[i] is the number of people the ith person can see to their right in the queue.   Please complete the following python code precisely: ```python class Solution: def canSeePersonsCount(self, heights: List[int]) -> List[int]: ```
{"functional": "def check(candidate):\n assert candidate(heights = [10,6,8,5,11,9]) == [3,1,2,1,1,0]\n assert candidate(heights = [5,1,2,3,10]) == [4,1,1,1,0]\n\n\ncheck(Solution().canSeePersonsCount)"}
193
88
coding
Solve the programming task below in a Python markdown code block. Scheduling is how the processor decides which jobs(processes) get to use the processor and for how long. This can cause a lot of problems. Like a really long process taking the entire CPU and freezing all the other processes. One solution is Shortest Job First(SJF), which today you will be implementing. SJF works by, well, letting the shortest jobs take the CPU first. If the jobs are the same size then it is First In First Out (FIFO). The idea is that the shorter jobs will finish quicker, so theoretically jobs won't get frozen because of large jobs. (In practice they're frozen because of small jobs). You will be implementing: ```python def SJF(jobs, index) ``` It takes in: 1. "jobs" a non-empty array of positive integers. They represent the clock-cycles(cc) needed to finish the job. 2. "index" a positive integer. That represents the job we're interested in. SJF returns: 1. A positive integer representing the cc it takes to complete the job at index. Here's an example: ``` SJF([3, 10, 20, 1, 2], 0) at 0cc [3, 10, 20, 1, 2] jobs[3] starts at 1cc [3, 10, 20, 0, 2] jobs[3] finishes, jobs[4] starts at 3cc [3, 10, 20, 0, 0] jobs[4] finishes, jobs[0] starts at 6cc [0, 10, 20, 0, 0] jobs[0] finishes ``` so: ``` SJF([3,10,20,1,2], 0) == 6 ``` Also feel free to reuse/extend the following starter code: ```python def SJF(jobs, index): ```
{"functional": "_inputs = [[[100], 0], [[3, 10, 20, 1, 2], 0], [[3, 10, 20, 1, 2], 1], [[3, 10, 10, 20, 1, 2], 1], [[3, 10, 10, 20, 1, 2], 2], [[3, 10, 20, 1, 2, 3], 5], [[3, 10, 20, 1, 2, 10, 10], 5]]\n_outputs = [[100], [6], [16], [16], [26], [9], [26]]\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(SJF(*i), o[0])"}
437
323
coding
Solve the programming task below in a Python markdown code block. As part of this Kata, you need to find the length of the sequence in an array, between the first and the second occurrence of a specified number. For example, for a given array `arr` [0, -3, 7, 4, 0, 3, 7, 9] Finding length between two `7`s like lengthOfSequence([0, -3, 7, 4, 0, 3, 7, 9], 7) would return `5`. For sake of simplicity, there will only be numbers (positive or negative) in the supplied array. If there are less or more than two occurrences of the number to search for, return `0`, or in Haskell, `Nothing`. Also feel free to reuse/extend the following starter code: ```python def length_of_sequence(arr,n): ```
{"functional": "_inputs = [[[1], 0], [[1], 1], [[-7, 3, -7, -7, 2, 1], -7], [[-7, 3, -7, -7, 2, -7], -7]]\n_outputs = [[0], [0], [0], [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(length_of_sequence(*i), o[0])"}
196
217
coding
Solve the programming task below in a Python markdown code block. You are given an integer sequence A=(A_{1}, A_{2},\dots, A_{N}) of length N and an integer M such that 0 ≤ M < \sum\limits_{i=1}^N A_{i}. An integer sequence B=(B_{1}, B_{2},\dots, B_{N}) of length N is called *good* if: 0 ≤ B_{i} ≤ A_{i} for each 1≤ i ≤ N B_{1}+ B_{2}+\dots+B_{N}=M Find the maximum value of \gcd(A_{1}-B_{1},A_{2}-B_{2},\dots,A_{N}-B_{N}) over all good sequences B. Here, \gcd denotes the [greatest common divisor]. Note: \gcd(a,b,c) = \gcd(a,\gcd(b,c)) and \gcd(a,0)=\gcd(0,a)=a. ------ 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. - The first line of each test case contains two space-separated integers N, M. - The second line of each test case contains N space-separated integers A_{1}, A_{2}, \dots, A_{N}. ------ Output Format ------ For each test case, print a single line containing one integer — the maximum value of \gcd(A_{1}-B_{1},A_{2}-B_{2},\dots,A_{N}-B_{N}) over all good sequences B. ------ Constraints ------ $1 ≤ T ≤ 10$ $1 ≤ N ≤ 10^{5}$ $1 ≤ A_{i} ≤ 10^{5}$ $0 ≤ M < \sum\limits_{i=1}^N A_{i}$ ------ subtasks ------ Subtask #1 (50 points): $1 ≤ N ≤ 10^{4}$ Subtask #2 (50 points): Original constraints ----- Sample Input 1 ------ 4 4 4 1 3 5 7 4 4 5 5 5 5 4 0 4 6 9 12 6 10 15 9 3 8 14 17 ----- Sample Output 1 ------ 3 4 1 7 ----- explanation 1 ------ Test case $1$: The optimal strategy is to take $B=(1,0,2,1)$. The answer is $\gcd(1-1,3-0,5-2,7-1)=\gcd(0,3,3,6)=3$. Test case $2$: The optimal strategy is to take $B=(1,1,1,1)$. The answer is $\gcd(5-1,5-1,5-1,5-1)=\gcd(4,4,4,4)=4$.
{"inputs": ["4\n4 4\n1 3 5 7\n4 4\n5 5 5 5\n4 0\n4 6 9 12\n6 10\n15 9 3 8 14 17"], "outputs": ["3\n4\n1\n7\n"]}
655
76
coding
Solve the programming task below in a Python markdown code block. There are 3^N people dancing in circle. We denote with 0,1,\dots, 3^{N}-1 the positions in the circle, starting from an arbitrary position and going around clockwise. Initially each position in the circle is occupied by one person. The people are going to dance on two kinds of songs: salsa and rumba. * When a salsa is played, the person in position i goes to position j, where j is the number obtained replacing all digits 1 with 2 and all digits 2 with 1 when reading i in base 3 (e.g., the person in position 46 goes to position 65). * When a rumba is played, the person in position i moves to position i+1 (with the identification 3^N = 0). You are given a string T=T_1T_2\cdots T_{|T|} such that T_i=`S` if the i-th song is a salsa and T_i=`R` if it is a rumba. After all the songs have been played, the person that initially was in position i is in position P_i. Compute the array P_0,P_1,\dots, P_{3^N-1}. Constraints * 1 \le N \le 12 * 1 \le |T| \le 200,000 * T contains only the characters `S` and `R`. Input Input is given from Standard Input in the following format: N T Output You should print on Standard Output: P_0 P_1 \cdots P_{3^N-1} Output You should print on Standard Output: P_0 P_1 \cdots P_{3^N-1} Examples Input 1 SRS Output 2 0 1 Input 2 RRSRSSSSR Output 3 8 1 0 5 7 6 2 4 Input 3 SRSRRSRRRSRRRR Output 23 9 22 8 3 7 20 24 19 5 18 4 17 12 16 2 6 1 14 0 13 26 21 25 11 15 10
{"inputs": ["1\nRRS", "1\nSRR", "1\nSSR", "1\nRSR", "1\nRRR", "1\nRSS", "1\nSRS", "2\nSRRRSSSSR"], "outputs": ["1 0 2 ", "2 1 0 ", "1 2 0 ", "0 2 1 ", "0 1 2 ", "1 2 0 ", "2 0 1", "4 6 5 1 3 2 7 0 8 "]}
519
125
coding
Please solve the programming task below using a self-contained code snippet in a markdown code block. There are n people in a line queuing to buy tickets, where the 0th person is at the front of the line and the (n - 1)th person is at the back of the line. You are given a 0-indexed integer array tickets of length n where the number of tickets that the ith person would like to buy is tickets[i]. Each person takes exactly 1 second to buy a ticket. A person can only buy 1 ticket at a time and has to go back to the end of the line (which happens instantaneously) in order to buy more tickets. If a person does not have any tickets left to buy, the person will leave the line. Return the time taken for the person initially at position k (0-indexed) to finish buying tickets.   Please complete the following python code precisely: ```python class Solution: def timeRequiredToBuy(self, tickets: List[int], k: int) -> int: ```
{"functional": "def check(candidate):\n assert candidate(tickets = [2,3,2], k = 2) == 6\n assert candidate(tickets = [5,1,1,1], k = 0) == 8\n\n\ncheck(Solution().timeRequiredToBuy)"}
216
67
coding
Solve the programming task below in a Python markdown code block. Determine whether a text T includes a pattern P. Your program should answer for given queries consisting of P_i. Constraints * 1 ≤ length of T ≤ 1000000 * 1 ≤ length of P_i ≤ 1000 * 1 ≤ Q ≤ 10000 * The input consists of alphabetical characters and digits Input In the first line, a text T is given. In the second line, an integer Q denoting the number of queries is given. In the following Q lines, the patterns P_i are given respectively. Output For each question, print 1 if the text includes P_i, or print 0 otherwise. Example Input aabaaa 4 aa ba bb xyz Output 1 1 0 0
{"inputs": ["aabaaa\n4\nab\nba\nbb\nxyz", "aabaaa\n4\nab\nba\nba\nxyz", "aabaaa\n4\nba\nbb\nac\nzyx", "aabaaa\n4\nca\nab\nba\nzyx", "aacaaa\n4\nba\nb`\nac\nzyx", "aacaaa\n4\nca\nb`\nac\nzyx", "aabaaa\n4\na`\nab\nca\nyzx", "aadaaa\n4\nca\nb`\nca\nzyx"], "outputs": ["1\n1\n0\n0\n", "1\n1\n1\n0\n", "1\n0\n0\n0\n", "0\n1\n1\n0\n", "0\n0\n1\n0\n", "1\n0\n1\n0\n", "0\n1\n0\n0\n", "0\n0\n0\n0\n"]}
185
209
coding
Solve the programming task below in a Python markdown code block. Akaki, a patissier, can make N kinds of doughnut using only a certain powder called "Okashi no Moto" (literally "material of pastry", simply called Moto below) as ingredient. These doughnuts are called Doughnut 1, Doughnut 2, ..., Doughnut N. In order to make one Doughnut i (1 ≤ i ≤ N), she needs to consume m_i grams of Moto. She cannot make a non-integer number of doughnuts, such as 0.5 doughnuts. Now, she has X grams of Moto. She decides to make as many doughnuts as possible for a party tonight. However, since the tastes of the guests differ, she will obey the following condition: - For each of the N kinds of doughnuts, make at least one doughnut of that kind. At most how many doughnuts can be made here? She does not necessarily need to consume all of her Moto. Also, under the constraints of this problem, it is always possible to obey the condition. -----Constraints----- - 2 ≤ N ≤ 100 - 1 ≤ m_i ≤ 1000 - m_1 + m_2 + ... + m_N ≤ X ≤ 10^5 - All values in input are integers. -----Input----- Input is given from Standard Input in the following format: N X m_1 m_2 : m_N -----Output----- Print the maximum number of doughnuts that can be made under the condition. -----Sample Input----- 3 1000 120 100 140 -----Sample Output----- 9 She has 1000 grams of Moto and can make three kinds of doughnuts. If she makes one doughnut for each of the three kinds, she consumes 120 + 100 + 140 = 360 grams of Moto. From the 640 grams of Moto that remains here, she can make additional six Doughnuts 2. This is how she can made a total of nine doughnuts, which is the maximum.
{"inputs": ["3 0010\n3\n101\n5", "3 1\n575\n3\n9\n15", "3 1\n668\n3\n9\n15", "3 2\n668\n3\n9\n15", "3 2\n668\n6\n9\n15", "3 2\n668\n1\n9\n15", "3 1010\n17\n101\n6", "3 0010\n17\n101\n6"], "outputs": ["-30\n", "-193\n", "-224\n", "-223\n", "-111\n", "-673\n", "150\n", "-16\n"]}
456
183
coding
Solve the programming task below in a Python markdown code block. You managed to send your friend to queue for tickets in your stead, but there is a catch: he will get there only if you tell him how much that is going to take. And everybody can only take one ticket at a time, then they go back in the last position of the queue if they need more (or go home if they are fine). Each ticket takes one minutes to emit, the queue is well disciplined, [Brit-style](https://www.codewars.com/kata/english-beggars), and so it moves smoothly, with no waste of time. You will be given an array/list/vector with all the people queuing and the *initial* position of your buddy, so for example, knowing that your friend is in the third position (that we will consider equal to the index, `2`: he is the guy that wants 3 tickets!) and the initial queue is `[2, 5, 3, 4, 6]`. The first dude gets his ticket and the queue goes now like this `[5, 3, 4, 6, 1]`, then `[3, 4, 6, 1, 4]` and so on. In the end, our buddy will be queuing for 12 minutes, true story! Build a function to compute it, resting assured that only positive integers are going to be there and you will be always given a valid index; but we also want to go to pretty popular events, so be ready for big queues with people getting plenty of tickets. [[hard core version](https://www.codewars.com/kata/queue-time-counter-hard-core-version/solutions/javascript) now available if you don't want the "easy" kata!] Also feel free to reuse/extend the following starter code: ```python def queue(queuers,pos): ```
{"functional": "_inputs = [[[2, 5, 3, 6, 4], 0], [[2, 5, 3, 6, 4], 1], [[2, 5, 3, 6, 4], 2], [[2, 5, 3, 6, 4], 3], [[2, 5, 3, 6, 4], 4]]\n_outputs = [[6], [18], [12], [20], [17]]\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(queue(*i), o[0])"}
393
256
coding
Please solve the programming task below using a self-contained code snippet in a markdown code block. You are working in a ball factory where you have n balls numbered from lowLimit up to highLimit inclusive (i.e., n == highLimit - lowLimit + 1), and an infinite number of boxes numbered from 1 to infinity. Your job at this factory is to put each ball in the box with a number equal to the sum of digits of the ball's number. For example, the ball number 321 will be put in the box number 3 + 2 + 1 = 6 and the ball number 10 will be put in the box number 1 + 0 = 1. Given two integers lowLimit and highLimit, return the number of balls in the box with the most balls.   Please complete the following python code precisely: ```python class Solution: def countBalls(self, lowLimit: int, highLimit: int) -> int: ```
{"functional": "def check(candidate):\n assert candidate(lowLimit = 1, highLimit = 10) == 2\n assert candidate(lowLimit = 5, highLimit = 15) == 2\n assert candidate(lowLimit = 19, highLimit = 28) == 2\n\n\ncheck(Solution().countBalls)"}
204
81
coding
Solve the programming task below in a Python markdown code block. Dima liked the present he got from Inna very much. He liked the present he got from Seryozha even more. Dima felt so grateful to Inna about the present that he decided to buy her n hares. Inna was very happy. She lined up the hares in a row, numbered them from 1 to n from left to right and started feeding them with carrots. Inna was determined to feed each hare exactly once. But in what order should she feed them? Inna noticed that each hare radiates joy when she feeds it. And the joy of the specific hare depends on whether Inna fed its adjacent hares before feeding it. Inna knows how much joy a hare radiates if it eats when either both of his adjacent hares are hungry, or one of the adjacent hares is full (that is, has been fed), or both of the adjacent hares are full. Please note that hares number 1 and n don't have a left and a right-adjacent hare correspondingly, so they can never have two full adjacent hares. Help Inna maximize the total joy the hares radiate. :) -----Input----- The first line of the input contains integer n (1 ≤ n ≤ 3000) — the number of hares. Then three lines follow, each line has n integers. The first line contains integers a_1 a_2 ... a_{n}. The second line contains b_1, b_2, ..., b_{n}. The third line contains c_1, c_2, ..., c_{n}. The following limits are fulfilled: 0 ≤ a_{i}, b_{i}, c_{i} ≤ 10^5. Number a_{i} in the first line shows the joy that hare number i gets if his adjacent hares are both hungry. Number b_{i} in the second line shows the joy that hare number i radiates if he has exactly one full adjacent hare. Number с_{i} in the third line shows the joy that hare number i radiates if both his adjacent hares are full. -----Output----- In a single line, print the maximum possible total joy of the hares Inna can get by feeding them. -----Examples----- Input 4 1 2 3 4 4 3 2 1 0 1 1 0 Output 13 Input 7 8 5 7 6 1 8 9 2 7 9 5 4 3 1 2 3 3 4 1 1 3 Output 44 Input 3 1 1 1 1 2 1 1 1 1 Output 4
{"inputs": ["1\n0\n1\n4\n", "1\n7\n1\n7\n", "1\n0\n0\n0\n", "1\n0\n1\n4\n", "1\n0\n0\n0\n", "1\n7\n1\n7\n", "1\n0\n2\n4\n", "1\n7\n1\n3\n"], "outputs": ["0\n", "7\n", "0\n", "0\n", "0\n", "7\n", "0\n", "7\n"]}
590
118
coding
Solve the programming task below in a Python markdown code block. Chefland is a grid with N$N$ rows and M$M$ columns. Each cell of this grid is either empty or contains a house. The distance between a pair of houses is the Manhattan distance between the cells containing them. For each d$d$ between 1$1$ and N+M−2$N+M-2$ inclusive, Chef wants to calculate the number of unordered pairs of distinct houses with distance equal to d$d$. Please help him! -----Input----- - The first line of the input contains a single integer T$T$ denoting the number of test cases. The description of T$T$ test cases follows. - The first line of each test case contains two space-separated integers N$N$ and M$M$. - N$N$ lines follow. For each i$i$ (1≤i≤N$1 \le i \le N$), the i$i$-th of these lines contains a binary string with length M$M$; for each j$j$ (1≤j≤M$1 \le j \le M$), the j$j$-th character of this string is '1' if the cell in the i$i$-th row and j$j$-th column contains a house or '0' if it is empty. -----Output----- For each test case, print a single line containing N+M−2$N+M-2$ space-separated integers. For each valid i$i$, the i$i$-th integer should denote the number of pairs with distance i$i$. -----Constraints----- - 1≤T≤3$1 \le T \le 3$ - 2≤N,M≤300$2 \le N, M \le 300$ -----Subtasks----- Subtask #1 (50 points): N,M≤50$N, M \le 50$ Subtask #2 (50 points): original constraints -----Example Input----- 1 3 4 0011 0000 0100 -----Example Output----- 1 0 1 1 0
{"inputs": ["1\n3 4\n0011\n0000\n0100"], "outputs": ["1 0 1 1 0"]}
461
39
coding
Solve the programming task below in a Python markdown code block. Vasya is sitting on an extremely boring math class. To have fun, he took a piece of paper and wrote out n numbers on a single line. After that, Vasya began to write out different ways to put pluses ("+") in the line between certain digits in the line so that the result was a correct arithmetic expression; formally, no two pluses in such a partition can stand together (between any two adjacent pluses there must be at least one digit), and no plus can stand at the beginning or the end of a line. For example, in the string 100500, ways 100500 (add no pluses), 1+00+500 or 10050+0 are correct, and ways 100++500, +1+0+0+5+0+0 or 100500+ are incorrect. The lesson was long, and Vasya has written all the correct ways to place exactly k pluses in a string of digits. At this point, he got caught having fun by a teacher and he was given the task to calculate the sum of all the resulting arithmetic expressions by the end of the lesson (when calculating the value of an expression the leading zeros should be ignored). As the answer can be large, Vasya is allowed to get only its remainder modulo 10^9 + 7. Help him! -----Input----- The first line contains two integers, n and k (0 ≤ k < n ≤ 10^5). The second line contains a string consisting of n digits. -----Output----- Print the answer to the problem modulo 10^9 + 7. -----Examples----- Input 3 1 108 Output 27 Input 3 2 108 Output 9 -----Note----- In the first sample the result equals (1 + 08) + (10 + 8) = 27. In the second sample the result equals 1 + 0 + 8 = 9.
{"inputs": ["1 0\n5\n", "1 0\n5\n", "3 1\n108\n", "3 2\n108\n", "3 1\n159\n", "3 1\n177\n", "3 1\n297\n", "3 1\n196\n"], "outputs": ["5", "5\n", "27", "9", "84\n", "102\n", "135\n", "122\n"]}
452
119
coding
Solve the programming task below in a Python markdown code block. There are two small spaceship, surrounded by two groups of enemy larger spaceships. The space is a two-dimensional plane, and one group of the enemy spaceships is positioned in such a way that they all have integer $y$-coordinates, and their $x$-coordinate is equal to $-100$, while the second group is positioned in such a way that they all have integer $y$-coordinates, and their $x$-coordinate is equal to $100$. Each spaceship in both groups will simultaneously shoot two laser shots (infinite ray that destroys any spaceship it touches), one towards each of the small spaceships, all at the same time. The small spaceships will be able to avoid all the laser shots, and now want to position themselves at some locations with $x=0$ (with not necessarily integer $y$-coordinates), such that the rays shot at them would destroy as many of the enemy spaceships as possible. Find the largest numbers of spaceships that can be destroyed this way, assuming that the enemy spaceships can't avoid laser shots. -----Input----- The first line contains two integers $n$ and $m$ ($1 \le n, m \le 60$), the number of enemy spaceships with $x = -100$ and the number of enemy spaceships with $x = 100$, respectively. The second line contains $n$ integers $y_{1,1}, y_{1,2}, \ldots, y_{1,n}$ ($|y_{1,i}| \le 10\,000$) — the $y$-coordinates of the spaceships in the first group. The third line contains $m$ integers $y_{2,1}, y_{2,2}, \ldots, y_{2,m}$ ($|y_{2,i}| \le 10\,000$) — the $y$-coordinates of the spaceships in the second group. The $y$ coordinates are not guaranteed to be unique, even within a group. -----Output----- Print a single integer – the largest number of enemy spaceships that can be destroyed. -----Examples----- Input 3 9 1 2 3 1 2 3 7 8 9 11 12 13 Output 9 Input 5 5 1 2 3 4 5 1 2 3 4 5 Output 10 -----Note----- In the first example the first spaceship can be positioned at $(0, 2)$, and the second – at $(0, 7)$. This way all the enemy spaceships in the first group and $6$ out of $9$ spaceships in the second group will be destroyed. In the second example the first spaceship can be positioned at $(0, 3)$, and the second can be positioned anywhere, it will be sufficient to destroy all the enemy spaceships.
{"inputs": ["1 1\n0\n0\n", "1 1\n1\n1\n", "1 1\n0\n1\n", "1 1\n5\n5\n", "1 1\n0\n0\n", "1 1\n5\n5\n", "1 1\n0\n1\n", "1 1\n1\n1\n"], "outputs": ["2\n", "2\n", "2\n", "2\n", "2\n", "2\n", "2\n", "2\n"]}
639
118
coding
Solve the programming task below in a Python markdown code block. # Task The game starts with `n` people standing in a circle. The presenter counts `m` people starting with the first one, and gives `1` coin to each of them. The rest of the players receive `2` coins each. After that, the last person who received `1` coin leaves the circle, giving everything he had to the next participant (who will also be considered "the first in the circle" in the next round). This process continues until only 1 person remains. Determine the `number` of this person and how many `coins` he has at the end of the game. The result should be a pair of values in the format: `[person, coins]`. ## Example: ``` n = 8, m = 3 People 1 2 3 1 2 ∙ 1 2 ∙ ∙ 2 ∙ ∙ 2 ∙ ∙ ∙ ∙ ∙ ∙ ∙ 8 4 => 8 4 => 8 4 => 8 4 => 8 4 => 8 4 => ∙ 4 => 7 7 6 5 7 6 5 7 ∙ 5 7 ∙ 5 7 ∙ ∙ 7 ∙ ∙ 7 ∙ ∙ Coins 0 0 0 1 1 ∙ 3 3 ∙ ∙ 9 ∙ ∙ 10 ∙ ∙ ∙ ∙ ∙ ∙ ∙ 0 0 => 2 3 => 4 4 => 5 6 => 7 7 => 8 20 => ∙ 30 => 51 0 0 0 2 2 2 7 ∙ 3 8 ∙ 5 16 ∙ ∙ 17 ∙ ∙ 18 ∙ ∙ ``` ## Notes: * The presenter can do several full circles during one counting. * In this case, the same person will receive `1` coin multiple times, i.e. no matter how many people are left in the circle, at least `m` coins will always be distributed among the participants during the round. * If a person had already received `1` coin (possibly multiple times), he won't receive any additional `2` coins **at once(!)** during that round. * People are counted starting with `1`. * `m` can be **bigger** than `n` at start Also feel free to reuse/extend the following starter code: ```python def find_last(n, m): ```
{"functional": "_inputs = [[5, 1], [8, 3], [75, 34], [82, 49], [73, 38], [86, 71], [61, 17], [42, 38], [29, 5], [64, 49], [61, 20], [88, 52]]\n_outputs = [[[5, 24]], [[7, 51]], [[35, 4238]], [[48, 5091]], [[61, 3996]], [[10, 6275]], [[26, 3000]], [[12, 1578]], [[28, 740]], [[43, 3327]], [[32, 2922]], [[59, 5856]]]\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_last(*i), o[0])"}
653
352
coding
Solve the programming task below in a Python markdown code block. You are given two integers, $N$ and $\mbox{M}$. Count the number of strings of length $N$ (under the alphabet set of size $\mbox{M}$) that doesn't contain any palindromic string of the length greater than $\mbox{1}$ as a consecutive substring. Input Format Several test cases will be given to you in a single file. The first line of the input will contain a single integer, ${T}$, the number of test cases. Then there will be ${T}$ lines, each containing two space-separated integers, $N$ and $\mbox{M}$, denoting a single test case. The meanings of $N$ and $\mbox{M}$ are described in the Problem Statement above. Output Format For each test case, output a single integer - the answer to the corresponding test case. This number can be huge, so output it modulo $10^9+7$. Constraints $1\leq T\leq10^5$ $1\leq N,M\leq10^9$ Sample Input 2 2 2 2 3 Sample Output 2 6 Explanation For the 1^{st} testcase, we have an alphabet of size M = 2. For the sake of simplicity, let's consider the alphabet as [A, B]. We can construct four strings of size N = 2 using these letters. AA AB BA BB Out of these, we have two strings, AB and BA, that satisfy the condition of not having a palindromic string of length greater than 1. Hence, the answer 2. For the 2^{nd} test case, we have an alphabet of size M = 3. For the sake of simplicity, let's consider the alphabet as [A, B, C]. We can construct nine strings of size N = 2 using these letters. AA AB AC BA BB BC CA CB CC Save AA, BB, and CC, all the strings satisfy the given condition; hence, the answer 6.
{"inputs": ["2\n2 2\n2 3\n"], "outputs": ["2\n6\n"]}
463
24
coding
Please solve the programming task below using a self-contained code snippet in a markdown code block. Given a pattern and a string s, return true if s matches the pattern. A string s matches a pattern if there is some bijective mapping of single characters to non-empty strings such that if each character in pattern is replaced by the string it maps to, then the resulting string is s. A bijective mapping means that no two characters map to the same string, and no character maps to two different strings.   Please complete the following python code precisely: ```python class Solution: def wordPatternMatch(self, pattern: str, s: str) -> bool: ```
{"functional": "def check(candidate):\n assert candidate(pattern = \"abab\", s = \"redblueredblue\") == True\n assert candidate(pattern = \"aaaa\", s = \"asdasdasdasd\") == True\n assert candidate(pattern = \"aabb\", s = \"xyzabcxzyabc\") == False\n\n\ncheck(Solution().wordPatternMatch)"}
135
82
coding
Solve the programming task below in a Python markdown code block. Freddy has a really fat left pinky finger, and every time Freddy tries to type an ```A```, he accidentally hits the CapsLock key! Given a string that Freddy wants to type, emulate the keyboard misses where each ```A``` supposedly pressed is replaced with CapsLock, and return the string that Freddy actually types. It doesn't matter if the ```A``` in the string is capitalized or not. When CapsLock is enabled, capitalization is reversed, but punctuation is not affected. Examples: ``` "The quick brown fox jumps over the lazy dog." -> "The quick brown fox jumps over the lZY DOG." "The end of the institution, maintenance, and administration of government, is to secure the existence of the body politic, to protect it, and to furnish the individuals who compose it with the power of enjoying in safety and tranquillity their natural rights, and the blessings of life: and whenever these great objects are not obtained, the people have a right to alter the government, and to take measures necessary for their safety, prosperity and happiness." -> "The end of the institution, mINTENnce, ND dministrTION OF GOVERNMENT, IS TO SECURE THE EXISTENCE OF THE BODY POLITIC, TO PROTECT IT, nd to furnish the individuLS WHO COMPOSE IT WITH THE POWER OF ENJOYING IN Sfety ND TRnquillity their nTURl rights, ND THE BLESSINGS OF LIFE: nd whenever these greT OBJECTS re not obtINED, THE PEOPLE Hve RIGHT TO lter the government, ND TO Tke meSURES NECESSry for their sFETY, PROSPERITY nd hPPINESS." "aAaaaaAaaaAAaAa" -> "" ``` **Note!** If (Caps Lock is Enabled) and then you (HOLD Shift + alpha character) it will always be the reverse Examples: ``` (Caps Lock Enabled) + (HOLD Shift + Press 'b') = b (Caps Lock Disabled) + (HOLD Shift + Press 'b') = B ``` If the given string is `""`, the answer should be evident. Happy coding! ~~~if:fortran *NOTE: In Fortran, your returned string is* **not** *permitted to contain any unnecessary leading/trailing whitespace.* ~~~ (Adapted from https://codegolf.stackexchange.com/questions/158132/no-a-just-caps-lock) Also feel free to reuse/extend the following starter code: ```python def fat_fingers(string): ```
{"functional": "_inputs = [['aAaaaaAaaaAAaAa'], ['The end of the institution, maintenance, and administration of government, is to secure the existence of the body politic, to protect it, and to furnish the individuals who compose it with the power of enjoying in safety and tranquillity their natural rights, and the blessings of life: and whenever these great objects are not obtained, the people have a right to alter the government, and to take measures necessary for their safety, prosperity and happiness.'], ['a99&a6/<a}']]\n_outputs = [[''], ['The end of the institution, mINTENnce, ND dministrTION OF GOVERNMENT, IS TO SECURE THE EXISTENCE OF THE BODY POLITIC, TO PROTECT IT, nd to furnish the individuLS WHO COMPOSE IT WITH THE POWER OF ENJOYING IN Sfety ND TRnquillity their nTURl rights, ND THE BLESSINGS OF LIFE: nd whenever these greT OBJECTS re not obtINED, THE PEOPLE Hve RIGHT TO lter the government, ND TO Tke meSURES NECESSry for their sFETY, PROSPERITY nd hPPINESS.'], ['99&6/<}']]\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(fat_fingers(*i), o[0])"}
554
405
coding
Solve the programming task below in a Python markdown code block. For a given positive integer n denote its k-rounding as the minimum positive integer x, such that x ends with k or more zeros in base 10 and is divisible by n. For example, 4-rounding of 375 is 375·80 = 30000. 30000 is the minimum integer such that it ends with 4 or more zeros and is divisible by 375. Write a program that will perform the k-rounding of n. -----Input----- The only line contains two integers n and k (1 ≤ n ≤ 10^9, 0 ≤ k ≤ 8). -----Output----- Print the k-rounding of n. -----Examples----- Input 375 4 Output 30000 Input 10000 1 Output 10000 Input 38101 0 Output 38101 Input 123456789 8 Output 12345678900000000
{"inputs": ["1 0\n", "2 0\n", "3 0\n", "1 1\n", "2 1\n", "3 1\n", "4 1\n", "5 1\n"], "outputs": ["1\n", "2\n", "3\n", "10\n", "10\n", "30\n", "20\n", "10\n"]}
251
91
coding
Please solve the programming task below using a self-contained code snippet in a markdown code block. A valid encoding of an array of words is any reference string s and array of indices indices such that: words.length == indices.length The reference string s ends with the '#' character. For each index indices[i], the substring of s starting from indices[i] and up to (but not including) the next '#' character is equal to words[i]. Given an array of words, return the length of the shortest reference string s possible of any valid encoding of words.   Please complete the following python code precisely: ```python class Solution: def minimumLengthEncoding(self, words: List[str]) -> int: ```
{"functional": "def check(candidate):\n assert candidate(words = [\"time\", \"me\", \"bell\"]) == 10\n assert candidate(words = [\"t\"]) == 2\n\n\ncheck(Solution().minimumLengthEncoding)"}
142
55
coding
Solve the programming task below in a Python markdown code block. There are n incoming messages for Vasya. The i-th message is going to be received after t_{i} minutes. Each message has a cost, which equals to A initially. After being received, the cost of a message decreases by B each minute (it can become negative). Vasya can read any message after receiving it at any moment of time. After reading the message, Vasya's bank account receives the current cost of this message. Initially, Vasya's bank account is at 0. Also, each minute Vasya's bank account receives C·k, where k is the amount of received but unread messages. Vasya's messages are very important to him, and because of that he wants to have all messages read after T minutes. Determine the maximum amount of money Vasya's bank account can hold after T minutes. -----Input----- The first line contains five integers n, A, B, C and T (1 ≤ n, A, B, C, T ≤ 1000). The second string contains n integers t_{i} (1 ≤ t_{i} ≤ T). -----Output----- Output one integer  — the answer to the problem. -----Examples----- Input 4 5 5 3 5 1 5 5 4 Output 20 Input 5 3 1 1 3 2 2 2 1 1 Output 15 Input 5 5 3 4 5 1 2 3 4 5 Output 35 -----Note----- In the first sample the messages must be read immediately after receiving, Vasya receives A points for each message, n·A = 20 in total. In the second sample the messages can be read at any integer moment. In the third sample messages must be read at the moment T. This way Vasya has 1, 2, 3, 4 and 0 unread messages at the corresponding minutes, he gets 40 points for them. When reading messages, he receives (5 - 4·3) + (5 - 3·3) + (5 - 2·3) + (5 - 1·3) + 5 = - 5 points. This is 35 in total.
{"inputs": ["1 6 4 3 9\n2\n", "1 6 4 3 9\n2\n", "4 5 5 3 5\n1 5 5 4\n", "4 5 5 3 5\n2 5 5 4\n", "4 5 5 3 5\n1 5 5 4\n", "5 3 1 1 3\n2 2 2 1 1\n", "5 5 3 4 5\n1 2 3 4 5\n", "5 6 1 1 3\n2 2 2 1 1\n"], "outputs": ["6\n", "6\n", "20\n", "20\n", "20\n", "15\n", "35\n", "30\n"]}
502
198
coding
Solve the programming task below in a Python markdown code block. We have N balance beams numbered 1 to N. The length of each beam is 1 meters. Snuke walks on Beam i at a speed of 1/A_i meters per second, and Ringo walks on Beam i at a speed of 1/B_i meters per second. Snuke and Ringo will play the following game: * First, Snuke connects the N beams in any order of his choice and makes a long beam of length N meters. * Then, Snuke starts at the left end of the long beam. At the same time, Ringo starts at a point chosen uniformly at random on the long beam. Both of them walk to the right end of the long beam. * Snuke wins if and only if he catches up to Ringo before Ringo reaches the right end of the long beam. That is, Snuke wins if there is a moment when Snuke and Ringo stand at the same position, and Ringo wins otherwise. Find the probability that Snuke wins when Snuke arranges the N beams so that the probability of his winning is maximized. This probability is a rational number, so we ask you to represent it as an irreducible fraction P/Q (to represent 0, use P=0, Q=1). Constraints * 1 \leq N \leq 10^5 * 1 \leq A_i,B_i \leq 10^9 * All values in input are integers. Input Input is given from Standard Input in the following format: N A_1 B_1 A_2 B_2 \vdots A_N B_N Output Print the numerator and denominator of the irreducible fraction that represents the maximum probability of Snuke's winning. Examples Input 2 3 2 1 2 Output 1 4 Input 4 1 5 4 7 2 1 8 4 Output 1 2 Input 3 4 1 5 2 6 3 Output 0 1 Input 10 866111664 178537096 705445072 318106937 472381277 579910117 353498483 865935868 383133839 231371336 378371075 681212831 304570952 16537461 955719384 267238505 844917655 218662351 550309930 62731178 Output 697461712 2899550585
{"inputs": ["2\n0 2\n1 2", "2\n2 1\n2 6", "2\n3 2\n1 2", "3\n1 1\n5 2\n6 3", "3\n1 1\n6 0\n1 3", "3\n4 1\n5 2\n6 3", "3\n1 2\n5 0\n14 3", "3\n1 4\n5 0\n14 3"], "outputs": ["3 4", "2 3", "1 4", "0 1", "4 9", "0 1", "1 6", "1 4"]}
681
156
coding
Please solve the programming task below using a self-contained code snippet in a markdown code block. Given an integer n, return true if it is a power of four. Otherwise, return false. An integer n is a power of four, if there exists an integer x such that n == 4x.   Please complete the following python code precisely: ```python class Solution: def isPowerOfFour(self, n: int) -> bool: ```
{"functional": "def check(candidate):\n assert candidate(n = 16) == True\n assert candidate(n = 5) == False\n assert candidate(n = 1) == True\n\n\ncheck(Solution().isPowerOfFour)"}
92
55
coding
Please solve the programming task below using a self-contained code snippet in a markdown code block. You are given two 0-indexed integer arrays nums1 and nums2 of length n. Let's define another 0-indexed integer array, nums3, of length n. For each index i in the range [0, n - 1], you can assign either nums1[i] or nums2[i] to nums3[i]. Your task is to maximize the length of the longest non-decreasing subarray in nums3 by choosing its values optimally. Return an integer representing the length of the longest non-decreasing subarray in nums3. Note: A subarray is a contiguous non-empty sequence of elements within an array.   Please complete the following python code precisely: ```python class Solution: def maxNonDecreasingLength(self, nums1: List[int], nums2: List[int]) -> int: ```
{"functional": "def check(candidate):\n assert candidate(nums1 = [2,3,1], nums2 = [1,2,1]) == 2\n assert candidate(nums1 = [1,3,2,1], nums2 = [2,2,3,4]) == 4\n assert candidate(nums1 = [1,1], nums2 = [2,2]) == 2\n\n\ncheck(Solution().maxNonDecreasingLength)"}
188
103
coding
Solve the programming task below in a Python markdown code block. A factory produces thimbles in bulk. Typically, it can produce up to a thimbles a day. However, some of the machinery is defective, so it can currently only produce b thimbles each day. The factory intends to choose a k-day period to do maintenance and construction; it cannot produce any thimbles during this time, but will be restored to its full production of a thimbles per day after the k days are complete. Initially, no orders are pending. The factory receives updates of the form di, ai, indicating that ai new orders have been placed for the di-th day. Each order requires a single thimble to be produced on precisely the specified day. The factory may opt to fill as many or as few of the orders in a single batch as it likes. As orders come in, the factory owner would like to know the maximum number of orders he will be able to fill if he starts repairs on a given day pi. Help the owner answer his questions. Input The first line contains five integers n, k, a, b, and q (1 ≤ k ≤ n ≤ 200 000, 1 ≤ b < a ≤ 10 000, 1 ≤ q ≤ 200 000) — the number of days, the length of the repair time, the production rates of the factory, and the number of updates, respectively. The next q lines contain the descriptions of the queries. Each query is of one of the following two forms: * 1 di ai (1 ≤ di ≤ n, 1 ≤ ai ≤ 10 000), representing an update of ai orders on day di, or * 2 pi (1 ≤ pi ≤ n - k + 1), representing a question: at the moment, how many orders could be filled if the factory decided to commence repairs on day pi? It's guaranteed that the input will contain at least one query of the second type. Output For each query of the second type, print a line containing a single integer — the maximum number of orders that the factory can fill over all n days. Examples Input 5 2 2 1 8 1 1 2 1 5 3 1 2 1 2 2 1 4 2 1 3 2 2 1 2 3 Output 3 6 4 Input 5 4 10 1 6 1 1 5 1 5 5 1 3 2 1 5 2 2 1 2 2 Output 7 1 Note Consider the first sample. We produce up to 1 thimble a day currently and will produce up to 2 thimbles a day after repairs. Repairs take 2 days. For the first question, we are able to fill 1 order on day 1, no orders on days 2 and 3 since we are repairing, no orders on day 4 since no thimbles have been ordered for that day, and 2 orders for day 5 since we are limited to our production capacity, for a total of 3 orders filled. For the third question, we are able to fill 1 order on day 1, 1 order on day 2, and 2 orders on day 5, for a total of 4 orders.
{"inputs": ["1 1 2 1 1\n2 1\n", "1 1 2 2 1\n2 1\n", "1 1 2 3 1\n2 1\n", "1 1 1 1 1\n2 1\n", "1 1 0 2 1\n2 1\n", "1 1 2 6 1\n2 1\n", "2 1 1 1 1\n2 1\n", "2 1 2 6 1\n2 1\n"], "outputs": ["0\n", "0\n", "0\n", "0\n", "0\n", "0\n", "0\n", "0\n"]}
737
166