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.
The number ```12``` is the first number in having six divisors, they are: ```1, 2, 3, 4, 6 and 12.```
Your challenge for this kata is to find the minimum number that has a certain number of divisors.
For this purpose we have to create the function
```find_min_num() or findMinNum() or similar in the other languages```
that receives the wanted number of divisors ```num_div```, and outputs the smallest number having an amount of divisors equals to ```num_div```.
Let's see some cases:
```
find_min_num(10) = 48 # divisors are: 1, 2, 3, 4, 6, 8, 12, 16, 24 and 48
find_min_num(12) = 60
```
In this kata all the tests will be with ```numDiv < 80```
(There will be a next kata with numDiv < 10000, Find the First Number Having a Certain Number of Divisors II, should have the help of number theory)
Enjoy it and happy coding!
(Memoization is advisable)
Also feel free to reuse/extend the following starter code:
```python
def find_min_num(d, n=1):
```
|
{"functional": "_inputs = [[6], [10], [12], [13]]\n_outputs = [[12], [48], [60], [4096]]\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_min_num(*i), o[0])"}
| 300
| 182
|
coding
|
Solve the programming task below in a Python markdown code block.
Algorithmic predicament - Bug Fixing #9
Oh no! Timmy's algorithim has gone wrong! help Timmy fix his algorithim!
Task
Your task is to fix timmy's algorithim so it returns the group name with the highest total age.
You will receive two groups of `people` objects, with two properties `name` and `age`. The name property is a string and the age property is a number.
Your goal is to make the total the age of all people having the same name through both groups and return the name of the one with the highest age. If two names have the same total age return the first alphabetical name.
Also feel free to reuse/extend the following starter code:
```python
def highest_age(group1,group2):
```
|
{"functional": "_inputs = [[[{'name': 'kay', 'age': 1}, {'name': 'john', 'age': 13}, {'name': 'kay', 'age': 76}], [{'name': 'john', 'age': 1}, {'name': 'alice', 'age': 77}]], [[{'name': 'kay', 'age': 1}, {'name': 'john', 'age': 13}, {'name': 'kay', 'age': 76}], [{'name': 'john', 'age': 1}, {'name': 'alice', 'age': 76}]], [[{'name': 'kay', 'age': 1}, {'name': 'john', 'age': 130}, {'name': 'kay', 'age': 76}], [{'name': 'john', 'age': 1}, {'name': 'alice', 'age': 76}]], [[{'name': 'kay', 'age': 1}, {'name': 'john', 'age': 130}, {'name': 'kay', 'age': 130}], [{'name': 'john', 'age': 1}, {'name': 'alice', 'age': 76}]], [[{'name': 'kay', 'age': 2}, {'name': 'john', 'age': 130}, {'name': 'kay', 'age': 130}], [{'name': 'john', 'age': 1}, {'name': 'alice', 'age': 76}]]]\n_outputs = [['alice'], ['kay'], ['john'], ['john'], ['kay']]\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(highest_age(*i), o[0])"}
| 179
| 506
|
coding
|
Solve the programming task below in a Python markdown code block.
Aayush has recently started teaching Latin Dance. Today, he will be teaching Salsa. For this, he needs to divide the people attending his dance class into pairs. Usually in Salsa, the dance pairs consist of one girl and one boy. But Aayush doesn't find this convention very interesting. He is rather more concerned about the IQ of people who are members of the same pair. Precisely, if the sums of digits of the IQ score of the two people forming a pair are co-prime, then the pair will be $\text{awkward}$ according to Aayush. For example IQ scores 12 (1+2=3) and 22 (2+2=4) form an awkward pair.
The IQ scores of all the people attending the Salsa class are pairwise distinct. The lowest IQ is $\text{L}$ and the largest IQ is $\text{R}$. Moreover, there are exactly $\text{R-L+1}$ people attending the Salsa class. Aayush wants to know the number of ways in which an awkward pair can be formed modulo $10^{9}+7$. Two ways are different if at least one of the members in the pairs formed is different.
------ Input ------
The first line contains a single interger $\text{T}$ - the number of testcases.
Each of the following $\text{T}$ lines contains two space separated integers $\text{L}$ and $\text{R}$, as described in the problem.
------ Output ------
For every test case, print an integer answer modulo $10^{9}+7$.
------ Constraints ------
$1 ≤ \text{T} ≤ 10$
$1 ≤ \text{L, R} ≤ 10^{18}$
------ Sample Input ------
2
5 8
7 10
------ Sample Output ------
5
6
|
{"inputs": ["2\n5 8\n7 10"], "outputs": ["5\n6\n"]}
| 412
| 24
|
coding
|
Solve the programming task below in a Python markdown code block.
You are given $n$ elements numbered from $1$ to $n$, the element $i$ has value $a_i$ and color $c_i$, initially, $c_i = 0$ for all $i$.
The following operation can be applied:
Select three elements $i$, $j$ and $k$ ($1 \leq i < j < k \leq n$), such that $c_i$, $c_j$ and $c_k$ are all equal to $0$ and $a_i = a_k$, then set $c_j = 1$.
Find the maximum value of $\sum\limits_{i=1}^n{c_i}$ that can be obtained after applying the given operation any number of times.
-----Input-----
The first line contains an integer $n$ ($3 \leq n \leq 2 \cdot 10^5$) — the number of elements.
The second line consists of $n$ integers $a_1, a_2, \dots, a_n$ ($1 \leq a_i \leq n$), where $a_i$ is the value of the $i$-th element.
-----Output-----
Print a single integer in a line — the maximum value of $\sum\limits_{i=1}^n{c_i}$ that can be obtained after applying the given operation any number of times.
-----Examples-----
Input
7
1 2 1 2 7 4 7
Output
2
Input
13
1 2 3 2 1 3 3 4 5 5 5 4 7
Output
7
-----Note-----
In the first test, it is possible to apply the following operations in order:
|
{"inputs": ["3\n1 1 2\n", "3\n1 1 1\n", "3\n1 2 1\n", "3\n1 2 2\n", "3\n1 2 3\n", "7\n1 2 1 2 7 4 7\n", "13\n1 2 3 2 1 3 3 4 5 5 5 4 7\n"], "outputs": ["0\n", "1\n", "1\n", "0\n", "0\n", "2\n", "7\n"]}
| 386
| 133
|
coding
|
Solve the programming task below in a Python markdown code block.
Given three distinct integers $a$, $b$, and $c$, find the medium number between all of them.
The medium number is the number that is neither the minimum nor the maximum of the given three numbers.
For example, the median of $5,2,6$ is $5$, since the minimum is $2$ and the maximum is $6$.
-----Input-----
The first line contains a single integer $t$ ($1 \leq t \leq 6840$) — the number of test cases.
The description of each test case consists of three distinct integers $a$, $b$, $c$ ($1 \leq a, b, c \leq 20$).
-----Output-----
For each test case, output a single integer — the medium number of the three numbers.
-----Examples-----
Input
9
5 2 6
14 3 4
20 2 1
1 2 3
11 19 12
10 8 20
6 20 3
4 1 3
19 8 4
Output
5
4
2
2
12
10
6
3
8
-----Note-----
None
|
{"inputs": ["1\n1 3 2\n", "1\n1 2 3\n", "1\n1 3 4\n", "1\n2 3 4\n", "1\n1 2 4\n", "1\n17 2 3\n", "2\n1 2 3\n2 3 1\n", "3\n1 2 3\n1 2 3\n1 2 3\n"], "outputs": ["2\n", "2\n", "3\n", "3\n", "2\n", "3\n", "2\n2\n", "2\n2\n2\n"]}
| 279
| 143
|
coding
|
Solve the programming task below in a Python markdown code block.
Write a function that accepts a square matrix (`N x N` 2D array) and returns the determinant of the matrix.
How to take the determinant of a matrix -- it is simplest to start with the smallest cases:
A 1x1 matrix `|a|` has determinant `a`.
A 2x2 matrix `[ [a, b], [c, d] ]` or
```
|a b|
|c d|
```
has determinant: `a*d - b*c`.
The determinant of an `n x n` sized matrix is calculated by reducing the problem to the calculation of the determinants of `n` matrices of`n-1 x n-1` size.
For the 3x3 case, `[ [a, b, c], [d, e, f], [g, h, i] ]` or
```
|a b c|
|d e f|
|g h i|
```
the determinant is: `a * det(a_minor) - b * det(b_minor) + c * det(c_minor)` where `det(a_minor)` refers to taking the determinant of the 2x2 matrix created by crossing out the row and column in which the element a occurs:
```
|- - -|
|- e f|
|- h i|
```
Note the alternation of signs.
The determinant of larger matrices are calculated analogously, e.g. if M is a 4x4 matrix with first row `[a, b, c, d]`, then:
`det(M) = a * det(a_minor) - b * det(b_minor) + c * det(c_minor) - d * det(d_minor)`
Also feel free to reuse/extend the following starter code:
```python
def determinant(matrix):
```
|
{"functional": "_inputs = [[[[5]]]]\n_outputs = [[5]]\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(determinant(*i), o[0])"}
| 388
| 157
|
coding
|
Solve the programming task below in a Python markdown code block.
###Story
Sometimes we are faced with problems when we have a big nested dictionary with which it's hard to work. Now, we need to solve this problem by writing a function that will flatten a given dictionary.
###Info
Python dictionaries are a convenient data type to store and process configurations. They allow you to store data by keys to create nested structures. You are given a dictionary where the keys are strings and the values are strings or dictionaries. The goal is flatten the dictionary, but save the structures in the keys. The result should be a dictionary without the nested dictionaries. The keys should contain paths that contain the parent keys from the original dictionary. The keys in the path are separated by a `/`. If a value is an empty dictionary, then it should be replaced by an empty string `""`.
###Examples
```python
{
"name": {
"first": "One",
"last": "Drone"
},
"job": "scout",
"recent": {},
"additional": {
"place": {
"zone": "1",
"cell": "2"
}
}
}
```
The result will be:
```python
{"name/first": "One", #one parent
"name/last": "Drone",
"job": "scout", #root key
"recent": "", #empty dict
"additional/place/zone": "1", #third level
"additional/place/cell": "2"}
```
***`Input: An original dictionary as a dict.`***
***`Output: The flattened dictionary as a dict.`***
***`Precondition:
Keys in a dictionary are non-empty strings.
Values in a dictionary are strings or dicts.
root_dictionary != {}`***
```python
flatten({"key": "value"}) == {"key": "value"}
flatten({"key": {"deeper": {"more": {"enough": "value"}}}}) == {"key/deeper/more/enough": "value"}
flatten({"empty": {}}) == {"empty": ""}
```
Also feel free to reuse/extend the following starter code:
```python
def flatten(dictionary):
```
|
{"functional": "_inputs = [[{'key': 'value'}], [{'key': {'deeper': {'more': {'enough': 'value'}}}}], [{'empty': {}}], [{'additional': {'place': {'cell': '2', 'zone': '1'}}, 'job': 'scout', 'name': {'last': 'Drone', 'first': 'One'}, 'recent': {}}], [{'job': {'1': 'scout', '2': 'worker', '3': 'writer', '4': 'reader', '5': 'learner'}, 'name': {'nick': {}, 'last': 'Drone', 'first': 'Second'}, 'recent': {'places': {'earth': {'NP': '', 'NY': '2017', 'Louvre': '2015'}}, 'times': {'XX': {'1964': 'Yes'}, 'XXI': {'2064': 'Nope'}}}}], [{'Hm': {'What': {'is': {'here': {'?': {}}}}}}], [{'glossary': {'GlossDiv': {'GlossList': {'GlossEntry': {'GlossDef': {'GlossSeeAlso': {'1': 'GML', '2': 'XML'}, 'para': 'A meta-markup language, used to create markup languages such as DocBook.'}, 'GlossSee': 'markup', 'Acronym': 'SGML', 'GlossTerm': 'Standard Generalized Markup Language', 'Abbrev': 'ISO 8879:1986', 'SortAs': 'SGML', 'ID': 'SGML'}}, 'title': 'S'}, 'title': 'example glossary'}, 'source': 'http://json.org/example'}]]\n_outputs = [[{'key': 'value'}], [{'key/deeper/more/enough': 'value'}], [{'empty': ''}], [{'additional/place/zone': '1', 'job': 'scout', 'additional/place/cell': '2', 'name/first': 'One', 'name/last': 'Drone', 'recent': ''}], [{'job/1': 'scout', 'recent/places/earth/NY': '2017', 'job/3': 'writer', 'job/2': 'worker', 'job/5': 'learner', 'job/4': 'reader', 'recent/places/earth/NP': '', 'recent/places/earth/Louvre': '2015', 'recent/times/XX/1964': 'Yes', 'recent/times/XXI/2064': 'Nope', 'name/first': 'Second', 'name/last': 'Drone', 'name/nick': ''}], [{'Hm/What/is/here/?': ''}], [{'glossary/GlossDiv/GlossList/GlossEntry/GlossDef/para': 'A meta-markup language, used to create markup languages such as DocBook.', 'glossary/title': 'example glossary', 'glossary/GlossDiv/GlossList/GlossEntry/Abbrev': 'ISO 8879:1986', 'glossary/GlossDiv/GlossList/GlossEntry/SortAs': 'SGML', 'glossary/GlossDiv/GlossList/GlossEntry/Acronym': 'SGML', 'glossary/GlossDiv/GlossList/GlossEntry/GlossTerm': 'Standard Generalized Markup Language', 'glossary/GlossDiv/title': 'S', 'source': 'http://json.org/example', 'glossary/GlossDiv/GlossList/GlossEntry/GlossDef/GlossSeeAlso/2': 'XML', 'glossary/GlossDiv/GlossList/GlossEntry/ID': 'SGML', 'glossary/GlossDiv/GlossList/GlossEntry/GlossDef/GlossSeeAlso/1': 'GML', 'glossary/GlossDiv/GlossList/GlossEntry/GlossSee': 'markup'}]]\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(flatten(*i), o[0])"}
| 461
| 1,001
|
coding
|
Solve the programming task below in a Python markdown code block.
There are N sightseeing spots on the x-axis, numbered 1, 2, ..., N.
Spot i is at the point with coordinate A_i.
It costs |a - b| yen (the currency of Japan) to travel from a point with coordinate a to another point with coordinate b along the axis.
You planned a trip along the axis.
In this plan, you first depart from the point with coordinate 0, then visit the N spots in the order they are numbered, and finally return to the point with coordinate 0.
However, something came up just before the trip, and you no longer have enough time to visit all the N spots, so you decided to choose some i and cancel the visit to Spot i.
You will visit the remaining spots as planned in the order they are numbered.
You will also depart from and return to the point with coordinate 0 at the beginning and the end, as planned.
For each i = 1, 2, ..., N, find the total cost of travel during the trip when the visit to Spot i is canceled.
-----Constraints-----
- 2 \leq N \leq 10^5
- -5000 \leq A_i \leq 5000 (1 \leq i \leq N)
- All input values are integers.
-----Input-----
Input is given from Standard Input in the following format:
N
A_1 A_2 ... A_N
-----Output-----
Print N lines.
In the i-th line, print the total cost of travel during the trip when the visit to Spot i is canceled.
-----Sample Input-----
3
3 5 -1
-----Sample Output-----
12
8
10
Spot 1, 2 and 3 are at the points with coordinates 3, 5 and -1, respectively.
For each i, the course of the trip and the total cost of travel when the visit to Spot i is canceled, are as follows:
- For i = 1, the course of the trip is 0 \rightarrow 5 \rightarrow -1 \rightarrow 0 and the total cost of travel is 5 + 6 + 1 = 12 yen.
- For i = 2, the course of the trip is 0 \rightarrow 3 \rightarrow -1 \rightarrow 0 and the total cost of travel is 3 + 4 + 1 = 8 yen.
- For i = 3, the course of the trip is 0 \rightarrow 3 \rightarrow 5 \rightarrow 0 and the total cost of travel is 3 + 2 + 5 = 10 yen.
|
{"inputs": ["3\n3 5 -1\n", "5\n1 1 1 2 0\n", "6\n-679 -2409 -3258 3095 -3291 -4462\n"], "outputs": ["12\n8\n10\n", "4\n4\n4\n2\n4\n", "21630\n21630\n19932\n8924\n21630\n19288\n"]}
| 566
| 123
|
coding
|
Solve the programming task below in a Python markdown code block.
You are given a directed graph consisting of n vertices and m edges (each edge is directed, so it can be traversed in only one direction). You are allowed to remove at most one edge from it.
Can you make this graph acyclic by removing at most one edge from it? A directed graph is called acyclic iff it doesn't contain any cycle (a non-empty path that starts and ends in the same vertex).
-----Input-----
The first line contains two integers n and m (2 ≤ n ≤ 500, 1 ≤ m ≤ min(n(n - 1), 100000)) — the number of vertices and the number of edges, respectively.
Then m lines follow. Each line contains two integers u and v denoting a directed edge going from vertex u to vertex v (1 ≤ u, v ≤ n, u ≠ v). Each ordered pair (u, v) is listed at most once (there is at most one directed edge from u to v).
-----Output-----
If it is possible to make this graph acyclic by removing at most one edge, print YES. Otherwise, print NO.
-----Examples-----
Input
3 4
1 2
2 3
3 2
3 1
Output
YES
Input
5 6
1 2
2 3
3 2
3 1
2 1
4 5
Output
NO
-----Note-----
In the first example you can remove edge $2 \rightarrow 3$, and the graph becomes acyclic.
In the second example you have to remove at least two edges (for example, $2 \rightarrow 1$ and $2 \rightarrow 3$) in order to make the graph acyclic.
|
{"inputs": ["2 2\n1 2\n2 1\n", "2 2\n1 2\n2 1\n", "3 3\n2 3\n2 1\n3 2\n", "3 3\n2 3\n2 1\n3 2\n", "3 4\n1 2\n2 3\n3 2\n3 1\n", "3 4\n1 2\n2 1\n1 3\n3 1\n", "4 4\n1 2\n2 1\n3 4\n4 3\n", "3 4\n3 2\n1 2\n2 3\n1 3\n"], "outputs": ["YES\n", "YES\n", "YES\n", "YES\n", "YES\n", "NO\n", "NO\n", "YES\n"]}
| 375
| 190
|
coding
|
Please solve the programming task below using a self-contained code snippet in a markdown code block.
Given a 2D integer array nums where nums[i] is a non-empty array of distinct positive integers, return the list of integers that are present in each array of nums sorted in ascending order.
Please complete the following python code precisely:
```python
class Solution:
def intersection(self, nums: List[List[int]]) -> List[int]:
```
|
{"functional": "def check(candidate):\n assert candidate(nums = [[3,1,2,4,5],[1,2,3,4],[3,4,5,6]]) == [3,4]\n assert candidate(nums = [[1,2,3],[4,5,6]]) == []\n\n\ncheck(Solution().intersection)"}
| 89
| 79
|
coding
|
Solve the programming task below in a Python markdown code block.
A histogram is made of a number of contiguous bars, which have same width.
For a given histogram with $N$ bars which have a width of 1 and a height of $h_i$ = $h_1, h_2, ... , h_N$ respectively, find the area of the largest rectangular area.
Constraints
* $1 \leq N \leq 10^5$
* $0 \leq h_i \leq 10^9$
Input
The input is given in the following format.
$N$
$h_1$ $h_2$ ... $h_N$
Output
Print the area of the largest rectangle.
Examples
Input
8
2 1 3 5 3 4 2 1
Output
12
Input
3
2 0 1
Output
2
|
{"inputs": ["3\n3 0 1", "3\n5 0 0", "3\n0 0 0", "3\n0 0 1", "3\n2 0 2", "3\n6 1 0", "3\n4 1 2", "3\n7 2 1"], "outputs": ["3\n", "5\n", "0\n", "1\n", "2\n", "6\n", "4\n", "7\n"]}
| 192
| 110
|
coding
|
Please solve the programming task below using a self-contained code snippet in a markdown code block.
Given the head of a linked list and an integer val, remove all the nodes of the linked list that has Node.val == val, and return the new head.
Please complete the following python code precisely:
```python
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def removeElements(self, head: Optional[ListNode], val: int) -> Optional[ListNode]:
```
|
{"functional": "def check(candidate):\n assert is_same_list(candidate(head = list_node([1,2,6,3,4,5,6]), val = 6), list_node([1,2,3,4,5]))\n assert is_same_list(candidate(head = list_node([]), val = 1), list_node([]))\n assert is_same_list(candidate(head = list_node([7,7,7,7]), val = 7), list_node([]))\n\n\ncheck(Solution().removeElements)"}
| 128
| 117
|
coding
|
Please solve the programming task below using a self-contained code snippet in a markdown code block.
Given an integer array nums, return the sum of divisors of the integers in that array that have exactly four divisors. If there is no such integer in the array, return 0.
Please complete the following python code precisely:
```python
class Solution:
def sumFourDivisors(self, nums: List[int]) -> int:
```
|
{"functional": "def check(candidate):\n assert candidate(nums = [21,4,7]) == 32\n\n\ncheck(Solution().sumFourDivisors)"}
| 89
| 39
|
coding
|
Solve the programming task below in a Python markdown code block.
Alice and Johnny are playing a simple guessing game. Johnny picks an arbitrary positive integer n (1<=n<=109) and gives Alice exactly k hints about the value of n. It is Alice's task to guess n, based on the received hints.
Alice often has a serious problem guessing the value of n, and she's beginning to suspect that Johnny occasionally cheats, that is, gives her incorrect hints.
After the last game, they had the following little conversation:
- [Alice] Johnny, you keep cheating!
- [Johnny] Indeed? You cannot prove it.
- [Alice] Oh yes I can. In fact, I can tell you with the utmost certainty that in the last game you lied to me at least *** times.
So, how many times at least did Johnny lie to Alice? Try to determine this, knowing only the hints Johnny gave to Alice.
-----Input-----
The first line of input contains t, the number of test cases (about 20). Exactly t test cases follow.
Each test case starts with a line containing a single integer k, denoting the number of hints given by Johnny (1<=k<=100000). Each of the next k lines contains exactly one hint. The i-th hint is of the form:
operator li logical_value
where operator denotes one of the symbols < , > , or =; li is an integer (1<=li<=109), while logical_value is one of the words: Yes or No. The hint is considered correct if logical_value is the correct reply to the question: "Does the relation: n operator li hold?", and is considered to be false (a lie) otherwise.
-----Output-----
For each test case output a line containing a single integer, equal to the minimal possible number of Johnny's lies during the game.
-----Example-----
Input:
3
2
< 100 No
> 100 No
3
< 2 Yes
> 4 Yes
= 3 No
6
< 2 Yes
> 1 Yes
= 1 Yes
= 1 Yes
> 1 Yes
= 1 Yes
Output:
0
1
2
Explanation: for the respective test cases, the number picked by Johnny could have been e.g. n=100, n=5, and n=1.
|
{"inputs": ["3\n2\n< 100 No\n> 100 No\n3\n< 2 Yes\n> 4 Yes\n= 3 No\n6\n< 2 Yes\n> 1 Yes\n= 1 Yes\n= 1 Yes\n> 1 Yes\n= 1 Yes", "3\n2\n< 100 No\n> 100 No\n3\n< 2 Yes\n> 4 Yes\n= 3 No\n6\n< 2 Yes\n> 1 Yes\n= 1 Yes\n= 1 Yes\n= 1 Yes\n= 1 Yes", "3\n2\n< 100 No\n? 100 No\n3\n< 2 Yes\n> 4 Yes\n= 3 No\n6\n< 2 Yes\n> 1 Yes\n= 1 Yes\n= 1 Yes\n> 1 Yes\n= 1 Yes", "3\n2\n< 100 No\n> 100 No\n3\n< 2 Yes\n> 4 Yes\n= 3 No\n6\n< 2 Yes\n> 1 Yes\n= 1 Yes\n= 2 Yes\n= 1 Yes\n> 1 Yes", "3\n2\n< 100 No\n> 100 No\n3\n< 2 Zes\n> 4 Yes\n= 3 No\n6\n< 2 Yes\n> 1 Yes\n= 1 Yes\n= 1 Yes\n> 1 Yes\n= 1 Yes", "3\n2\n< 100 No\n? 100 No\n3\n< 2 Yfs\n> 4 Yes\n= 3 nN\n6\n< 1 Yes\n> 1 Yes\n= 1 Yes\n= 1 Yes\n> 1 Yes\n= 1 Yse", "3\n2\n< 100 No\n> 100 No\n3\n< 2 seY\n> 4 Yes\n= 3 No\n3\n< 2 Yes\n> 1 Yes\n= 1 Yes\n= 2 Yes\n= 1 Yes\n> 1 Yes", "3\n2\n< 101 No\n> 100 No\n3\n< 2 Yes\n> 4 Yes\n= 3 oN\n6\n< 2 Yes\n> 1 Yes\n= 1 Yes\n= 2 Yes\n= 1 Yes\n> 1 Yes"], "outputs": ["0\n1\n2", "0\n1\n1\n", "0\n1\n2\n", "0\n1\n3\n", "0\n0\n2\n", "0\n0\n3\n", "0\n0\n1\n", "1\n1\n3\n"]}
| 502
| 619
|
coding
|
Please solve the programming task below using a self-contained code snippet in a markdown code block.
There are n cars on an infinitely long road. The cars are numbered from 0 to n - 1 from left to right and each car is present at a unique point.
You are given a 0-indexed string directions of length n. directions[i] can be either 'L', 'R', or 'S' denoting whether the ith car is moving towards the left, towards the right, or staying at its current point respectively. Each moving car has the same speed.
The number of collisions can be calculated as follows:
When two cars moving in opposite directions collide with each other, the number of collisions increases by 2.
When a moving car collides with a stationary car, the number of collisions increases by 1.
After a collision, the cars involved can no longer move and will stay at the point where they collided. Other than that, cars cannot change their state or direction of motion.
Return the total number of collisions that will happen on the road.
Please complete the following python code precisely:
```python
class Solution:
def countCollisions(self, directions: str) -> int:
```
|
{"functional": "def check(candidate):\n assert candidate(directions = \"RLRSLL\") == 5\n assert candidate(directions = \"LLRR\") == 0\n\n\ncheck(Solution().countCollisions)"}
| 245
| 49
|
coding
|
Please solve the programming task below using a self-contained code snippet in a markdown code block.
You are given an m x n binary matrix grid where each cell is either 0 (empty) or 1 (occupied).
You are then given stamps of size stampHeight x stampWidth. We want to fit the stamps such that they follow the given restrictions and requirements:
Cover all the empty cells.
Do not cover any of the occupied cells.
We can put as many stamps as we want.
Stamps can overlap with each other.
Stamps are not allowed to be rotated.
Stamps must stay completely inside the grid.
Return true if it is possible to fit the stamps while following the given restrictions and requirements. Otherwise, return false.
Please complete the following python code precisely:
```python
class Solution:
def possibleToStamp(self, grid: List[List[int]], stampHeight: int, stampWidth: int) -> bool:
```
|
{"functional": "def check(candidate):\n assert candidate(grid = [[1,0,0,0],[1,0,0,0],[1,0,0,0],[1,0,0,0],[1,0,0,0]], stampHeight = 4, stampWidth = 3) == True\n assert candidate(grid = [[1,0,0,0],[0,1,0,0],[0,0,1,0],[0,0,0,1]], stampHeight = 2, stampWidth = 2 ) == False \n\n\ncheck(Solution().possibleToStamp)"}
| 189
| 135
|
coding
|
Solve the programming task below in a Python markdown code block.
An Ironman Triathlon is one of a series of long-distance triathlon races organized by the World Triathlon Corporaion (WTC).
It consists of a 2.4-mile swim, a 112-mile bicycle ride and a marathon (26.2-mile) (run, raced in that order and without a break. It hurts... trust me.
Your task is to take a distance that an athlete is through the race, and return one of the following:
If the distance is zero, return `'Starting Line... Good Luck!'`.
If the athlete will be swimming, return an object with `'Swim'` as the key, and the remaining race distance as the value.
If the athlete will be riding their bike, return an object with `'Bike'` as the key, and the remaining race distance as the value.
If the athlete will be running, and has more than 10 miles to go, return an object with `'Run'` as the key, and the remaining race distance as the value.
If the athlete has 10 miles or less to go, return return an object with `'Run'` as the key, and `'Nearly there!'` as the value.
Finally, if the athlete has completed te distance, return `"You're done! Stop running!"`.
All distance should be calculated to two decimal places.
Also feel free to reuse/extend the following starter code:
```python
def i_tri(s):
```
|
{"functional": "_inputs = [[36], [103], [0], [2], [151]]\n_outputs = [[{'Bike': '104.60 to go!'}], [{'Bike': '37.60 to go!'}], ['Starting Line... Good Luck!'], [{'Swim': '138.60 to go!'}], [\"You're done! Stop running!\"]]\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(i_tri(*i), o[0])"}
| 312
| 234
|
coding
|
Please solve the programming task below using a self-contained code snippet in a markdown code block.
Given a string of English letters s, return the greatest English letter which occurs as both a lowercase and uppercase letter in s. The returned letter should be in uppercase. If no such letter exists, return an empty string.
An English letter b is greater than another letter a if b appears after a in the English alphabet.
Please complete the following python code precisely:
```python
class Solution:
def greatestLetter(self, s: str) -> str:
```
|
{"functional": "def check(candidate):\n assert candidate(s = \"lEeTcOdE\") == \"E\"\n assert candidate(s = \"arRAzFif\") == \"R\"\n assert candidate(s = \"AbCdEfGhIjK\") == \"\"\n\n\ncheck(Solution().greatestLetter)"}
| 111
| 75
|
coding
|
Solve the programming task below in a Python markdown code block.
A New Year party is not a New Year party without lemonade! As usual, you are expecting a lot of guests, and buying lemonade has already become a pleasant necessity.
Your favorite store sells lemonade in bottles of n different volumes at different costs. A single bottle of type i has volume 2^{i} - 1 liters and costs c_{i} roubles. The number of bottles of each type in the store can be considered infinite.
You want to buy at least L liters of lemonade. How many roubles do you have to spend?
-----Input-----
The first line contains two integers n and L (1 ≤ n ≤ 30; 1 ≤ L ≤ 10^9) — the number of types of bottles in the store and the required amount of lemonade in liters, respectively.
The second line contains n integers c_1, c_2, ..., c_{n} (1 ≤ c_{i} ≤ 10^9) — the costs of bottles of different types.
-----Output-----
Output a single integer — the smallest number of roubles you have to pay in order to buy at least L liters of lemonade.
-----Examples-----
Input
4 12
20 30 70 90
Output
150
Input
4 3
10000 1000 100 10
Output
10
Input
4 3
10 100 1000 10000
Output
30
Input
5 787787787
123456789 234567890 345678901 456789012 987654321
Output
44981600785557577
-----Note-----
In the first example you should buy one 8-liter bottle for 90 roubles and two 2-liter bottles for 30 roubles each. In total you'll get 12 liters of lemonade for just 150 roubles.
In the second example, even though you need only 3 liters, it's cheaper to buy a single 8-liter bottle for 10 roubles.
In the third example it's best to buy three 1-liter bottles for 10 roubles each, getting three liters for 30 roubles.
|
{"inputs": ["1 1\n1\n", "1 1\n1\n", "2 3\n10 1\n", "2 3\n10 5\n", "2 3\n10 5\n", "2 3\n10 1\n", "2 3\n13 5\n", "2 2\n10 1\n"], "outputs": ["1\n", "1\n", "2\n", "10\n", "10\n", "2\n", "10\n", "1\n"]}
| 547
| 123
|
coding
|
Solve the programming task below in a Python markdown code block.
Memory is now interested in the de-evolution of objects, specifically triangles. He starts with an equilateral triangle of side length x, and he wishes to perform operations to obtain an equilateral triangle of side length y.
In a single second, he can modify the length of a single side of the current triangle such that it remains a non-degenerate triangle (triangle of positive area). At any moment of time, the length of each side should be integer.
What is the minimum number of seconds required for Memory to obtain the equilateral triangle of side length y?
-----Input-----
The first and only line contains two integers x and y (3 ≤ y < x ≤ 100 000) — the starting and ending equilateral triangle side lengths respectively.
-----Output-----
Print a single integer — the minimum number of seconds required for Memory to obtain the equilateral triangle of side length y if he starts with the equilateral triangle of side length x.
-----Examples-----
Input
6 3
Output
4
Input
8 5
Output
3
Input
22 4
Output
6
-----Note-----
In the first sample test, Memory starts with an equilateral triangle of side length 6 and wants one of side length 3. Denote a triangle with sides a, b, and c as (a, b, c). Then, Memory can do $(6,6,6) \rightarrow(6,6,3) \rightarrow(6,4,3) \rightarrow(3,4,3) \rightarrow(3,3,3)$.
In the second sample test, Memory can do $(8,8,8) \rightarrow(8,8,5) \rightarrow(8,5,5) \rightarrow(5,5,5)$.
In the third sample test, Memory can do: $(22,22,22) \rightarrow(7,22,22) \rightarrow(7,22,16) \rightarrow(7,10,16) \rightarrow(7,10,4) \rightarrow$
$(7,4,4) \rightarrow(4,4,4)$.
|
{"inputs": ["6 3\n", "8 5\n", "4 3\n", "5 4\n", "4 3\n", "5 4\n", "8 5\n", "6 3\n"], "outputs": ["4\n", "3\n", "3\n", "3\n", "3\n", "3\n", "3\n", "4\n"]}
| 469
| 86
|
coding
|
Solve the programming task below in a Python markdown code block.
You stumbled upon a new kind of chess puzzles. The chessboard you are given is not necesserily $8 \times 8$, but it still is $N \times N$. Each square has some number written on it, all the numbers are from $1$ to $N^2$ and all the numbers are pairwise distinct. The $j$-th square in the $i$-th row has a number $A_{ij}$ written on it.
In your chess set you have only three pieces: a knight, a bishop and a rook. At first, you put one of them on the square with the number $1$ (you can choose which one). Then you want to reach square $2$ (possibly passing through some other squares in process), then square $3$ and so on until you reach square $N^2$. In one step you are allowed to either make a valid move with the current piece or replace it with some other piece. Each square can be visited arbitrary number of times.
A knight can move to a square that is two squares away horizontally and one square vertically, or two squares vertically and one square horizontally. A bishop moves diagonally. A rook moves horizontally or vertically. The move should be performed to a different square from the one a piece is currently standing on.
You want to minimize the number of steps of the whole traversal. Among all the paths to have the same number of steps you want to choose the one with the lowest number of piece replacements.
What is the path you should take to satisfy all conditions?
-----Input-----
The first line contains a single integer $N$ ($3 \le N \le 10$) — the size of the chessboard.
Each of the next $N$ lines contains $N$ integers $A_{i1}, A_{i2}, \dots, A_{iN}$ ($1 \le A_{ij} \le N^2$) — the numbers written on the squares of the $i$-th row of the board.
It is guaranteed that all $A_{ij}$ are pairwise distinct.
-----Output-----
The only line should contain two integers — the number of steps in the best answer and the number of replacement moves in it.
-----Example-----
Input
3
1 9 3
8 6 7
4 2 5
Output
12 1
-----Note-----
Here are the steps for the first example (the starting piece is a knight): Move to $(3, 2)$ Move to $(1, 3)$ Move to $(3, 2)$ Replace the knight with a rook Move to $(3, 1)$ Move to $(3, 3)$ Move to $(3, 2)$ Move to $(2, 2)$ Move to $(2, 3)$ Move to $(2, 1)$ Move to $(1, 1)$ Move to $(1, 2)$
|
{"inputs": ["3\n1 9 3\n8 6 7\n4 2 5\n", "3\n1 5 8\n9 2 4\n3 6 7\n", "3\n1 4 7\n6 9 2\n3 8 5\n", "3\n1 6 3\n7 2 9\n4 8 5\n", "3\n1 6 3\n4 9 8\n7 2 5\n", "3\n8 6 3\n9 1 5\n2 4 7\n", "3\n1 5 2\n7 6 3\n4 8 9\n", "3\n1 4 8\n7 2 6\n5 9 3\n"], "outputs": ["12 1\n", "12 1\n", "9 1\n", "11 2\n", "9 1\n", "13 2\n", "11 0\n", "11 3\n"]}
| 632
| 236
|
coding
|
Solve the programming task below in a Python markdown code block.
Write a function that merges two sorted arrays into a single one. The arrays only contain integers. Also, the final outcome must be sorted and not have any duplicate.
Also feel free to reuse/extend the following starter code:
```python
def merge_arrays(first, second):
```
|
{"functional": "_inputs = [[[1, 3, 5], [2, 4, 6]], [[2, 4, 8], [2, 4, 6]], [[1, 2, 3], []], [[], []]]\n_outputs = [[[1, 2, 3, 4, 5, 6]], [[2, 4, 6, 8]], [[1, 2, 3]], [[]]]\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(merge_arrays(*i), o[0])"}
| 69
| 241
|
coding
|
Please solve the programming task below using a self-contained code snippet in a markdown code block.
There is a row of n houses, where each house can be painted one of three colors: red, blue, or green. The cost of painting each house with a certain color is different. You have to paint all the houses such that no two adjacent houses have the same color.
The cost of painting each house with a certain color is represented by an n x 3 cost matrix costs.
For example, costs[0][0] is the cost of painting house 0 with the color red; costs[1][2] is the cost of painting house 1 with color green, and so on...
Return the minimum cost to paint all houses.
Please complete the following python code precisely:
```python
class Solution:
def minCost(self, costs: List[List[int]]) -> int:
```
|
{"functional": "def check(candidate):\n assert candidate(costs = [[17,2,17],[16,16,5],[14,3,19]]) == 10\n assert candidate(costs = [[7,6,2]]) == 2\n\n\ncheck(Solution().minCost)"}
| 181
| 72
|
coding
|
Please solve the programming task below using a self-contained code snippet in a markdown code block.
The minimum absolute difference of an array a is defined as the minimum value of |a[i] - a[j]|, where 0 <= i < j < a.length and a[i] != a[j]. If all elements of a are the same, the minimum absolute difference is -1.
For example, the minimum absolute difference of the array [5,2,3,7,2] is |2 - 3| = 1. Note that it is not 0 because a[i] and a[j] must be different.
You are given an integer array nums and the array queries where queries[i] = [li, ri]. For each query i, compute the minimum absolute difference of the subarray nums[li...ri] containing the elements of nums between the 0-based indices li and ri (inclusive).
Return an array ans where ans[i] is the answer to the ith query.
A subarray is a contiguous sequence of elements in an array.
The value of |x| is defined as:
x if x >= 0.
-x if x < 0.
Please complete the following python code precisely:
```python
class Solution:
def minDifference(self, nums: List[int], queries: List[List[int]]) -> List[int]:
```
|
{"functional": "def check(candidate):\n assert candidate(nums = [1,3,4,8], queries = [[0,1],[1,2],[2,3],[0,3]]) == [2,1,4,1]\n assert candidate(nums = [4,5,2,2,7,10], queries = [[2,3],[0,2],[0,5],[3,5]]) == [-1,1,1,3]\n\n\ncheck(Solution().minDifference)"}
| 276
| 112
|
coding
|
Solve the programming task below in a Python markdown code block.
## Your task
You are given a dictionary/hash/object containing some languages and your test results in the given languages. Return the list of languages where your test score is at least `60`, in descending order of the results.
Note: the scores will always be unique (so no duplicate values)
## Examples
```python
{"Java": 10, "Ruby": 80, "Python": 65} --> ["Ruby", "Python"]
{"Hindi": 60, "Dutch" : 93, "Greek": 71} --> ["Dutch", "Greek", "Hindi"]
{"C++": 50, "ASM": 10, "Haskell": 20} --> []
```
---
## My other katas
If you enjoyed this kata then please try [my other katas](https://www.codewars.com/collections/katas-created-by-anter69)! :-)
### _Translations are welcome!_
Also feel free to reuse/extend the following starter code:
```python
def my_languages(results):
```
|
{"functional": "_inputs = [[{'Java': 10, 'Ruby': 80, 'Python': 65}], [{'Hindi': 60, 'Greek': 71, 'Dutch': 93}], [{'C++': 50, 'ASM': 10, 'Haskell': 20}]]\n_outputs = [[['Ruby', 'Python']], [['Dutch', 'Greek', 'Hindi']], [[]]]\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(my_languages(*i), o[0])"}
| 245
| 237
|
coding
|
Solve the programming task below in a Python markdown code block.
Consider the sequence `a(1) = 7, a(n) = a(n-1) + gcd(n, a(n-1)) for n >= 2`:
`7, 8, 9, 10, 15, 18, 19, 20, 21, 22, 33, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 69, 72, 73...`.
Let us take the differences between successive elements of the sequence and
get a second sequence `g: 1, 1, 1, 5, 3, 1, 1, 1, 1, 11, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 23, 3, 1...`.
For the sake of uniformity of the lengths of sequences **we add** a `1` at the head of g:
`g: 1, 1, 1, 1, 5, 3, 1, 1, 1, 1, 11, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 23, 3, 1...`
Removing the 1s gives a third sequence:
`p: 5, 3, 11, 3, 23, 3...`
where you can see prime numbers.
#Task:
Write functions:
```
1: an(n) with parameter n: returns the first n terms of the series a(n) (not tested)
2: gn(n) with parameter n: returns the first n terms of the series g(n) (not tested)
3: countOnes(n) with parameter n: returns the number of 1 in g(n)
(don't forget to add a `1` at the head) # (tested)
4: p(n) with parameter n: returns an array of n unique prime numbers (not tested)
5: maxp(n) with parameter n: returns the biggest prime number of the sequence pn(n) # (tested)
6: anOver(n) with parameter n: returns an array (n terms) of the a(i)/i for every i such g(i) != 1 (not tested but interesting result)
7: anOverAverage(n) with parameter n: returns as an *integer* the average of anOver(n) (tested)
```
#Note:
You can write directly functions `3:`, `5:` and `7:`. There is no need to write functions `1:`, `2:`, `4:` `6:`
except out of pure curiosity.
Also feel free to reuse/extend the following starter code:
```python
def count_ones(n):
```
|
{"functional": "_inputs = [[1], [10], [100], [200], [1000], [10000], [100000]]\n_outputs = [[1], [8], [90], [184], [975], [9968], [99955]]\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(count_ones(*i), o[0])"}
| 674
| 220
|
coding
|
Solve the programming task below in a Python markdown code block.
The beauty of a sequence a of length n is defined as a_1 \oplus \cdots \oplus a_n, where \oplus denotes the bitwise exclusive or (XOR).
You are given a sequence A of length N. Snuke will insert zero or more partitions in A to divide it into some number of non-empty contiguous subsequences.
There are 2^{N-1} possible ways to insert partitions. How many of them divide A into sequences whose beauties are all equal? Find this count modulo 10^{9}+7.
Constraints
* All values in input are integers.
* 1 \leq N \leq 5 \times 10^5
* 0 \leq A_i < 2^{20}
Input
Input is given from Standard Input in the following format:
N
A_1 A_2 \ldots A_{N}
Output
Print the answer.
Examples
Input
3
1 2 3
Output
3
Input
3
1 2 2
Output
1
Input
32
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
Output
147483634
Input
24
1 2 5 3 3 6 1 1 8 8 0 3 3 4 6 6 4 0 7 2 5 4 6 2
Output
292
|
{"inputs": ["3\n2 2 0", "3\n1 4 2", "3\n1 2 0", "3\n1 8 2", "3\n1 6 2", "3\n1 0 0", "3\n1 6 3", "3\n0 0 3"], "outputs": ["3\n", "1\n", "1\n", "1\n", "1\n", "1\n", "1\n", "1\n"]}
| 378
| 110
|
coding
|
Solve the programming task below in a Python markdown code block.
## Find Mean
Find the mean (average) of a list of numbers in an array.
## Information
To find the mean (average) of a set of numbers add all of the numbers together and divide by the number of values in the list.
For an example list of `1, 3, 5, 7`
1. Add all of the numbers
```
1+3+5+7 = 16
```
2. Divide by the number of values in the list. In this example there are 4 numbers in the list.
```
16/4 = 4
```
3. The mean (or average) of this list is 4
Also feel free to reuse/extend the following starter code:
```python
def find_average(nums):
```
|
{"functional": "_inputs = [[[1]], [[1, 3, 5, 7]], [[-1, 3, 5, -7]], [[5, 7, 3, 7]], [[]]]\n_outputs = [[1], [4], [0], [5.5], [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(find_average(*i), o[0])"}
| 177
| 207
|
coding
|
Solve the programming task below in a Python markdown code block.
There is only little time left until the New Year! For that reason, Chef decided to make a present for his best friend. He made a connected and undirected simple graph with N$N$ vertices and M$M$ edges.
Since Chef does not like odd numbers and his friend does not like undirected graphs, Chef decided to direct each edge in one of two possible directions in such a way that the indegrees of all vertices of the resulting graph are even. The indegree of a vertex is the number of edges directed to that vertex from another vertex. As usual, Chef is busy in the kitchen, so you need to help him with directing the edges. Find one possible way to direct them or determine that it is impossible under the given conditions, so that Chef could bake a cake as a present instead.
-----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$.
- M$M$ lines follow. For each i$i$ (1≤i≤M$1 \le i \le M$), the i$i$-th of these lines contains two space-separated integers ui$u_i$ and vi$v_i$ denoting an edge between vertices ui$u_i$ and vi$v_i$.
-----Output-----
For each test case:
- If a valid way to direct the edges does not exist, print a single line containing one integer −1$-1$.
- Otherwise, print a single line containing M$M$ space-separated integers. For each valid i$i$, the i$i$-th of these integers should be 0$0$ if edge i$i$ is directed from ui$u_i$ to vi$v_i$ or 1$1$ if it is directed from vi$v_i$ to ui$u_i$.
-----Constraints-----
- 1≤T≤5$1 \le T \le 5$
- 1≤N,M≤105$1 \le N, M \le 10^5$
- 1≤ui,vi≤N$1 \le u_i, v_i \le N$ for each valid i$i$
- the graph on the input is connected, does not contain multiple edges or self-loops
-----Subtasks-----
Subtask #1 (30 points): 1≤N,M≤1,000$1 \le N, M \le 1,000$
Subtask #2 (70 points): original constraints
-----Example Input-----
2
4 4
1 2
1 3
2 4
3 4
3 3
1 2
2 3
1 3
-----Example Output-----
0 0 1 1
-1
|
{"inputs": ["2\n4 4\n1 2\n1 3\n2 4\n3 4\n3 3\n1 2\n2 3\n1 3"], "outputs": ["0 0 1 1\n-1"]}
| 622
| 57
|
coding
|
Solve the programming task below in a Python markdown code block.
At an arcade, Takahashi is playing a game called RPS Battle, which is played as follows:
- The player plays N rounds of Rock Paper Scissors against the machine. (See Notes for the description of Rock Paper Scissors. A draw also counts as a round.)
- Each time the player wins a round, depending on which hand he/she uses, he/she earns the following score (no points for a draw or a loss):
- R points for winning with Rock;
- S points for winning with Scissors;
- P points for winning with Paper.
- However, in the i-th round, the player cannot use the hand he/she used in the (i-K)-th round. (In the first K rounds, the player can use any hand.)
Before the start of the game, the machine decides the hand it will play in each round. With supernatural power, Takahashi managed to read all of those hands.
The information Takahashi obtained is given as a string T. If the i-th character of T (1 \leq i \leq N) is r, the machine will play Rock in the i-th round. Similarly, p and s stand for Paper and Scissors, respectively.
What is the maximum total score earned in the game by adequately choosing the hand to play in each round?
-----Notes-----
In this problem, Rock Paper Scissors can be thought of as a two-player game, in which each player simultaneously forms Rock, Paper, or Scissors with a hand.
- If a player chooses Rock and the other chooses Scissors, the player choosing Rock wins;
- if a player chooses Scissors and the other chooses Paper, the player choosing Scissors wins;
- if a player chooses Paper and the other chooses Rock, the player choosing Paper wins;
- if both players play the same hand, it is a draw.
-----Constraints-----
- 2 \leq N \leq 10^5
- 1 \leq K \leq N-1
- 1 \leq R,S,P \leq 10^4
- N,K,R,S, and P are all integers.
- |T| = N
- T consists of r, p, and s.
-----Input-----
Input is given from Standard Input in the following format:
N K
R S P
T
-----Output-----
Print the maximum total score earned in the game.
-----Sample Input-----
5 2
8 7 6
rsrpr
-----Sample Output-----
27
The machine will play {Rock, Scissors, Rock, Paper, Rock}.
We can, for example, play {Paper, Rock, Rock, Scissors, Paper} against it to earn 27 points.
We cannot earn more points, so the answer is 27.
|
{"inputs": ["3 2\n1 8 6\nssr\n", "5 2\n8 7 2\nrsrpr", "5 2\n8 7 6\nrsrpr", "5 2\n8 7 6\nrsrpr\n", "5 2\n12 7 2\nrsrpr", "5 2\n14 7 2\nrsrpr", "5 2\n18 7 2\nrsrpr", "5 2\n18 7 1\nrsrpr"], "outputs": ["8\n", "19\n", "27", "27\n", "23\n", "25\n", "29\n", "27\n"]}
| 592
| 169
|
coding
|
Please solve the programming task below using a self-contained code snippet in a markdown code block.
You are given the head of a non-empty linked list representing a non-negative integer without leading zeroes.
Return the head of the linked list after doubling it.
Please complete the following python code precisely:
```python
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def doubleIt(self, head: Optional[ListNode]) -> Optional[ListNode]:
```
|
{"functional": "def check(candidate):\n assert is_same_list(candidate(head = list_node([1,8,9])), list_node([3,7,8]))\n assert is_same_list(candidate(head = list_node([9,9,9])), list_node([1,9,9,8]))\n\n\ncheck(Solution().doubleIt)"}
| 122
| 77
|
coding
|
Solve the programming task below in a Python markdown code block.
Note : This question carries $100$ $points$
CodeLand is celebrating a festival by baking cakes! In order to avoid wastage, families follow a unique way of distributing cakes.
For $T$ families in the locality, $i$-th family (1 <= $i$ <= $T$) has $N$ members. They baked $S$ slices of cakes. The smallest member of the family gets $K$ slices of cakes. Each family has a lucky number of $R$ and they agree to distribute the slices such that the member gets $R$ times more slices than the member just smaller than them. Since the family is busy in festival preparations, find out if the number of slices would be sufficient for the family or not. Also, find how many extra slices they have or how many slices are they short of.
Also, the locality is kind and believes in sharing. So, you also need to determine if each family would have sufficient slices if families shared their cakes among each other!
-----Input :-----
- First line of input will have a single integer $T$ i.e. the number of families in the locality
- For next $T$ lines, each line will describe one family through 4 integers i.e. $S$, $N$, $K$, $R$ separated by spaces
-----Output-----
- First $T$ lines of output will show if slices are enough for the family or not, followed by extra or required slices. For example, if slices are sufficient, the output would be $POSSIBLE$ $10$ which implies 10 slices are extra. If slices are insufficient, the output would be $IMPOSSIBLE$ $15$ which implies 15 slices are required to fulfill the requirement.
- Last line of output would be $IMPOSSIBLE$ or $POSSIBLE$ depending on whether each family would get enough slices after sharing.
-----Constraints:-----
- 1 ≤ $T$ ≤ 50
- 1 ≤ $N$ ≤ 15
- 1 ≤ $S$ ≤ 10^9
- 1 ≤ $K$ ≤ 5
- 1 ≤ $R$ ≤ 5
-----Sample Input:-----
5
100 4 2 2
100 4 3 2
100 4 3 3
200 4 4 2
10 3 2 2
-----Sample Output:-----
POSSIBLE 70
POSSIBLE 55
IMPOSSIBLE 20
POSSIBLE 140
IMPOSSIBLE 4
POSSIBLE
-----Explanation-----
For the first home, the youngest member has got 2 slices, the one older than them gets 2 times more slices, and so forth. So, first home needs 2 + 4 + 8 + 16 = 30 slices. But since they made 100, they have 70 extra, hence we print 'POSSIBLE 70'.
Doing the same for other houses, we find 20 + 4 = 24 slices extra are required so that all families have enough slices. In this case we have 70 + 55 + 140 = 265 extra slices which is > 24, so we print 'POSSIBLE' in last line.
|
{"inputs": ["5\n100 4 2 2\n100 4 3 2\n100 4 3 3\n200 4 4 2\n10 3 2 2"], "outputs": ["POSSIBLE 70\nPOSSIBLE 55\nIMPOSSIBLE 20\nPOSSIBLE 140\nIMPOSSIBLE 4\nPOSSIBLE"]}
| 731
| 100
|
coding
|
Solve the programming task below in a Python markdown code block.
Tonight is brain dinner night and all zombies will gather together to scarf down some delicious brains. The artful Heidi plans to crash the party, incognito, disguised as one of them. Her objective is to get away with at least one brain, so she can analyze the zombies' mindset back home and gain a strategic advantage.
They will be N guests tonight: N - 1 real zombies and a fake one, our Heidi. The living-dead love hierarchies as much as they love brains: each one has a unique rank in the range 1 to N - 1, and Heidi, who still appears slightly different from the others, is attributed the highest rank, N. Tonight there will be a chest with brains on display and every attendee sees how many there are. These will then be split among the attendees according to the following procedure:
The zombie of the highest rank makes a suggestion on who gets how many brains (every brain is an indivisible entity). A vote follows. If at least half of the attendees accept the offer, the brains are shared in the suggested way and the feast begins. But if majority is not reached, then the highest-ranked zombie is killed, and the next zombie in hierarchy has to make a suggestion. If he is killed too, then the third highest-ranked makes one, etc. (It's enough to have exactly half of the votes – in case of a tie, the vote of the highest-ranked alive zombie counts twice, and he will of course vote in favor of his own suggestion in order to stay alive.)
You should know that zombies are very greedy and sly, and they know this too – basically all zombie brains are alike. Consequently, a zombie will never accept an offer which is suboptimal for him. That is, if an offer is not strictly better than a potential later offer, he will vote against it. And make no mistake: while zombies may normally seem rather dull, tonight their intellects are perfect. Each zombie's priorities for tonight are, in descending order: survive the event (they experienced death already once and know it is no fun), get as many brains as possible.
Heidi goes first and must make an offer which at least half of the attendees will accept, and which allocates at least one brain for Heidi herself.
What is the smallest number of brains that have to be in the chest for this to be possible?
-----Input-----
The only line of input contains one integer: N, the number of attendees (1 ≤ N ≤ 10^9).
-----Output-----
Output one integer: the smallest number of brains in the chest which allows Heidi to take one brain home.
-----Examples-----
Input
1
Output
1
Input
4
Output
2
-----Note-----
|
{"inputs": ["1\n", "4\n", "2\n", "3\n", "5\n", "6\n", "7\n", "8\n"], "outputs": ["1\n", "2\n", "1\n", "2\n", "3\n", "3\n", "4\n", "4\n"]}
| 574
| 70
|
coding
|
Solve the programming task below in a Python markdown code block.
Does the card fit in a snack? (Are Cards Snacks?)
square1001 You have $ N $ cards.
Each of these cards has an integer written on it, and the integer on the $ i $ th card is $ A_i $.
square1001 Your random number today is $ K $. square1001 You want to choose some of these $ N $ cards so that they add up to $ K $.
E869120, who was watching this situation, wanted to prevent this.
Specifically, I want to eat a few cards in advance so that square1001 doesn't add up to $ K $ no matter how you choose the rest of the cards.
However, E869120 is full and I don't want to eat cards as much as possible.
Now, how many cards can you eat at least E869120 to prevent this?
input
Input is given from standard input in the following format.
$ N $ $ K $
$ A_1 $ $ A_2 $ $ A_3 $ $ \ cdots $ $ A_N $
output
E869120 Print the minimum number of cards you eat to achieve your goal in one line.
However, insert a line break at the end.
Constraint
* $ 1 \ leq N \ leq 20 $
* $ 1 \ leq K \ leq 1000000000 \ (= 10 ^ 9) $
* $ 0 \ leq A_i \ leq 1000000 \ (= 10 ^ 6) $
* All inputs are integers.
Input example 1
5 9
8 6 9 1 2
Output example 1
2
For example, you can thwart square1001's purpose by eating the third card (which has a 9) and the fourth card (which has a 1).
Input example 2
8 2
1 1 1 1 1 1 1 1
Output example 2
7
Input example 3
20 200
31 12 21 17 19 29 25 40 5 8 32 1 27 20 31 13 35 1 8 5
Output example 3
6
Example
Input
5 9
8 6 9 1 2
Output
2
|
{"inputs": ["7 9\n8 6 9 1 2", "5 9\n8 6 9 1 0", "7 9\n8 6 7 1 2", "7 9\n8 6 1 1 1", "7 9\n8 6 8 0 3", "7 9\n8 6 1 2 1", "7 9\n8 6 8 1 3", "6 9\n8 6 1 2 1"], "outputs": ["2\n", "2\n", "2\n", "2\n", "1\n", "2\n", "2\n", "2\n"]}
| 559
| 158
|
coding
|
Solve the programming task below in a Python markdown code block.
Chef made $N$ pieces of cakes, numbered them $1$ through $N$ and arranged them in a row in this order. There are $K$ possible types of flavours (numbered $1$ through $K$); for each valid $i$, the $i$-th piece of cake has a flavour $A_i$.
Chef wants to select a contiguous subsegment of the pieces of cake such that there is at least one flavour which does not occur in that subsegment. Find the maximum possible length of such a subsegment of cakes.
-----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 integers $N$ and $K$.
- The second line contains $N$ space-separated integers $A_1, A_2, \ldots, A_N$.
-----Output-----
For each test case, print a single line containing one integer ― the maximum length of a valid subsegment.
-----Constraints-----
- $1 \le T \le 1,000$
- $1 \le N \le 10^5$
- $2 \le K \le 10^5$
- $1 \le A_i \le K$ for each valid $i$
- the sum of $N$ over all test cases does not exceed $10^6$
-----Subtasks-----
Subtask #1 (50 points):
- $N \le 10^3$
- $K = 2$
- the sum of $N$ over all test cases does not exceed $10^4$
Subtask #2 (50 points): original constraints
-----Example Input-----
2
6 2
1 1 1 2 2 1
5 3
1 1 2 2 1
-----Example Output-----
3
5
|
{"inputs": ["2\n6 2\n1 1 1 2 2 1\n5 3\n1 1 2 2 1"], "outputs": ["3\n5"]}
| 423
| 44
|
coding
|
Solve the programming task below in a Python markdown code block.
You are given three non-negative integers $X$, $Y$ and $N$. Find the number of integers $Z$ such that $0 \le Z \le N$ and $(X \oplus Z) < (Y \oplus Z)$, where $\oplus$ denotes the bitwise XOR operation.
-----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 three space-separated integers $X$, $Y$ and $N$.
-----Output-----
For each test case, print a single line containing one integer ― the number of integers $Z$ which satisfy all conditions.
-----Constraints-----
- $1 \le T \le 1,000$
- $0 \le X, Y, N \le 2^{30} - 1$
-----Subtasks-----
Subtask #1 (5 points): $X, Y, N \le 2^6 - 1$
Subtask #2 (95 points): original constraints
-----Example Input-----
3
1 2 10
2 1 10
0 0 7
-----Example Output-----
6
5
0
|
{"inputs": ["3\n1 2 10\n2 1 10\n0 0 7"], "outputs": ["6\n5\n0"]}
| 281
| 36
|
coding
|
Solve the programming task below in a Python markdown code block.
You are given a square map as a matrix of integer strings. Each cell of the map has a value denoting its depth. We will call a cell of the map a cavity if and only if this cell is not on the border of the map and each cell adjacent to it has strictly smaller depth. Two cells are adjacent if they have a common side, or edge.
Find all the cavities on the map and replace their depths with the uppercase character X.
Example
$grid=['989','191','111']$
The grid is rearranged for clarity:
989
191
111
Return:
989
1X1
111
The center cell was deeper than those on its edges: [8,1,1,1]. The deep cells in the top two corners do not share an edge with the center cell, and none of the border cells is eligible.
Function Description
Complete the cavityMap function in the editor below.
cavityMap has the following parameter(s):
string grid[n]: each string represents a row of the grid
Returns
string{n}: the modified grid
Input Format
The first line contains an integer $n$, the number of rows and columns in the grid.
Each of the following $n$ lines (rows) contains $n$ positive digits without spaces (columns) that represent the depth at $grid[row,column]$.
Constraints
$1\leq n\leq100$
Sample Input
STDIN Function
----- --------
4 grid[] size n = 4
1112 grid = ['1112', '1912', '1892', '1234']
1912
1892
1234
Sample Output
1112
1X12
18X2
1234
Explanation
The two cells with the depth of 9 are not on the border and are surrounded on all sides by shallower cells. Their values are replaced by X.
|
{"inputs": ["4\n1112\n1912\n1892\n1234\n"], "outputs": ["1112\n1X12\n18X2\n1234\n"]}
| 451
| 52
|
coding
|
Solve the programming task below in a Python markdown code block.
Masha really loves algebra. On the last lesson, her strict teacher Dvastan gave she new exercise.
You are given geometric progression b defined by two integers b_1 and q. Remind that a geometric progression is a sequence of integers b_1, b_2, b_3, ..., where for each i > 1 the respective term satisfies the condition b_{i} = b_{i} - 1·q, where q is called the common ratio of the progression. Progressions in Uzhlyandia are unusual: both b_1 and q can equal 0. Also, Dvastan gave Masha m "bad" integers a_1, a_2, ..., a_{m}, and an integer l.
Masha writes all progression terms one by one onto the board (including repetitive) while condition |b_{i}| ≤ l is satisfied (|x| means absolute value of x). There is an exception: if a term equals one of the "bad" integers, Masha skips it (doesn't write onto the board) and moves forward to the next term.
But the lesson is going to end soon, so Masha has to calculate how many integers will be written on the board. In order not to get into depression, Masha asked you for help: help her calculate how many numbers she will write, or print "inf" in case she needs to write infinitely many integers.
-----Input-----
The first line of input contains four integers b_1, q, l, m (-10^9 ≤ b_1, q ≤ 10^9, 1 ≤ l ≤ 10^9, 1 ≤ m ≤ 10^5) — the initial term and the common ratio of progression, absolute value of maximal number that can be written on the board and the number of "bad" integers, respectively.
The second line contains m distinct integers a_1, a_2, ..., a_{m} (-10^9 ≤ a_{i} ≤ 10^9) — numbers that will never be written on the board.
-----Output-----
Print the only integer, meaning the number of progression terms that will be written on the board if it is finite, or "inf" (without quotes) otherwise.
-----Examples-----
Input
3 2 30 4
6 14 25 48
Output
3
Input
123 1 2143435 4
123 11 -5453 141245
Output
0
Input
123 1 2143435 4
54343 -13 6 124
Output
inf
-----Note-----
In the first sample case, Masha will write integers 3, 12, 24. Progression term 6 will be skipped because it is a "bad" integer. Terms bigger than 24 won't be written because they exceed l by absolute value.
In the second case, Masha won't write any number because all terms are equal 123 and this is a "bad" integer.
In the third case, Masha will write infinitely integers 123.
|
{"inputs": ["2 2 4 1\n2\n", "0 8 5 1\n9\n", "2 0 1 1\n2\n", "2 0 2 1\n2\n", "4 0 4 1\n0\n", "2 2 4 1\n3\n", "0 1 1 1\n0\n", "3 1 3 1\n5\n"], "outputs": ["1", "inf", "0", "inf", "1", "2", "0", "inf"]}
| 701
| 126
|
coding
|
Solve the programming task below in a Python markdown code block.
You are given a string $s$ consisting of $n$ characters. Each character of $s$ is either 0 or 1.
A substring of $s$ is a contiguous subsequence of its characters.
You have to choose two substrings of $s$ (possibly intersecting, possibly the same, possibly non-intersecting — just any two substrings). After choosing them, you calculate the value of the chosen pair of substrings as follows:
let $s_1$ be the first substring, $s_2$ be the second chosen substring, and $f(s_i)$ be the integer such that $s_i$ is its binary representation (for example, if $s_i$ is 11010, $f(s_i) = 26$);
the value is the bitwise OR of $f(s_1)$ and $f(s_2)$.
Calculate the maximum possible value you can get, and print it in binary representation without leading zeroes.
-----Input-----
The first line contains one integer $n$ — the number of characters in $s$.
The second line contains $s$ itself, consisting of exactly $n$ characters 0 and/or 1.
All non-example tests in this problem are generated randomly: every character of $s$ is chosen independently of other characters; for each character, the probability of it being 1 is exactly $\frac{1}{2}$.
This problem has exactly $40$ tests. Tests from $1$ to $3$ are the examples; tests from $4$ to $40$ are generated randomly. In tests from $4$ to $10$, $n = 5$; in tests from $11$ to $20$, $n = 1000$; in tests from $21$ to $40$, $n = 10^6$.
Hacks are forbidden in this problem.
-----Output-----
Print the maximum possible value you can get in binary representation without leading zeroes.
-----Examples-----
Input
5
11010
Output
11111
Input
7
1110010
Output
1111110
Input
4
0000
Output
0
-----Note-----
In the first example, you can choose the substrings 11010 and 101. $f(s_1) = 26$, $f(s_2) = 5$, their bitwise OR is $31$, and the binary representation of $31$ is 11111.
In the second example, you can choose the substrings 1110010 and 11100.
|
{"inputs": ["4\n0000\n", "5\n11010\n", "5\n10110\n", "5\n10111\n", "5\n11011\n", "5\n11000\n", "5\n10000\n", "5\n10110\n"], "outputs": ["0\n", "11111\n", "11111\n", "11111\n", "11111\n", "11110\n", "11000\n", "11111\n"]}
| 586
| 145
|
coding
|
Solve the programming task below in a Python markdown code block.
Andrewid the Android is a galaxy-famous detective. He is now investigating the case of vandalism at the exhibition of contemporary art.
The main exhibit is a construction of n matryoshka dolls that can be nested one into another. The matryoshka dolls are numbered from 1 to n. A matryoshka with a smaller number can be nested in a matryoshka with a higher number, two matryoshkas can not be directly nested in the same doll, but there may be chain nestings, for example, 1 → 2 → 4 → 5.
In one second, you can perform one of the two following operations: Having a matryoshka a that isn't nested in any other matryoshka and a matryoshka b, such that b doesn't contain any other matryoshka and is not nested in any other matryoshka, you may put a in b; Having a matryoshka a directly contained in matryoshka b, such that b is not nested in any other matryoshka, you may get a out of b.
According to the modern aesthetic norms the matryoshka dolls on display were assembled in a specific configuration, i.e. as several separate chains of nested matryoshkas, but the criminal, following the mysterious plan, took out all the dolls and assembled them into a single large chain (1 → 2 → ... → n). In order to continue the investigation Andrewid needs to know in what minimum time it is possible to perform this action.
-----Input-----
The first line contains integers n (1 ≤ n ≤ 10^5) and k (1 ≤ k ≤ 10^5) — the number of matryoshkas and matryoshka chains in the initial configuration.
The next k lines contain the descriptions of the chains: the i-th line first contains number m_{i} (1 ≤ m_{i} ≤ n), and then m_{i} numbers a_{i}1, a_{i}2, ..., a_{im}_{i} — the numbers of matryoshkas in the chain (matryoshka a_{i}1 is nested into matryoshka a_{i}2, that is nested into matryoshka a_{i}3, and so on till the matryoshka a_{im}_{i} that isn't nested into any other matryoshka).
It is guaranteed that m_1 + m_2 + ... + m_{k} = n, the numbers of matryoshkas in all the chains are distinct, in each chain the numbers of matryoshkas follow in the ascending order.
-----Output-----
In the single line print the minimum number of seconds needed to assemble one large chain from the initial configuration.
-----Examples-----
Input
3 2
2 1 2
1 3
Output
1
Input
7 3
3 1 3 7
2 2 5
2 4 6
Output
10
-----Note-----
In the first sample test there are two chains: 1 → 2 and 3. In one second you can nest the first chain into the second one and get 1 → 2 → 3.
In the second sample test you need to disassemble all the three chains into individual matryoshkas in 2 + 1 + 1 = 4 seconds and then assemble one big chain in 6 seconds.
|
{"inputs": ["1 1\n1 1\n", "1 1\n1 1\n", "3 2\n2 1 2\n1 3\n", "3 2\n1 2\n2 1 3\n", "3 2\n1 2\n2 1 3\n", "3 2\n2 1 2\n1 3\n", "5 3\n1 4\n3 1 2 3\n1 5\n", "5 3\n1 4\n3 1 2 3\n1 5\n"], "outputs": ["0\n", "0", "1\n", "3\n", "3", "1", "2\n", "2"]}
| 742
| 162
|
coding
|
Solve the programming task below in a Python markdown code block.
Watson gives Sherlock an array of integers. His challenge is to find an element of the array such that the sum of all elements to the left is equal to the sum of all elements to the right.
Example
$arr=[5,6,8,11]$
$8$ is between two subarrays that sum to $\mbox{11}$.
$arr=[1]$
The answer is $[1]$ since left and right sum to $0$.
You will be given arrays of integers and must determine whether there is an element that meets the criterion. If there is, return YES. Otherwise, return NO.
Function Description
Complete the balancedSums function in the editor below.
balancedSums has the following parameter(s):
int arr[n]: an array of integers
Returns
string: either YES or NO
Input Format
The first line contains $T$, the number of test cases.
The next $T$ pairs of lines each represent a test case.
- The first line contains $n$, the number of elements in the array $arr$.
- The second line contains $n$ space-separated integers $arr[i]$ where $0\leq i<n$.
Constraints
$1\leq T\leq10$
$1\leq n\leq10^5$
$1\leq\textit{arr}[i]\leq2\times10^4$
$0\leq i<n$
Sample Input 0
2
3
1 2 3
4
1 2 3 3
Sample Output 0
NO
YES
Explanation 0
For the first test case, no such index exists.
For the second test case, $arr[0]+ar r[1]=ar r[3]$, therefore index $2$ satisfies the given conditions.
Sample Input 1
3
5
1 1 4 1 1
4
2 0 0 0
4
0 0 2 0
Sample Output 1
YES
YES
YES
Explanation 1
In the first test case, $arr[2]=4$ is between two subarrays summing to $2$.
In the second case, $arr[0]=2$ is between two subarrays summing to $0$.
In the third case, $arr[2]=2$ is between two subarrays summing to $0$.
|
{"inputs": ["2\n3\n1 2 3\n4\n1 2 3 3\n", "3\n5\n1 1 4 1 1\n4\n2 0 0 0\n4\n0 0 2 0 \n"], "outputs": ["NO\nYES\n", "YES\nYES\nYES\n"]}
| 536
| 79
|
coding
|
Solve the programming task below in a Python markdown code block.
It seems that Borya is seriously sick. He is going visit n doctors to find out the exact diagnosis. Each of the doctors needs the information about all previous visits, so Borya has to visit them in the prescribed order (i.e. Borya should first visit doctor 1, then doctor 2, then doctor 3 and so on). Borya will get the information about his health from the last doctor.
Doctors have a strange working schedule. The doctor i goes to work on the s_{i}-th day and works every d_{i} day. So, he works on days s_{i}, s_{i} + d_{i}, s_{i} + 2d_{i}, ....
The doctor's appointment takes quite a long time, so Borya can not see more than one doctor per day. What is the minimum time he needs to visit all doctors?
-----Input-----
First line contains an integer n — number of doctors (1 ≤ n ≤ 1000).
Next n lines contain two numbers s_{i} and d_{i} (1 ≤ s_{i}, d_{i} ≤ 1000).
-----Output-----
Output a single integer — the minimum day at which Borya can visit the last doctor.
-----Examples-----
Input
3
2 2
1 2
2 2
Output
4
Input
2
10 1
6 5
Output
11
-----Note-----
In the first sample case, Borya can visit all doctors on days 2, 3 and 4.
In the second sample case, Borya can visit all doctors on days 10 and 11.
|
{"inputs": ["1\n1 1\n", "1\n1 1\n", "1\n8 3\n", "1\n8 1\n", "1\n10 3\n", "1\n10 10\n", "1\n10 10\n", "1\n10 13\n"], "outputs": ["1\n", "1\n", "8\n", "8\n", "10\n", "10\n", "10\n", "10\n"]}
| 370
| 113
|
coding
|
Solve the programming task below in a Python markdown code block.
You are given a rectangular board of M × N squares. Also you are given an unlimited number of standard domino pieces of 2 × 1 squares. You are allowed to rotate the pieces. You are asked to place as many dominoes as possible on the board so as to meet the following conditions:
1. Each domino completely covers two squares.
2. No two dominoes overlap.
3. Each domino lies entirely inside the board. It is allowed to touch the edges of the board.
Find the maximum number of dominoes, which can be placed under these restrictions.
Input
In a single line you are given two integers M and N — board sizes in squares (1 ≤ M ≤ N ≤ 16).
Output
Output one number — the maximal number of dominoes, which can be placed.
Examples
Input
2 4
Output
4
Input
3 3
Output
4
|
{"inputs": ["2 6\n", "1 5\n", "3 6\n", "2 5\n", "2 7\n", "4 4\n", "5 7\n", "2 2\n"], "outputs": ["6\n", "2\n", "9\n", "5\n", "7\n", "8\n", "17\n", "2\n"]}
| 204
| 87
|
coding
|
Solve the programming task below in a Python markdown code block.
A cheetah and a cheater are going to play the game of Nim. In this game they use N piles of stones. Initially the i-th pile contains a_i stones. The players take turns alternately, and the cheetah plays first. In each turn, the player chooses one of the piles, and takes one or more stones from the pile. The player who can't make a move loses.
However, before the game starts, the cheater wants to cheat a bit to make sure that he can win regardless of the moves by the cheetah. From each pile, the cheater takes zero or one stone and eats it before the game. In case there are multiple ways to guarantee his winning, he wants to minimize the number of stones he eats.
Compute the number of stones the cheater will eat. In case there is no way for the cheater to win the game even with the cheating, print `-1` instead.
Constraints
* 1 ≤ N ≤ 10^5
* 2 ≤ a_i ≤ 10^9
Input
The input is given from Standard Input in the following format:
N
a_1
:
a_N
Output
Print the answer.
Examples
Input
3
2
3
4
Output
3
Input
3
100
100
100
Output
-1
|
{"inputs": ["3\n3\n3\n4", "3\n2\n3\n3", "3\n2\n1\n3", "3\n4\n5\n8", "3\n3\n5\n4", "3\n3\n4\n4", "3\n3\n5\n8", "3\n3\n1\n4"], "outputs": ["-1\n", "2\n", "0\n", "3\n", "-1\n", "-1\n", "2\n", "2\n"]}
| 299
| 111
|
coding
|
Solve the programming task below in a Python markdown code block.
Let's call a binary string $T$ of length $m$ indexed from $1$ to $m$ paranoid if we can obtain a string of length $1$ by performing the following two kinds of operations $m-1$ times in any order :
Select any substring of $T$ that is equal to 01, and then replace it with 1.
Select any substring of $T$ that is equal to 10, and then replace it with 0.
For example, if $T = $ 001, we can select the substring $[T_2T_3]$ and perform the first operation. So we obtain $T = $ 01.
You are given a binary string $S$ of length $n$ indexed from $1$ to $n$. Find the number of pairs of integers $(l, r)$ $1 \le l \le r \le n$ such that $S[l \ldots r]$ (the substring of $S$ from $l$ to $r$) is a paranoid string.
-----Input-----
The first line contains an integer $t$ ($1 \le t \le 1000$) — the number of test cases. The description of test cases follows.
The first line of each test case contains a single integer $n$ ($1 \le n \le 2 \cdot 10^5$) — the size of $S$.
The second line of each test case contains a binary string $S$ of $n$ characters $S_1S_2 \ldots S_n$. ($S_i = $ 0 or $S_i = $ 1 for each $1 \le i \le n$)
It is guaranteed that the sum of $n$ over all test cases doesn't exceed $2 \cdot 10^5$.
-----Output-----
For each test case, output the number of pairs of integers $(l, r)$ $1 \le l \le r \le n$ such that $S[l \ldots r]$ (the substring of $S$ from $l$ to $r$) is a paranoid string.
-----Examples-----
Input
5
1
1
2
01
3
100
4
1001
5
11111
Output
1
3
4
8
5
-----Note-----
In the first sample, $S$ already has length $1$ and doesn't need any operations.
In the second sample, all substrings of $S$ are paranoid. For the entire string, it's enough to perform the first operation.
In the third sample, all substrings of $S$ are paranoid except $[S_2S_3]$, because we can't perform any operations on it, and $[S_1S_2S_3]$ (the entire string).
|
{"inputs": ["5\n1\n1\n2\n01\n3\n100\n4\n1001\n5\n11111\n"], "outputs": ["1\n3\n4\n8\n5\n"]}
| 619
| 52
|
coding
|
Solve the programming task below in a Python markdown code block.
Just in case somebody missed it: this winter is totally cold in Nvodsk! It is so cold that one gets funny thoughts. For example, let's say there are strings with the length exactly n, based on the alphabet of size m. Any its substring with length equal to k is a palindrome. How many such strings exist? Your task is to find their quantity modulo 1000000007 (109 + 7). Be careful and don't miss a string or two!
Let us remind you that a string is a palindrome if it can be read the same way in either direction, from the left to the right and from the right to the left.
Input
The first and only line contains three integers: n, m and k (1 ≤ n, m, k ≤ 2000).
Output
Print a single integer — the number of strings of the described type modulo 1000000007 (109 + 7).
Examples
Input
1 1 1
Output
1
Input
5 2 4
Output
2
Note
In the first sample only one string is valid: "a" (let's denote the only letter of our alphabet as "a").
In the second sample (if we denote the alphabet letters as "a" and "b") the following strings are valid: "aaaaa" and "bbbbb".
|
{"inputs": ["5 2 5\n", "5 4 5\n", "3 5 3\n", "3 3 3\n", "7 2 7\n", "5 5 5\n", "4 4 1\n", "5 5 1\n"], "outputs": ["8", "64", "25", "9", "16", "125", "256", "3125"]}
| 310
| 104
|
coding
|
Solve the programming task below in a Python markdown code block.
Arkady wants to water his only flower. Unfortunately, he has a very poor watering system that was designed for $n$ flowers and so it looks like a pipe with $n$ holes. Arkady can only use the water that flows from the first hole.
Arkady can block some of the holes, and then pour $A$ liters of water into the pipe. After that, the water will flow out from the non-blocked holes proportionally to their sizes $s_1, s_2, \ldots, s_n$. In other words, if the sum of sizes of non-blocked holes is $S$, and the $i$-th hole is not blocked, $\frac{s_i \cdot A}{S}$ liters of water will flow out of it.
What is the minimum number of holes Arkady should block to make at least $B$ liters of water flow out of the first hole?
-----Input-----
The first line contains three integers $n$, $A$, $B$ ($1 \le n \le 100\,000$, $1 \le B \le A \le 10^4$) — the number of holes, the volume of water Arkady will pour into the system, and the volume he wants to get out of the first hole.
The second line contains $n$ integers $s_1, s_2, \ldots, s_n$ ($1 \le s_i \le 10^4$) — the sizes of the holes.
-----Output-----
Print a single integer — the number of holes Arkady should block.
-----Examples-----
Input
4 10 3
2 2 2 2
Output
1
Input
4 80 20
3 2 1 4
Output
0
Input
5 10 10
1000 1 1 1 1
Output
4
-----Note-----
In the first example Arkady should block at least one hole. After that, $\frac{10 \cdot 2}{6} \approx 3.333$ liters of water will flow out of the first hole, and that suits Arkady.
In the second example even without blocking any hole, $\frac{80 \cdot 3}{10} = 24$ liters will flow out of the first hole, that is not less than $20$.
In the third example Arkady has to block all holes except the first to make all water flow out of the first hole.
|
{"inputs": ["1 1 1\n1\n", "1 2 1\n1\n", "1 2 1\n1\n", "1 1 1\n1\n", "1 2 1\n2\n", "1 1 1\n2\n", "1 2 2\n2\n", "1 2 2\n4\n"], "outputs": ["0\n", "0\n", "0\n", "0\n", "0\n", "0\n", "0\n", "0\n"]}
| 551
| 118
|
coding
|
Solve the programming task below in a Python markdown code block.
Write
```python
function repeating_fractions(numerator, denominator)
```
that given two numbers representing the numerator and denominator of a fraction, return the fraction in string format. If the fractional part has repeated digits, replace those digits with a single digit in parentheses.
For example:
```python
repeating_fractions(1,1) === '1'
repeating_fractions(1,3) === '0.(3)'
repeating_fractions(2,888) === '0.(0)(2)5(2)5(2)5(2)5(2)5(2)'
```
Also feel free to reuse/extend the following starter code:
```python
def repeating_fractions(n,d):
```
|
{"functional": "_inputs = [[0, 1], [18018018, 80000000000], [1, 1], [1, 2], [1, 3], [1554, 70]]\n_outputs = [['0.0'], ['0.(0)(2)5(2)5(2)5'], ['1.0'], ['0.5'], ['0.(3)'], ['22.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(repeating_fractions(*i), o[0])"}
| 171
| 252
|
coding
|
Please solve the programming task below using a self-contained code snippet in a markdown code block.
Given an array of integers arr and an integer k.
A value arr[i] is said to be stronger than a value arr[j] if |arr[i] - m| > |arr[j] - m| where m is the median of the array.
If |arr[i] - m| == |arr[j] - m|, then arr[i] is said to be stronger than arr[j] if arr[i] > arr[j].
Return a list of the strongest k values in the array. return the answer in any arbitrary order.
Median is the middle value in an ordered integer list. More formally, if the length of the list is n, the median is the element in position ((n - 1) / 2) in the sorted list (0-indexed).
For arr = [6, -3, 7, 2, 11], n = 5 and the median is obtained by sorting the array arr = [-3, 2, 6, 7, 11] and the median is arr[m] where m = ((5 - 1) / 2) = 2. The median is 6.
For arr = [-7, 22, 17, 3], n = 4 and the median is obtained by sorting the array arr = [-7, 3, 17, 22] and the median is arr[m] where m = ((4 - 1) / 2) = 1. The median is 3.
Please complete the following python code precisely:
```python
class Solution:
def getStrongest(self, arr: List[int], k: int) -> List[int]:
```
|
{"functional": "def check(candidate):\n assert candidate(arr = [1,2,3,4,5], k = 2) == [5,1]\n assert candidate(arr = [1,1,3,5,5], k = 2) == [5,5]\n assert candidate(arr = [6,7,11,7,6,8], k = 5) == [11,8,6,6,7]\n assert candidate(arr = [6,-3,7,2,11], k = 3) == [-3,11,2]\n assert candidate(arr = [-7,22,17,3], k = 2) == [22,17]\n\n\ncheck(Solution().getStrongest)"}
| 370
| 176
|
coding
|
Solve the programming task below in a Python markdown code block.
Ram and Shyam are sitting next to each other, hoping to cheat on an exam. However, the examination board has prepared $p$ different sets of questions (numbered $0$ through $p-1$), which will be distributed to the students in the following way:
- The students are assigned roll numbers — pairwise distinct positive integers.
- If a student's roll number is $r$, this student gets the $((r-1)\%p)$-th set of questions.
Obviously, Ram and Shyam can cheat only if they get the same set of questions.
You are given the roll numbers of Ram and Shyam: $A$ and $B$ respectively. Find the number of values of $p$ for which they can cheat, or determine that there is an infinite number of such values.
-----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 $A$ and $B$.
-----Output-----
For each test case, print a single line — the number of values of $p$ for which Ram and Shyam can cheat, or $-1$ if there is an infinite number of such values.
-----Constraints-----
- $1 \le T \le 100$
- $1 \le A, B \le 10^8$
-----Example Input-----
1
2 6
-----Example Output-----
3
-----Explanation-----
Example case 1: They can cheat for $p = 1$, $p = 2$ or $p = 4$.
|
{"inputs": ["1\n2 6"], "outputs": ["3"]}
| 365
| 16
|
coding
|
Solve the programming task below in a Python markdown code block.
Read problems statements in Mandarin chinese, Russian and Vietnamese as well.
You are a poor person in ChocoLand. Here, people eat chocolates daily instead of normal food. There is only one shop near your home; this shop is closed on Sunday, but open on all other days of the week. You may buy at most one box of N chocolates from this shop on each day when it is open.
Currently, it's Monday, and you need to survive for the next S days (including the current day). You have to eat K chocolates everyday (including the current day) to survive. Do note that you are allowed to buy the a chocolate box and eat from it on the same day.
Compute the minimum number of days on which you need to buy from the shop so that you can survive the next S days, or determine that it isn't possible to survive.
------ 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 3 integers N, K and S denoting the number of chocolates in a box, the number of chocolates you have to eat everyday to survive and the number of days you need to survive.
------ Output ------
For each test case, print a single line containing one integer — the minimum number of days on which you need to buy from the shop to survive, or -1 if you will not be able to survive S days.
------ Constraints ------
$1 ≤ T ≤ 100$
$1 ≤ N ≤ 100$
$1 ≤ K ≤ 100$
$1 ≤ S ≤ 1000$
----- Sample Input 1 ------
2
16 2 10
50 48 7
----- Sample Output 1 ------
2
-1
----- explanation 1 ------
Example case 1: One possible solution is to buy a box on day 1 (Monday); it's sufficient to eat from this box up to day 8 (Monday) inclusive. Now, on day 9 (Tuesday), you buy another box and use the chocolates in it to survive days 9 and 10.
Example case 2: You will not be able to survive even if you buy from the shop everyday except every 7-th day.
|
{"inputs": ["2\n16 2 10\n50 48 7"], "outputs": ["2\n-1"]}
| 499
| 31
|
coding
|
Solve the programming task below in a Python markdown code block.
A famous Berland's painter Kalevitch likes to shock the public. One of his last obsessions is chess. For more than a thousand years people have been playing this old game on uninteresting, monotonous boards. Kalevitch decided to put an end to this tradition and to introduce a new attitude to chessboards.
As before, the chessboard is a square-checkered board with the squares arranged in a 8 × 8 grid, each square is painted black or white. Kalevitch suggests that chessboards should be painted in the following manner: there should be chosen a horizontal or a vertical line of 8 squares (i.e. a row or a column), and painted black. Initially the whole chessboard is white, and it can be painted in the above described way one or more times. It is allowed to paint a square many times, but after the first time it does not change its colour any more and remains black. Kalevitch paints chessboards neatly, and it is impossible to judge by an individual square if it was painted with a vertical or a horizontal stroke.
Kalevitch hopes that such chessboards will gain popularity, and he will be commissioned to paint chessboards, which will help him ensure a comfortable old age. The clients will inform him what chessboard they want to have, and the painter will paint a white chessboard meeting the client's requirements.
It goes without saying that in such business one should economize on everything — for each commission he wants to know the minimum amount of strokes that he has to paint to fulfill the client's needs. You are asked to help Kalevitch with this task.
Input
The input file contains 8 lines, each of the lines contains 8 characters. The given matrix describes the client's requirements, W character stands for a white square, and B character — for a square painted black.
It is guaranteed that client's requirments can be fulfilled with a sequence of allowed strokes (vertical/column or horizontal/row).
Output
Output the only number — the minimum amount of rows and columns that Kalevitch has to paint on the white chessboard to meet the client's requirements.
Examples
Input
WWWBWWBW
BBBBBBBB
WWWBWWBW
WWWBWWBW
WWWBWWBW
WWWBWWBW
WWWBWWBW
WWWBWWBW
Output
3
Input
WWWWWWWW
BBBBBBBB
WWWWWWWW
WWWWWWWW
WWWWWWWW
WWWWWWWW
WWWWWWWW
WWWWWWWW
Output
1
|
{"inputs": ["BBBBBBBB\nWBWWBBBW\nBBBBBBBB\nWBWWBBBW\nWBWWBBBW\nWBWWBBBW\nWBWWBBBW\nBBBBBBBB\n", "BBBBBBBB\nBBBBBBBB\nBBBBBBBB\nBBBBBBBB\nBBBBBBBB\nBBBBBBBB\nBBBBBBBB\nBWBBWBWB\n", "BBBBBBBB\nWWWBBBBB\nWWWBBBBB\nBBBBBBBB\nWWWBBBBB\nWWWBBBBB\nBBBBBBBB\nBBBBBBBB\n", "BBBBBBBB\nBBBBBBBB\nBBBBBBBB\nBBBBBBBB\nBBBBBBBB\nBBBBBBBB\nBBBBBBBB\nBBBBBBBB\n", "BBBBBBBB\nWBBBWBBW\nBBBBBBBB\nWBBBWBBW\nWBBBWBBW\nBBBBBBBB\nBBBBBBBB\nWBBBWBBW\n", "BWBBBWWB\nBWBBBWWB\nBBBBBBBB\nBBBBBBBB\nBWBBBWWB\nBBBBBBBB\nBBBBBBBB\nBBBBBBBB\n", "BWBBBBWW\nBWBBBBWW\nBWBBBBWW\nBWBBBBWW\nBBBBBBBB\nBWBBBBWW\nBWBBBBWW\nBBBBBBBB\n", "BBBBBBBB\nBBBBBBBB\nBBBBBBBB\nWBBBWBBW\nBBBBBBBB\nBBBBBBBB\nWBBBWBBW\nBBBBBBBB\n"], "outputs": ["7\n", "12\n", "9\n", "8\n", "9\n", "10\n", "7\n", "11\n"]}
| 542
| 298
|
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 forts of length n representing the positions of several forts. forts[i] can be -1, 0, or 1 where:
-1 represents there is no fort at the ith position.
0 indicates there is an enemy fort at the ith position.
1 indicates the fort at the ith the position is under your command.
Now you have decided to move your army from one of your forts at position i to an empty position j such that:
0 <= i, j <= n - 1
The army travels over enemy forts only. Formally, for all k where min(i,j) < k < max(i,j), forts[k] == 0.
While moving the army, all the enemy forts that come in the way are captured.
Return the maximum number of enemy forts that can be captured. In case it is impossible to move your army, or you do not have any fort under your command, return 0.
Please complete the following python code precisely:
```python
class Solution:
def captureForts(self, forts: List[int]) -> int:
```
|
{"functional": "def check(candidate):\n assert candidate(forts = [1,0,0,-1,0,0,0,0,1]) == 4\n assert candidate(forts = [0,0,1,-1]) == 0\n\n\ncheck(Solution().captureForts)"}
| 246
| 68
|
coding
|
Please solve the programming task below using a self-contained code snippet in a markdown code block.
Given a directed acyclic graph, with n vertices numbered from 0 to n-1, and an array edges where edges[i] = [fromi, toi] represents a directed edge from node fromi to node toi.
Find the smallest set of vertices from which all nodes in the graph are reachable. It's guaranteed that a unique solution exists.
Notice that you can return the vertices in any order.
Please complete the following python code precisely:
```python
class Solution:
def findSmallestSetOfVertices(self, n: int, edges: List[List[int]]) -> List[int]:
```
|
{"functional": "def check(candidate):\n assert candidate(n = 6, edges = [[0,1],[0,2],[2,5],[3,4],[4,2]]) == [0,3]\n assert candidate(n = 5, edges = [[0,1],[2,1],[3,1],[1,4],[2,4]]) == [0,2,3]\n\n\ncheck(Solution().findSmallestSetOfVertices)"}
| 156
| 101
|
coding
|
Solve the programming task below in a Python markdown code block.
The little girl loves the problems on array queries very much.
One day she came across a rather well-known problem: you've got an array of n elements (the elements of the array are indexed starting from 1); also, there are q queries, each one is defined by a pair of integers l_{i}, r_{i} (1 ≤ l_{i} ≤ r_{i} ≤ n). You need to find for each query the sum of elements of the array with indexes from l_{i} to r_{i}, inclusive.
The little girl found the problem rather boring. She decided to reorder the array elements before replying to the queries in a way that makes the sum of query replies maximum possible. Your task is to find the value of this maximum sum.
-----Input-----
The first line contains two space-separated integers n (1 ≤ n ≤ 2·10^5) and q (1 ≤ q ≤ 2·10^5) — the number of elements in the array and the number of queries, correspondingly.
The next line contains n space-separated integers a_{i} (1 ≤ a_{i} ≤ 2·10^5) — the array elements.
Each of the following q lines contains two space-separated integers l_{i} and r_{i} (1 ≤ l_{i} ≤ r_{i} ≤ n) — the i-th query.
-----Output-----
In a single line print a single integer — the maximum sum of query replies after the array elements are reordered.
Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
-----Examples-----
Input
3 3
5 3 2
1 2
2 3
1 3
Output
25
Input
5 3
5 2 4 1 3
1 5
2 3
2 3
Output
33
|
{"inputs": ["3 2\n1 2 3\n2 3\n1 2\n", "3 2\n1 2 3\n2 3\n1 2\n", "3 2\n1 4 3\n2 3\n1 2\n", "3 2\n1 2 5\n2 3\n1 2\n", "3 2\n1 7 3\n2 3\n1 2\n", "3 3\n5 3 2\n1 2\n2 3\n1 3\n", "3 3\n5 3 3\n1 2\n2 3\n1 3\n", "3 3\n5 3 2\n1 2\n2 3\n1 2\n"], "outputs": ["9\n", "9\n", "12\n", "13\n", "18\n", "25\n", "27\n", "23\n"]}
| 431
| 216
|
coding
|
Solve the programming task below in a Python markdown code block.
A: four tea
problem
Tea is indispensable for programming contests. Tea has the effect of relieving constant tension [citation needed]
There are N players participating in the contest, so I would like to prepare tea for this number of people. There are four types of tea packages, A, B, C, and D, all of which are the same variety but have different contents. For a package X, the price of one package is p_X yen, and it is known that if you buy one, you can make t_X cups of tea.
Find the minimum amount needed to make tea for N people. You may have a package that you don't buy at all, and you don't have to buy a package for just N people (if you can make more than N people).
Input format
The input is given in the following format.
N
p_A p_B p_C p_D
t_A t_B t_C t_D
* The first line gives the number of players participating in the contest.
* In the second line, the prices of tea in packages A, B, C and D are given separated by blanks.
* The third line gives the number of cups of tea that can be made from packages A, B, C, and D, separated by blanks.
Constraint
* 1 \ leq N \ leq 100
* 1 \ leq p_X \ leq 100
* 1 \ leq t_X \ leq 100
* All inputs are given as integers.
Output format
Output the minimum amount required to make tea for N people in one line.
Input example 1
Ten
1 2 3 4
1 2 4 8
Output example 1
6
* It's best to buy one package B and one D.
Input example 2
Five
2 9 9 8
1 4 5 100
Output example 2
8
* You will have 20 times more tea than you need, but buying one Package D is the cheapest way to get more than 5 cups of tea.
Input example 3
twenty four
2 3 4 7
7 9 11 20
Output example 3
8
* It's best to buy two packages A and one C. It may not be possible to make just enough tea for the number of people as in this case.
Example
Input
10
1 2 3 4
1 2 4 8
Output
6
|
{"inputs": ["10\n1 2 3 2\n1 2 4 8", "10\n1 1 3 2\n0 2 3 8", "10\n1 2 3 4\n1 3 4 8", "10\n1 1 3 2\n0 2 3 1", "10\n0 2 1 4\n0 1 0 8", "10\n1 2 3 2\n0 0 4 3", "10\n1 1 6 2\n1 1 2 1", "10\n1 1 5 1\n0 1 6 1"], "outputs": ["4\n", "3\n", "6\n", "5\n", "8\n", "7\n", "10\n", "9\n"]}
| 550
| 199
|
coding
|
Please solve the programming task below using a self-contained code snippet in a markdown code block.
You are given two 0-indexed arrays nums1 and nums2 of length n, both of which are permutations of [0, 1, ..., n - 1].
A good triplet is a set of 3 distinct values which are present in increasing order by position both in nums1 and nums2. In other words, if we consider pos1v as the index of the value v in nums1 and pos2v as the index of the value v in nums2, then a good triplet will be a set (x, y, z) where 0 <= x, y, z <= n - 1, such that pos1x < pos1y < pos1z and pos2x < pos2y < pos2z.
Return the total number of good triplets.
Please complete the following python code precisely:
```python
class Solution:
def goodTriplets(self, nums1: List[int], nums2: List[int]) -> int:
```
|
{"functional": "def check(candidate):\n assert candidate(nums1 = [2,0,1,3], nums2 = [0,1,2,3]) == 1\n assert candidate(nums1 = [4,0,1,3,2], nums2 = [4,1,0,2,3]) == 4\n\n\ncheck(Solution().goodTriplets)"}
| 219
| 86
|
coding
|
Solve the programming task below in a Python markdown code block.
Calculate the trace of a square matrix. A square matrix has `n` rows and `n` columns, where `n` is any integer > 0. The entries of the matrix can contain any number of integers. The function should return the calculated trace of the matrix, or `nil/None` if the array is empty or not square; you can otherwise assume the input will be valid (of the form described below).
The trace of an n-by-n square matrix **A** is defined to be the sum of the elements on the main diagonal (the diagonal from the upper left to the lower right) of **A**.
A matrix will be defined as an array of arrays, where the 1st entry represents the 1st row, the 2nd entry the 2nd row, and so on.
For example, the following code...
```ruby,python
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
```
represents the matrix
```
|1 2 3|
|4 5 6|
|7 8 9|
```
which has a trace of `1 + 5 + 9 = 15`.
You can read more about the trace of a matrix at these sources:
* http://en.wikipedia.org/wiki/Trace_(linear_algebra)
* http://mathworld.wolfram.com/MatrixTrace.html
~~~if:ruby
Note: The `Matrix` class is disabled.
~~~
~~~if:python
Note: `Numpy` is disabled.
~~~
Also feel free to reuse/extend the following starter code:
```python
def trace(matrix):
```
|
{"functional": "_inputs = [[[[1, 2, 3], [4, 5, 6], [7, 8, 9]]], [[[0, 0], [0, 0]]], [[[0, 0, 0], [0, 0, 0], [0, 0, 0]]], [[[1, 0, 0], [0, 1, 0], [0, 0, -2]]], [[[0]]], [[[1]]], [[[-300]]], [[]], [[[]]], [[[1, 2], [1, 2], [1, 2]]], [[[1, 2, 3], [1, 2, 3]]]]\n_outputs = [[15], [0], [0], [0], [0], [1], [-300], [None], [None], [None], [None]]\nimport math\ndef _deep_eq(a, b, tol=1e-5):\n if isinstance(a, float) or isinstance(b, float):\n return math.isclose(a, b, rel_tol=tol, abs_tol=tol)\n if isinstance(a, (list, tuple)):\n if len(a) != len(b): return False\n return all(_deep_eq(x, y, tol) for x, y in zip(a, b))\n return a == b\n\nfor i, o in zip(_inputs, _outputs):\n assert _deep_eq(trace(*i), o[0])"}
| 367
| 339
|
coding
|
Solve the programming task below in a Python markdown code block.
# Task
Pero has been into robotics recently, so he decided to make a robot that checks whether a deck of poker cards is complete.
He’s already done a fair share of work - he wrote a programme that recognizes the suits of the cards. For simplicity’s sake, we can assume that all cards have a suit and a number.
The suit of the card is one of the characters `"P", "K", "H", "T"`, and the number of the card is an integer between `1` and `13`. The robot labels each card in the format `TXY` where `T` is the suit and `XY` is the number. If the card’s number consists of one digit, then X = 0. For example, the card of suit `"P"` and number `9` is labelled `"P09"`.
A complete deck has `52` cards in total. For each of the four suits there is exactly one card with a number between `1` and `13`.
The robot has read the labels of all the cards in the deck and combined them into the string `s`.
Your task is to help Pero finish the robot by writing a program that reads the string made out of card labels and returns the number of cards that are missing for each suit.
If there are two same cards in the deck, return array with `[-1, -1, -1, -1]` instead.
# Input/Output
- `[input]` string `s`
A correct string of card labels. 0 ≤ |S| ≤ 1000
- `[output]` an integer array
Array of four elements, representing the number of missing card of suits `"P", "K", "H", and "T"` respectively. If there are two same cards in the deck, return `[-1, -1, -1, -1]` instead.
# Example
For `s = "P01K02H03H04"`, the output should be `[12, 12, 11, 13]`.
`1` card from `"P"` suit, `1` card from `"K"` suit, `2` cards from `"H"` suit, no card from `"T"` suit.
For `s = "H02H10P11H02"`, the output should be `[-1, -1, -1, -1]`.
There are two same cards `"H02"` in the string `s`.
Also feel free to reuse/extend the following starter code:
```python
def cards_and_pero(s):
```
|
{"functional": "_inputs = [['P01K02H03H04'], ['H02H10P11H02'], ['P10K10H10T01'], ['P05P01P02P03P13P09P11P07K01P12K03K02K13K12K10K08H03H02H13H12H10H08T01T03T02T13T12T10T08P04K07H02T07H06T11K11T05K05H05H11'], ['P01K02P03P11K09K10P13P10']]\n_outputs = [[[12, 12, 11, 13]], [[-1, -1, -1, -1]], [[12, 12, 12, 12]], [[-1, -1, -1, -1]], [[8, 10, 13, 13]]]\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(cards_and_pero(*i), o[0])"}
| 570
| 413
|
coding
|
Please solve the programming task below using a self-contained code snippet in a markdown code block.
You are given a 0-indexed binary string s of length n on which you can apply two types of operations:
Choose an index i and invert all characters from index 0 to index i (both inclusive), with a cost of i + 1
Choose an index i and invert all characters from index i to index n - 1 (both inclusive), with a cost of n - i
Return the minimum cost to make all characters of the string equal.
Invert a character means if its value is '0' it becomes '1' and vice-versa.
Please complete the following python code precisely:
```python
class Solution:
def minimumCost(self, s: str) -> int:
```
|
{"functional": "def check(candidate):\n assert candidate(s = \"0011\") == 2\n assert candidate(s = \"010101\") == 9\n\n\ncheck(Solution().minimumCost)"}
| 169
| 51
|
coding
|
Solve the programming task below in a Python markdown code block.
A palindrome is a word, phrase, number, or other sequence of characters which reads the same backward as forward. Examples of numerical palindromes are:
2332
110011
54322345
For a given number ```num```, write a function which returns the number of numerical palindromes within each number. For this kata, single digit numbers will NOT be considered numerical palindromes.
Return "Not valid" if the input is not an integer or is less than 0.
```
palindrome(5) => 0
palindrome(1221) => 2
palindrome(141221001) => 5
palindrome(1294) => 0
palindrome("1221") => "Not valid"
```
```Haskell
In Haskell, return a Maybe Int with Nothing for negative numbers.
```
Other Kata in this Series:
Numerical Palindrome #1
Numerical Palindrome #1.5
Numerical Palindrome #2
Numerical Palindrome #3
Numerical Palindrome #3.5
Numerical Palindrome #4
Numerical Palindrome #5
Also feel free to reuse/extend the following starter code:
```python
def palindrome(num):
```
|
{"functional": "_inputs = [[2], [141221001], [1551], [13598], ['ACCDDCCA'], ['1551'], [-4505]]\n_outputs = [[0], [5], [2], [0], ['Not valid'], ['Not valid'], ['Not valid']]\nimport math\ndef _deep_eq(a, b, tol=1e-5):\n if isinstance(a, float) or isinstance(b, float):\n return math.isclose(a, b, rel_tol=tol, abs_tol=tol)\n if isinstance(a, (list, tuple)):\n if len(a) != len(b): return False\n return all(_deep_eq(x, y, tol) for x, y in zip(a, b))\n return a == b\n\nfor i, o in zip(_inputs, _outputs):\n assert _deep_eq(palindrome(*i), o[0])"}
| 294
| 217
|
coding
|
Solve the programming task below in a Python markdown code block.
You have a positive integer m and a non-negative integer s. Your task is to find the smallest and the largest of the numbers that have length m and sum of digits s. The required numbers should be non-negative integers written in the decimal base without leading zeroes.
-----Input-----
The single line of the input contains a pair of integers m, s (1 ≤ m ≤ 100, 0 ≤ s ≤ 900) — the length and the sum of the digits of the required numbers.
-----Output-----
In the output print the pair of the required non-negative integer numbers — first the minimum possible number, then — the maximum possible number. If no numbers satisfying conditions required exist, print the pair of numbers "-1 -1" (without the quotes).
-----Examples-----
Input
2 15
Output
69 96
Input
3 0
Output
-1 -1
|
{"inputs": ["3 0\n", "2 1\n", "1 9\n", "1 0\n", "1 1\n", "1 2\n", "1 8\n", "2 0\n"], "outputs": ["-1 -1\n", "10 10\n", "9 9\n", "0 0\n", "1 1\n", "2 2\n", "8 8\n", "-1 -1\n"]}
| 200
| 105
|
coding
|
Solve the programming task below in a Python markdown code block.
Your job is to write a function that takes a string and a maximum number of characters per line and then inserts line breaks as necessary so that no line in the resulting string is longer than the specified limit.
If possible, line breaks should not split words. However, if a single word is longer than the limit, it obviously has to be split. In this case, the line break should be placed after the first part of the word (see examples below).
Really long words may need to be split multiple times.
#Input
A word consists of one or more letters.
Input text will be the empty string or a string consisting of one or more words separated by single spaces. It will not contain any punctiation or other special characters.
The limit will always be an integer greater or equal to one.
#Examples
**Note:** Line breaks in the results have been replaced with two dashes to improve readability.
1. ("test", 7) -> "test"
2. ("hello world", 7) -> "hello--world"
3. ("a lot of words for a single line", 10) -> "a lot of--words for--a single--line"
4. ("this is a test", 4) -> "this--is a--test"
5. ("a longword", 6) -> "a long--word"
6. ("areallylongword", 6) -> "areall--ylongw--ord"
**Note:** Sometimes spaces are hard to see in the test results window.
Also feel free to reuse/extend the following starter code:
```python
def word_wrap(text, limit):
```
|
{"functional": "_inputs = [['test', 7], ['hello world', 7], ['a lot of words for a single line', 10], ['this is a test', 4], ['a longword', 6], ['areallylongword', 6], ['aa', 3], ['aaa', 3], ['aaaa', 3], ['a a', 3], ['a aa', 3], ['a aaa', 3], ['a aaaa', 3], ['a aaaaa', 3], ['a a a', 3], ['a aa a', 3], ['a aaa a', 3], ['a aaaa a', 3], ['a aaaaa a', 3], ['a a aaa', 3], ['a aa aaa', 3], ['a aaa aaa', 3], ['a aaaa aaa', 3], ['a aaaaa aaa', 3], ['aaa aaaa a', 3], ['a b c dd eee ffff g hhhhh i', 3]]\n_outputs = [['test'], ['hello\\nworld'], ['a lot of\\nwords for\\na single\\nline'], ['this\\nis a\\ntest'], ['a long\\nword'], ['areall\\nylongw\\nord'], ['aa'], ['aaa'], ['aaa\\na'], ['a a'], ['a\\naa'], ['a\\naaa'], ['a a\\naaa'], ['a a\\naaa\\na'], ['a a\\na'], ['a\\naa\\na'], ['a\\naaa\\na'], ['a a\\naaa\\na'], ['a a\\naaa\\na a'], ['a a\\naaa'], ['a\\naa\\naaa'], ['a\\naaa\\naaa'], ['a a\\naaa\\naaa'], ['a a\\naaa\\na\\naaa'], ['aaa\\naaa\\na a'], ['a b\\nc\\ndd\\neee\\nfff\\nf g\\nhhh\\nhh\\ni']]\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(word_wrap(*i), o[0])"}
| 349
| 584
|
coding
|
Please solve the programming task below using a self-contained code snippet in a markdown code block.
Given an array of integers cost and an integer target, return the maximum integer you can paint under the following rules:
The cost of painting a digit (i + 1) is given by cost[i] (0-indexed).
The total cost used must be equal to target.
The integer does not have 0 digits.
Since the answer may be very large, return it as a string. If there is no way to paint any integer given the condition, return "0".
Please complete the following python code precisely:
```python
class Solution:
def largestNumber(self, cost: List[int], target: int) -> str:
```
|
{"functional": "def check(candidate):\n assert candidate(cost = [4,3,2,5,6,7,2,5,5], target = 9) == \"7772\"\n assert candidate(cost = [7,6,5,5,5,6,8,7,8], target = 12) == \"85\"\n assert candidate(cost = [2,4,6,2,4,6,4,4,4], target = 5) == \"0\"\n assert candidate(cost = [6,10,15,40,40,40,40,40,40], target = 47) == \"32211\"\n\n\ncheck(Solution().largestNumber)"}
| 148
| 174
|
coding
|
Solve the programming task below in a Python markdown code block.
Sunuke received a d-dimensional hypercube with a side length of l1 × ... × ld as a birthday present. Sunuke placed this rectangular parallelepiped so that the range of the i-th coordinate was 0 or more and li or less, and ate the part that satisfied x1 + ... + xd ≤ s. However, xi represents the i-th coordinate. If the volume of the part eaten by Sunuke is V, it can be proved that d! V (V multiplied by the factorial of d) is an integer. Find the remainder of d! V divided by 1,000,000,007.
Constraints
* 2 ≤ d ≤ 300
* 1 ≤ li ≤ 300
* 0 ≤ s ≤ $ \ sum l_ {i} $
* All inputs are integers
Input
d
l1
.. ..
ld
s
Output
Output d! V divided by 1,000,000,007.
Examples
Input
2
6
3
4
Output
15
Input
5
12
34
56
78
90
123
Output
433127538
|
{"inputs": ["2\n6\n3\n3", "2\n1\n6\n3", "2\n1\n6\n0", "2\n6\n3\n7", "2\n6\n6\n1", "2\n2\n6\n5", "2\n6\n3\n4", "2\n11\n3\n7"], "outputs": ["9\n", "5\n", "0\n", "32\n", "1\n", "16\n", "15", "33\n"]}
| 278
| 114
|
coding
|
Solve the programming task below in a Python markdown code block.
There were and still are many problem in CW about palindrome numbers and palindrome strings. We suposse that you know which kind of numbers they are. If not, you may search about them using your favourite search engine.
In this kata you will be given a positive integer, ```val``` and you have to create the function ```next_pal()```(```nextPal``` Javascript) that will output the smallest palindrome number higher than ```val```.
Let's see:
```python
For Python
next_pal(11) == 22
next_pal(188) == 191
next_pal(191) == 202
next_pal(2541) == 2552
```
You will be receiving values higher than 10, all valid.
Enjoy it!!
Also feel free to reuse/extend the following starter code:
```python
def next_pal(val):
```
|
{"functional": "_inputs = [[11], [188], [191], [2541]]\n_outputs = [[22], [191], [202], [2552]]\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(next_pal(*i), o[0])"}
| 205
| 188
|
coding
|
Please solve the programming task below using a self-contained code snippet in a markdown code block.
An integer array is called arithmetic if it consists of at least three elements and if the difference between any two consecutive elements is the same.
For example, [1,3,5,7,9], [7,7,7,7], and [3,-1,-5,-9] are arithmetic sequences.
Given an integer array nums, return the number of arithmetic subarrays of nums.
A subarray is a contiguous subsequence of the array.
Please complete the following python code precisely:
```python
class Solution:
def numberOfArithmeticSlices(self, nums: List[int]) -> int:
```
|
{"functional": "def check(candidate):\n assert candidate(nums = [1,2,3,4]) == 3\n assert candidate(nums = [1]) == 0\n\n\ncheck(Solution().numberOfArithmeticSlices)"}
| 143
| 52
|
coding
|
Solve the programming task below in a Python markdown code block.
Appleman has n cards. Each card has an uppercase letter written on it. Toastman must choose k cards from Appleman's cards. Then Appleman should give Toastman some coins depending on the chosen cards. Formally, for each Toastman's card i you should calculate how much Toastman's cards have the letter equal to letter on ith, then sum up all these quantities, such a number of coins Appleman should give to Toastman.
Given the description of Appleman's cards. What is the maximum number of coins Toastman can get?
-----Input-----
The first line contains two integers n and k (1 ≤ k ≤ n ≤ 10^5). The next line contains n uppercase letters without spaces — the i-th letter describes the i-th card of the Appleman.
-----Output-----
Print a single integer – the answer to the problem.
-----Examples-----
Input
15 10
DZFDFZDFDDDDDDF
Output
82
Input
6 4
YJSNPI
Output
4
-----Note-----
In the first test example Toastman can choose nine cards with letter D and one additional card with any letter. For each card with D he will get 9 coins and for the additional card he will get 1 coin.
|
{"inputs": ["1 1\nV\n", "1 1\nV\n", "1 1\nU\n", "2 1\nWT\n", "2 2\nBL\n", "2 2\nBL\n", "2 1\nWT\n", "2 2\nLB\n"], "outputs": ["1\n", "1\n", "1\n", "1\n", "2\n", "2\n", "1\n", "2\n"]}
| 277
| 102
|
coding
|
Solve the programming task below in a Python markdown code block.
This is simple version of harder [Square Sums](/kata/square-sums).
# Square sums
Write function `square_sums_row` (or `squareSumsRow`/`SquareSumsRow` depending on language rules) that, given integer number `N` (in range `2..43`), returns array of integers `1..N` arranged in a way, so sum of each 2 consecutive numbers is a square.
Solution is valid if and only if following two criterias are met:
1. Each number in range `1..N` is used once and only once.
2. Sum of each 2 consecutive numbers is a perfect square.
### Example
For N=15 solution could look like this:
`[ 9, 7, 2, 14, 11, 5, 4, 12, 13, 3, 6, 10, 15, 1, 8 ]`
### Verification
1. All numbers are used once and only once. When sorted in ascending order array looks like this:
`[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 ]`
2. Sum of each 2 consecutive numbers is a perfect square:
```
16 16 16 16 16 16 16
/+\ /+\ /+\ /+\ /+\ /+\ /+\
[ 9, 7, 2, 14, 11, 5, 4, 12, 13, 3, 6, 10, 15, 1, 8 ]
\+/ \+/ \+/ \+/ \+/ \+/ \+/
9 25 9 25 9 25 9
9 = 3*3
16 = 4*4
25 = 5*5
```
If there is no solution, return `false` (or, `None` in scala). For example if `N=5`, then numbers `1,2,3,4,5` cannot be put into square sums row: `1+3=4`, `4+5=9`, but
`2` has no pairs and cannot link `[1,3]` and `[4,5]`
# Have fun!
Harder version of this Kata is [here](/kata/square-sums).
Also feel free to reuse/extend the following starter code:
```python
def square_sums_row(n):
```
|
{"functional": "_inputs = [[5], [24]]\n_outputs = [[False], [False]]\nimport math\ndef _deep_eq(a, b, tol=1e-5):\n if isinstance(a, float) or isinstance(b, float):\n return math.isclose(a, b, rel_tol=tol, abs_tol=tol)\n if isinstance(a, (list, tuple)):\n if len(a) != len(b): return False\n return all(_deep_eq(x, y, tol) for x, y in zip(a, b))\n return a == b\n\nfor i, o in zip(_inputs, _outputs):\n assert _deep_eq(square_sums_row(*i), o[0])"}
| 622
| 163
|
coding
|
Solve the programming task below in a Python markdown code block.
Enter a positive integer n of 4,000 or less, with a pair of integers a, b, c, d in the range 0-1000.
a + b + c + d = n
Create a program that outputs the number of combinations that satisfy the conditions.
Input
Given multiple datasets. Each dataset is given n on one row. Please process until the end of the input.
The number of datasets does not exceed 50.
Output
For each data set, output the number of combinations of a, b, c, and d on one line.
Example
Input
2
3
35
Output
10
20
8436
|
{"inputs": ["2\n0\n8", "2\n0\n1", "2\n1\n8", "2\n2\n8", "2\n1\n1", "2\n4\n8", "2\n1\n2", "2\n4\n1"], "outputs": ["10\n1\n165\n", "10\n1\n4\n", "10\n4\n165\n", "10\n10\n165\n", "10\n4\n4\n", "10\n35\n165\n", "10\n4\n10\n", "10\n35\n4\n"]}
| 158
| 146
|
coding
|
Solve the programming task below in a Python markdown code block.
group()
A group() expression returns one or more subgroups of the match.
Code
>>> import re
>>> m = re.match(r'(\w+)@(\w+)\.(\w+)','username@hackerrank.com')
>>> m.group(0) # The entire match
'username@hackerrank.com'
>>> m.group(1) # The first parenthesized subgroup.
'username'
>>> m.group(2) # The second parenthesized subgroup.
'hackerrank'
>>> m.group(3) # The third parenthesized subgroup.
'com'
>>> m.group(1,2,3) # Multiple arguments give us a tuple.
('username', 'hackerrank', 'com')
groups()
A groups() expression returns a tuple containing all the subgroups of the match.
Code
>>> import re
>>> m = re.match(r'(\w+)@(\w+)\.(\w+)','username@hackerrank.com')
>>> m.groups()
('username', 'hackerrank', 'com')
groupdict()
A groupdict() expression returns a dictionary containing all the named subgroups of the match, keyed by the subgroup name.
Code
>>> m = re.match(r'(?P<user>\w+)@(?P<website>\w+)\.(?P<extension>\w+)','myname@hackerrank.com')
>>> m.groupdict()
{'website': 'hackerrank', 'user': 'myname', 'extension': 'com'}
Task
You are given a string $\mbox{S}$.
Your task is to find the first occurrence of an alphanumeric character in $\mbox{S}$ (read from left to right) that has consecutive repetitions.
Input Format
A single line of input containing the string $\mbox{S}$.
Constraints
$0<len(S)<100$
Output Format
Print the first occurrence of the repeating character. If there are no repeating characters, print -1.
Sample Input
..12345678910111213141516171820212223
Sample Output
1
Explanation
.. is the first repeating character, but it is not alphanumeric.
1 is the first (from left to right) alphanumeric repeating character of the string in the substring 111.
|
{"inputs": ["..12345678910111213141516171820212223\n"], "outputs": ["1\n"]}
| 510
| 49
|
coding
|
Solve the programming task below in a Python markdown code block.
Vasily exited from a store and now he wants to recheck the total price of all purchases in his bill. The bill is a string in which the names of the purchases and their prices are printed in a row without any spaces. Check has the format "name_1price_1name_2price_2...name_{n}price_{n}", where name_{i} (name of the i-th purchase) is a non-empty string of length not more than 10, consisting of lowercase English letters, and price_{i} (the price of the i-th purchase) is a non-empty string, consisting of digits and dots (decimal points). It is possible that purchases with equal names have different prices.
The price of each purchase is written in the following format. If the price is an integer number of dollars then cents are not written.
Otherwise, after the number of dollars a dot (decimal point) is written followed by cents in a two-digit format (if number of cents is between 1 and 9 inclusively, there is a leading zero).
Also, every three digits (from less significant to the most) in dollars are separated by dot (decimal point). No extra leading zeroes are allowed. The price always starts with a digit and ends with a digit.
For example: "234", "1.544", "149.431.10", "0.99" and "123.05" are valid prices, ".333", "3.33.11", "12.00", ".33", "0.1234" and "1.2" are not valid.
Write a program that will find the total price of all purchases in the given bill.
-----Input-----
The only line of the input contains a non-empty string s with length not greater than 1000 — the content of the bill.
It is guaranteed that the bill meets the format described above. It is guaranteed that each price in the bill is not less than one cent and not greater than 10^6 dollars.
-----Output-----
Print the total price exactly in the same format as prices given in the input.
-----Examples-----
Input
chipsy48.32televizor12.390
Output
12.438.32
Input
a1b2c3.38
Output
6.38
Input
aa0.01t0.03
Output
0.04
|
{"inputs": ["a1.01\n", "a0.11\n", "a0.01\n", "a0.40\n", "a0.11\n", "a0.40\n", "a1.01\n", "a0.01\n"], "outputs": ["1.01\n", "0.11\n", "0.01\n", "0.40\n", "0.11", "0.40", "1.01", "0.01"]}
| 547
| 122
|
coding
|
Solve the programming task below in a Python markdown code block.
Given the list of numbers, you are to sort them in non decreasing order.
-----Input-----
t – the number of numbers in list, then t lines follow [t <= 10^6].
Each line contains one integer: N [0 <= N <= 10^6]
-----Output-----
Output given numbers in non decreasing order.
-----Example-----
Input:
5
5
3
6
7
1
Output:
1
3
5
6
7
|
{"inputs": ["5\n5\n3\n6\n7\n1", "5\n5\n3\n3\n7\n1", "5\n0\n3\n3\n7\n1", "5\n1\n3\n3\n7\n1", "5\n1\n3\n3\n7\n2", "5\n1\n1\n3\n7\n2", "5\n1\n2\n4\n1\n1", "5\n1\n2\n4\n1\n0"], "outputs": ["1\n3\n5\n6\n7", "1\n3\n3\n5\n7\n", "0\n1\n3\n3\n7\n", "1\n1\n3\n3\n7\n", "1\n2\n3\n3\n7\n", "1\n1\n2\n3\n7\n", "1\n1\n1\n2\n4\n", "0\n1\n1\n2\n4\n"]}
| 112
| 205
|
coding
|
Solve the programming task below in a Python markdown code block.
A piece of paper contains an array of n integers a1, a2, ..., an. Your task is to find a number that occurs the maximum number of times in this array.
However, before looking for such number, you are allowed to perform not more than k following operations — choose an arbitrary element from the array and add 1 to it. In other words, you are allowed to increase some array element by 1 no more than k times (you are allowed to increase the same element of the array multiple times).
Your task is to find the maximum number of occurrences of some number in the array after performing no more than k allowed operations. If there are several such numbers, your task is to find the minimum one.
Input
The first line contains two integers n and k (1 ≤ n ≤ 105; 0 ≤ k ≤ 109) — the number of elements in the array and the number of operations you are allowed to perform, correspondingly.
The third line contains a sequence of n integers a1, a2, ..., an (|ai| ≤ 109) — the initial array. The numbers in the lines are separated by single spaces.
Output
In a single line print two numbers — the maximum number of occurrences of some number in the array after at most k allowed operations are performed, and the minimum number that reaches the given maximum. Separate the printed numbers by whitespaces.
Examples
Input
5 3
6 3 4 0 2
Output
3 4
Input
3 4
5 5 5
Output
3 5
Input
5 3
3 1 2 2 1
Output
4 2
Note
In the first sample your task is to increase the second element of the array once and increase the fifth element of the array twice. Thus, we get sequence 6, 4, 4, 0, 4, where number 4 occurs 3 times.
In the second sample you don't need to perform a single operation or increase each element by one. If we do nothing, we get array 5, 5, 5, if we increase each by one, we get 6, 6, 6. In both cases the maximum number of occurrences equals 3. So we should do nothing, as number 5 is less than number 6.
In the third sample we should increase the second array element once and the fifth element once. Thus, we get sequence 3, 2, 2, 2, 2, where number 2 occurs 4 times.
|
{"inputs": ["1 0\n0\n", "1 1\n0\n", "1 1\n1\n", "1 2\n0\n", "1 2\n1\n", "1 3\n0\n", "1 0\n1\n", "3 4\n5 5 5\n"], "outputs": ["1 0\n", "1 0\n\n", "1 1\n\n", "1 0\n\n", "1 1\n\n", "1 0\n\n", "1 1\n\n", "3 5\n"]}
| 556
| 128
|
coding
|
Solve the programming task below in a Python markdown code block.
$n$ heroes fight against each other in the Arena. Initially, the $i$-th hero has level $a_i$.
Each minute, a fight between two different heroes occurs. These heroes can be chosen arbitrarily (it's even possible that it is the same two heroes that were fighting during the last minute).
When two heroes of equal levels fight, nobody wins the fight. When two heroes of different levels fight, the one with the higher level wins, and his level increases by $1$.
The winner of the tournament is the first hero that wins in at least $100^{500}$ fights (note that it's possible that the tournament lasts forever if no hero wins this number of fights, then there is no winner). A possible winner is a hero such that there exists a sequence of fights that this hero becomes the winner of the tournament.
Calculate the number of possible winners among $n$ heroes.
-----Input-----
The first line contains one integer $t$ ($1 \le t \le 500$) — the number of test cases.
Each test case consists of two lines. The first line contains one integer $n$ ($2 \le n \le 100$) — the number of heroes. The second line contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 100$), where $a_i$ is the initial level of the $i$-th hero.
-----Output-----
For each test case, print one integer — the number of possible winners among the given $n$ heroes.
-----Examples-----
Input
3
3
3 2 2
2
5 5
4
1 3 3 7
Output
1
0
3
-----Note-----
In the first test case of the example, the only possible winner is the first hero.
In the second test case of the example, each fight between the heroes results in nobody winning it, so the tournament lasts forever and there is no winner.
|
{"inputs": ["1\n3\n90 91 92\n", "1\n3\n90 91 92\n", "1\n3\n90 56 92\n", "1\n3\n90 75 92\n", "1\n3\n49 75 92\n", "1\n3\n90 43 92\n", "1\n3\n90 57 92\n", "1\n3\n49 75 180\n"], "outputs": ["2\n", "2\n", "2\n", "2\n", "2\n", "2\n", "2\n", "2\n"]}
| 440
| 159
|
coding
|
Solve the programming task below in a Python markdown code block.
Read problem statements in [Bengali], [Russian], [Mandarin] and [Vietnamese] as well.
You are given a binary string S. You can perform the following operations on S:
Flip: Pick an index i (1 ≤ i ≤ |S|) and flip the i-th character (i.e change 1 to 0 or 0 to 1). For e.g. 01\underline{1}001 \rightarrow 01\underline{0}001
Compress: Pick any non-empty substring consisting of the same character and replace it with a single occurrence of that character. For e.g. 100\underline{1111}10 \rightarrow 100\underline{1}10
You want to make all the characters of the binary string equal (i.e. either all characters are 0 or all characters are 1). Find the minimum number of operations required to do so.
------ 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 and only line of each test case contains a binary string S.
------ Output Format ------
For each test case, output a single line containing one integer - the minimum number of operations required to make all the characters of S equal.
------ Constraints ------
$1 ≤T ≤10^{5}$
$1 ≤|S| ≤10^{6}$
$S$ is a binary string.
- It is guaranteed that the sum of $|S|$ over all test cases does not exceed $10^{6}$.
------ subtasks ------
Subtask #1 (5 points):
$1 ≤ T ≤ 10^{3}$
$1 ≤ |S| ≤ 10$
Subtask #2 (20 points):
$1 ≤ T ≤ 10^{3}$
$1 ≤ |S| ≤ 50$
Subtask #3 (75 points):
Original constraints
----- Sample Input 1 ------
3
100011
1110011
000101110
----- Sample Output 1 ------
2
2
3
----- explanation 1 ------
In the first test case,
- $1\underline{000}11 \xrightarrow{\text{compress}} 1\underline{0}11$
- $1\underline{0}11 \xrightarrow{\text{flip}} 1\underline{1}11$
In the second test case,
- $111\underline{0}011 \xrightarrow{\text{flip}} 111\underline{1}011$
- $1111\underline{0}11 \xrightarrow{\text{flip}} 1111\underline{1}11$
In the third test case,
- $0001\underline{0}1110 \xrightarrow{\text{flip}} 0001\underline{1}1110$
- $000\underline{11111}0 \xrightarrow{\text{compress}} 000\underline{1}0$
- $000\underline{1}0 \xrightarrow{\text{flip}} 000\underline{0}0$
|
{"inputs": ["3\n100011\n1110011\n000101110\n"], "outputs": ["2\n2\n3\n"]}
| 758
| 43
|
coding
|
Please solve the programming task below using a self-contained code snippet in a markdown code block.
You are given a string expression representing a Lisp-like expression to return the integer value of.
The syntax for these expressions is given as follows.
An expression is either an integer, let expression, add expression, mult expression, or an assigned variable. Expressions always evaluate to a single integer.
(An integer could be positive or negative.)
A let expression takes the form "(let v1 e1 v2 e2 ... vn en expr)", where let is always the string "let", then there are one or more pairs of alternating variables and expressions, meaning that the first variable v1 is assigned the value of the expression e1, the second variable v2 is assigned the value of the expression e2, and so on sequentially; and then the value of this let expression is the value of the expression expr.
An add expression takes the form "(add e1 e2)" where add is always the string "add", there are always two expressions e1, e2 and the result is the addition of the evaluation of e1 and the evaluation of e2.
A mult expression takes the form "(mult e1 e2)" where mult is always the string "mult", there are always two expressions e1, e2 and the result is the multiplication of the evaluation of e1 and the evaluation of e2.
For this question, we will use a smaller subset of variable names. A variable starts with a lowercase letter, then zero or more lowercase letters or digits. Additionally, for your convenience, the names "add", "let", and "mult" are protected and will never be used as variable names.
Finally, there is the concept of scope. When an expression of a variable name is evaluated, within the context of that evaluation, the innermost scope (in terms of parentheses) is checked first for the value of that variable, and then outer scopes are checked sequentially. It is guaranteed that every expression is legal. Please see the examples for more details on the scope.
Please complete the following python code precisely:
```python
class Solution:
def evaluate(self, expression: str) -> int:
```
|
{"functional": "def check(candidate):\n assert candidate(expression = \"(let x 2 (mult x (let x 3 y 4 (add x y))))\") == 14\n assert candidate(expression = \"(let x 3 x 2 x)\") == 2\n assert candidate(expression = \"(let x 1 y 2 x (add x y) (add x y))\") == 5\n\n\ncheck(Solution().evaluate)"}
| 445
| 102
|
coding
|
Solve the programming task below in a Python markdown code block.
There are n kangaroos with pockets. Each kangaroo has a size (integer number). A kangaroo can go into another kangaroo's pocket if and only if the size of kangaroo who hold the kangaroo is at least twice as large as the size of kangaroo who is held.
Each kangaroo can hold at most one kangaroo, and the kangaroo who is held by another kangaroo cannot hold any kangaroos.
The kangaroo who is held by another kangaroo cannot be visible from outside. Please, find a plan of holding kangaroos with the minimal number of kangaroos who is visible.
Input
The first line contains a single integer — n (1 ≤ n ≤ 5·105). Each of the next n lines contains an integer si — the size of the i-th kangaroo (1 ≤ si ≤ 105).
Output
Output a single integer — the optimal number of visible kangaroos.
Examples
Input
8
2
5
7
6
9
8
4
2
Output
5
Input
8
9
1
6
2
6
5
8
3
Output
5
|
{"inputs": ["1\n1\n", "1\n2\n", "3\n1\n2\n4\n", "3\n1\n3\n4\n", "3\n1\n3\n5\n", "3\n1\n6\n5\n", "3\n1\n6\n9\n", "3\n1\n11\n9\n"], "outputs": ["1\n", "1\n", "2\n", "2\n", "2\n", "2\n", "2\n", "2\n"]}
| 257
| 111
|
coding
|
Solve the programming task below in a Python markdown code block.
Create a function that takes a string and returns that
string with the first half lowercased and the last half uppercased.
eg: foobar == fooBAR
If it is an odd number then 'round' it up to find which letters to uppercase. See example below.
sillycase("brian")
// --^-- midpoint
// bri first half (lower-cased)
// AN second half (upper-cased)
Also feel free to reuse/extend the following starter code:
```python
def sillycase(silly):
```
|
{"functional": "_inputs = [['foobar'], ['codewars'], ['jAvASCript'], ['brian'], ['jabberwock'], ['SCOTland'], ['WeLlDoNe']]\n_outputs = [['fooBAR'], ['codeWARS'], ['javasCRIPT'], ['briAN'], ['jabbeRWOCK'], ['scotLAND'], ['wellDONE']]\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(sillycase(*i), o[0])"}
| 131
| 221
|
coding
|
Solve the programming task below in a Python markdown code block.
Problem
GPA is an abbreviation for "Galaxy Point of Aizu" and takes real numbers from 0 to 4.
GPA rock-paper-scissors is a game played by two people. After each player gives a signal of "rock-paper-scissors, pon (hoi)" to each other's favorite move, goo, choki, or par, the person with the higher GPA becomes the winner, and the person with the lower GPA becomes the loser. If they are the same, it will be a draw.
Since the GPA data of N people is given, output the points won in each round-robin battle.
However, the points won will be 3 when winning, 1 when drawing, and 0 when losing.
Round-robin is a system in which all participants play against participants other than themselves exactly once.
Constraints
The input satisfies the following conditions.
* 2 ≤ N ≤ 105
* N is an integer
* 0.000 ≤ ai ≤ 4.000 (1 ≤ i ≤ N)
* ai is a real number (1 ≤ i ≤ N)
* Each GPA is given up to 3 decimal places
Input
The input is given in the following format.
N
a1
a2
...
aN
The first line is given the number of people N to play GPA rock-paper-scissors.
The following N lines are given the data ai of the i-th person's GPA in one line.
Output
Output the points of the i-th person on the i-line on one line. (1 ≤ i ≤ N)
Examples
Input
3
1.000
3.000
3.000
Output
0
4
4
Input
3
1.000
2.000
3.000
Output
0
3
6
|
{"inputs": ["3\n1.000\n2.000\n3.000", "3\n1.000\n3.000\n3.000", "3\n1.000\n2.000\n3.4274102096399073", "3\n1.3153899733914476\n3.000\n3.000", "3\n1.000\n3.000\n3.1230319554116766", "3\n1.000\n2.000\n3.9759367558439593", "3\n1.000\n2.5451927881659007\n3.000", "3\n1.6470390157297516\n3.000\n3.000"], "outputs": ["0\n3\n6", "0\n4\n4", "0\n3\n6\n", "0\n4\n4\n", "0\n3\n6\n", "0\n3\n6\n", "0\n3\n6\n", "0\n4\n4\n"]}
| 403
| 314
|
coding
|
Solve the programming task below in a Python markdown code block.
Dr. Evil kidnapped Mahmoud and Ehab in the evil land because of their performance in the Evil Olympiad in Informatics (EOI). He decided to give them some problems to let them go.
Dr. Evil is interested in sets, He has a set of n integers. Dr. Evil calls a set of integers evil if the MEX of it is exactly x. the MEX of a set of integers is the minimum non-negative integer that doesn't exist in it. For example, the MEX of the set {0, 2, 4} is 1 and the MEX of the set {1, 2, 3} is 0 .
Dr. Evil is going to make his set evil. To do this he can perform some operations. During each operation he can add some non-negative integer to his set or erase some element from it. What is the minimal number of operations Dr. Evil has to perform to make his set evil?
-----Input-----
The first line contains two integers n and x (1 ≤ n ≤ 100, 0 ≤ x ≤ 100) — the size of the set Dr. Evil owns, and the desired MEX.
The second line contains n distinct non-negative integers not exceeding 100 that represent the set.
-----Output-----
The only line should contain one integer — the minimal number of operations Dr. Evil should perform.
-----Examples-----
Input
5 3
0 4 5 6 7
Output
2
Input
1 0
0
Output
1
Input
5 0
1 2 3 4 5
Output
0
-----Note-----
For the first test case Dr. Evil should add 1 and 2 to the set performing 2 operations.
For the second test case Dr. Evil should erase 0 from the set. After that, the set becomes empty, so the MEX of it is 0.
In the third test case the set is already evil.
|
{"inputs": ["1 0\n0\n", "1 0\n0\n", "1 100\n0\n", "1 0\n100\n", "2 2\n0 2\n", "2 1\n1 2\n", "2 2\n0 2\n", "2 1\n1 2\n"], "outputs": ["1\n", "1\n", "99\n", "0\n", "2\n", "2\n", "2\n", "2\n"]}
| 428
| 115
|
coding
|
Solve the programming task below in a Python markdown code block.
In a strategic computer game "Settlers II" one has to build defense structures to expand and protect the territory. Let's take one of these buildings. At the moment the defense structure accommodates exactly n soldiers. Within this task we can assume that the number of soldiers in the defense structure won't either increase or decrease.
Every soldier has a rank — some natural number from 1 to k. 1 stands for a private and k stands for a general. The higher the rank of the soldier is, the better he fights. Therefore, the player profits from having the soldiers of the highest possible rank.
To increase the ranks of soldiers they need to train. But the soldiers won't train for free, and each training session requires one golden coin. On each training session all the n soldiers are present.
At the end of each training session the soldiers' ranks increase as follows. First all the soldiers are divided into groups with the same rank, so that the least possible number of groups is formed. Then, within each of the groups where the soldiers below the rank k are present, exactly one soldier increases his rank by one.
You know the ranks of all n soldiers at the moment. Determine the number of golden coins that are needed to increase the ranks of all the soldiers to the rank k.
Input
The first line contains two integers n and k (1 ≤ n, k ≤ 100). They represent the number of soldiers and the number of different ranks correspondingly. The second line contains n numbers in the non-decreasing order. The i-th of them, ai, represents the rank of the i-th soldier in the defense building (1 ≤ i ≤ n, 1 ≤ ai ≤ k).
Output
Print a single integer — the number of golden coins needed to raise all the soldiers to the maximal rank.
Examples
Input
4 4
1 2 2 3
Output
4
Input
4 3
1 1 1 1
Output
5
Note
In the first example the ranks will be raised in the following manner:
1 2 2 3 → 2 2 3 4 → 2 3 4 4 → 3 4 4 4 → 4 4 4 4
Thus totals to 4 training sessions that require 4 golden coins.
|
{"inputs": ["1 5\n1\n", "1 5\n4\n", "1 1\n1\n", "1 8\n1\n", "1 2\n1\n", "1 3\n1\n", "1 4\n1\n", "1 6\n1\n"], "outputs": ["4\n", "1\n", "0\n", "7\n", "1\n", "2\n", "3\n", "5\n"]}
| 499
| 102
|
coding
|
Solve the programming task below in a Python markdown code block.
Shivani is interning at HackerEarth. One day she has to distribute some chocolates to her colleagues. She is biased towards her friends and may have distributed the chocolates unequally. One of the program managers gets to know this and orders Shivani to make sure everyone gets equal number of chocolates.
But to make things difficult for the intern, she is ordered to equalize the number of chocolates for every colleague in the following manner,
For every operation, she can choose one of her colleagues and can do one of the three things.
(i) She can give one chocolate to every colleague other than chosen one.
(ii) She can give two chocolates to every colleague other than chosen one.
(iii) She can give five chocolates to every colleague other than chosen one.
Calculate minimum number of such operations needed to ensure that every colleague has the same number of chocolates.
Input Format
First line contains an integer T denoting the number of testcases. T testcases follow.
Each testcase has 2 lines. First line of each testcase contains an integer N denoting the number of co-interns. Second line contains N space separated integers denoting the current number of chocolates each colleague has.
Output Format
T lines, each containing the minimum number of operations needed to make sure all colleagues have the same number of chocolates.
Constraints
1 ≤ T ≤ 100
1 ≤ N ≤ 10000
Number of initial chocolates each colleague has < 1000
SAMPLE INPUT
1
4
2 2 3 7
SAMPLE OUTPUT
2
Explanation
1st case: Shivani increases all elements by 1 except 3rd one
2 2 3 7 -> 3 3 3 8
2nd case: Shivani increases all element by 5 except last one
3 3 3 8 -> 8 8 8 8
|
{"inputs": ["1\n4\n2 2 3 7"], "outputs": ["2"]}
| 403
| 22
|
coding
|
Please solve the programming task below using a self-contained code snippet in a markdown code block.
Alice is texting Bob using her phone. The mapping of digits to letters is shown in the figure below.
In order to add a letter, Alice has to press the key of the corresponding digit i times, where i is the position of the letter in the key.
For example, to add the letter 's', Alice has to press '7' four times. Similarly, to add the letter 'k', Alice has to press '5' twice.
Note that the digits '0' and '1' do not map to any letters, so Alice does not use them.
However, due to an error in transmission, Bob did not receive Alice's text message but received a string of pressed keys instead.
For example, when Alice sent the message "bob", Bob received the string "2266622".
Given a string pressedKeys representing the string received by Bob, return the total number of possible text messages Alice could have sent.
Since the answer may be very large, return it modulo 109 + 7.
Please complete the following python code precisely:
```python
class Solution:
def countTexts(self, pressedKeys: str) -> int:
```
|
{"functional": "def check(candidate):\n assert candidate(pressedKeys = \"22233\") == 8\n assert candidate(pressedKeys = \"222222222222222222222222222222222222\") == 82876089\n\n\ncheck(Solution().countTexts)"}
| 259
| 94
|
coding
|
Solve the programming task below in a Python markdown code block.
An L-shape is a figure on gridded paper that looks like the first four pictures below. An L-shape contains exactly three shaded cells (denoted by *), which can be rotated in any way.
You are given a rectangular grid. Determine if it contains L-shapes only, where L-shapes can't touch an edge or corner. More formally:
Each shaded cell in the grid is part of exactly one L-shape, and
no two L-shapes are adjacent by edge or corner.
For example, the last two grids in the picture above do not satisfy the condition because the two L-shapes touch by corner and edge, respectively.
-----Input-----
The input consists of multiple test cases. The first line contains an integer $t$ ($1 \leq t \leq 100$) — the number of test cases. The description of the test cases follows.
The first line of each test case contains two integers $n$ and $m$ ($1 \leq n, m \leq 50$) — the number of rows and columns in the grid, respectively.
Then $n$ lines follow, each containing $m$ characters. Each of these characters is either '.' or '*' — an empty cell or a shaded cell, respectively.
-----Output-----
For each test case, output "YES" if the grid is made up of L-shape that don't share edges or corners, and "NO" otherwise.
You can output the answer in any case (for example, the strings "yEs", "yes", "Yes" and "YES" will be recognized as a positive answer).
-----Examples-----
Input
10
6 10
........**
.**......*
..*..*....
.....**...
...*.....*
..**....**
6 10
....*...**
.**......*
..*..*....
.....**...
...*.....*
..**....**
3 3
...
***
...
4 4
.*..
**..
..**
..*.
5 4
.*..
**..
....
..**
..*.
3 2
.*
**
*.
2 3
*..
.**
3 2
..
**
*.
3 3
.**
*.*
**.
3 3
..*
.**
..*
Output
YES
NO
NO
NO
YES
NO
NO
YES
NO
NO
-----Note-----
None
|
{"inputs": ["1\n4 4\n.**.\n*..*\n*..*\n.**.\n", "1\n4 5\n..*..\n.*.*.\n.*.*.\n..*..\n", "1\n6 6\n..**..\n.*..*.\n*....*\n*....*\n.*..*.\n..**..\n", "10\n6 10\n........**\n.**......*\n..*..*....\n.....**...\n...*.....*\n..**....**\n6 10\n....*...**\n.**......*\n..*..*....\n.....**...\n...*.....*\n..**....**\n3 3\n...\n***\n...\n4 4\n.*..\n**..\n..**\n..*.\n5 4\n.*..\n**..\n....\n..**\n..*.\n3 2\n.*\n**\n*.\n2 3\n*..\n.**\n3 2\n..\n**\n*.\n3 3\n.**\n*.*\n**.\n3 3\n..*\n.**\n..*\n"], "outputs": ["NO\n", "NO\n", "NO\n", "YES\nNO\nNO\nNO\nYES\nNO\nNO\nYES\nNO\nNO\n"]}
| 517
| 316
|
coding
|
Please solve the programming task below using a self-contained code snippet in a markdown code block.
There is an integer array nums sorted in ascending order (with distinct values).
Prior to being passed to your function, nums is possibly rotated at an unknown pivot index k (1 <= k < nums.length) such that the resulting array is [nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]] (0-indexed). For example, [0,1,2,4,5,6,7] might be rotated at pivot index 3 and become [4,5,6,7,0,1,2].
Given the array nums after the possible rotation and an integer target, return the index of target if it is in nums, or -1 if it is not in nums.
You must write an algorithm with O(log n) runtime complexity.
Please complete the following python code precisely:
```python
class Solution:
def search(self, nums: List[int], target: int) -> int:
```
|
{"functional": "def check(candidate):\n assert candidate(nums = [4,5,6,7,0,1,2], target = 0) == 4\n assert candidate(nums = [4,5,6,7,0,1,2], target = 3) == -1\n assert candidate(nums = [1], target = 0) == -1\n\n\ncheck(Solution().search)"}
| 222
| 93
|
coding
|
Solve the programming task below in a Python markdown code block.
# Your Task
You have a Petri dish with bacteria, and you are preparing to dive into the harsh micro-world. But, unfortunately, you don't have any microscope nearby, so you can't watch them.
You know that you have `n` bacteria in the Petri dish and size of the i-th bacteria is bacteriai. Also you know intergalactic positive integer constant `K`.
The i-th bacteria can swallow the j-th bacteria if and only if bacteriai > bacteriaj and bacteriai ≤ bacteriaj + K. The j-th bacteria disappear, but the i-th bacteria doesn't change its size.
Since you don't have a microscope, you can only guess the minimal possible number of bacteria that will remain in your Petri dish when you finally find a microscope.
```python
micro_world([101, 53, 42, 102, 101, 55, 54], 1) == 3
micro_world([20, 15, 10, 15, 20, 25], 5) == 1
```
___
# Explanation
```python
bacteria = [101, 53, 42, 102, 101, 55, 54]
K = 1
```
```if:cpp
The one of possible sequences of swallows is: {101,53,42,102,101,55,54} → {101,53,42,102,55,54} → {101,42,102,55,54} → {42,102,55,54} → {42,102,55}. In total there are 3 bacteria remaining.
```
```if:python,ruby,javascript
The one of possible sequences of swallows is: [101,53,42,102,101,55,54] → [101,53,42,102,55,54] → [101,42,102,55,54] → [42,102,55,54] → [42,102,55]. In total there are 3 bacteria remaining.
```
Also feel free to reuse/extend the following starter code:
```python
def micro_world(bacteria, k):
```
|
{"functional": "_inputs = [[[101, 53, 42, 102, 101, 55, 54], 1], [[20, 15, 10, 15, 20, 25], 5], [[5, 3, 1, 5], 1]]\n_outputs = [[3], [1], [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(micro_world(*i), o[0])"}
| 564
| 234
|
coding
|
Solve the programming task below in a Python markdown code block.
You have an infinitely long digital panel. Using various combinations of 7 segments, we can represent each digit. The picture shows how all 10 decimal digits are displayed.
Initially, all segments in the panel are off. You are given seven integers A, B, C, D, E, F and G representing the number of coins required to turn on the respective segment, as shown above.
Given an integer N, find the minimum number of coins you need to spend to display some [factor] of N on the panel.
------ Input Format ------
- The first line contains an integer T denoting the number of test cases. The T test cases then follow.
- The only line of each test case contains eight space-separated integers N, A, B, C, D, E, F and G, denoting the integer N and the number of coins required to turn on each of the seven segments.
------ Output Format ------
For each test case, output a single integer - the minimum number of coins you need to spend to display some factor of N on the panel.
------ Constraints ------
$1 ≤ T ≤ 1000$
$1 ≤ N < 10^{100}$
$1 ≤ A, B, C, D, E, F, G ≤ 50$
----- Sample Input 1 ------
3
10 1 31 21 5 3 12 9
69697 1 2 3 4 5 6 7
3964083074239146524786 1 41 31 21 11 1 41
----- Sample Output 1 ------
48
5
72
----- explanation 1 ------
Test case $1$: $10$ has four factors: $1$, $2$, $5$, and $10$. Their costs are:
- Display $1$: $31+21=52$.
- Display $2$: $1+31+5+3+9=49$.
- Display $5$: $1+21+5+12+9=48$.
- Display $10$: $31+21+1+31+21+5+3+12=125$.
The minimum number of coins are required to display $5$, which costs $48$ coins.
Test case $2$: $69697$ has two factors: $1$ and $69697$. The cost to display $1$ is only $5$ coins, while the cost to display $69697$ is much larger, so the answer is $5$.
|
{"inputs": ["3\n10 1 31 21 5 3 12 9\n69697 1 2 3 4 5 6 7\n3964083074239146524786 1 41 31 21 11 1 41\n"], "outputs": ["48\n5\n72\n"]}
| 601
| 102
|
coding
|
Solve the programming task below in a Python markdown code block.
You have recently discovered that horses travel in a unique pattern - they're either running (at top speed) or resting (standing still).
Here's an example of how one particular horse might travel:
```
The horse Blaze can run at 14 metres/second for 60 seconds, but must then rest for 45 seconds.
After 500 seconds Blaze will have traveled 4200 metres.
```
Your job is to write a function that returns how long a horse will have traveled after a given time.
####Input:
* totalTime - How long the horse will be traveling (in seconds)
* runTime - How long the horse can run for before having to rest (in seconds)
* restTime - How long the horse have to rest for after running (in seconds)
* speed - The max speed of the horse (in metres/second)
Also feel free to reuse/extend the following starter code:
```python
def travel(total_time, run_time, rest_time, speed):
```
|
{"functional": "_inputs = [[1000, 10, 127, 14], [1000, 10, 0, 10], [25, 50, 120, 18], [35869784, 90, 100, 5], [1234567, 4, 3, 11], [100000000, 21, 5, 14], [0, 100, 10, 14], [250, 0, 5, 14], [100, 10, 0, 14], [500, 100, 10, 0]]\n_outputs = [[1120], [10000], [450], [84954920], [7760148], [1130769276], [0], [0], [1400], [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(travel(*i), o[0])"}
| 221
| 392
|
coding
|
Solve the programming task below in a Python markdown code block.
There are some rabbits in Singapore Zoo. To feed them, Zookeeper bought $n$ carrots with lengths $a_1, a_2, a_3, \ldots, a_n$. However, rabbits are very fertile and multiply very quickly. Zookeeper now has $k$ rabbits and does not have enough carrots to feed all of them. To solve this problem, Zookeeper decided to cut the carrots into $k$ pieces. For some reason, all resulting carrot lengths must be positive integers.
Big carrots are very difficult for rabbits to handle and eat, so the time needed to eat a carrot of size $x$ is $x^2$.
Help Zookeeper split his carrots while minimizing the sum of time taken for rabbits to eat the carrots.
-----Input-----
The first line contains two integers $n$ and $k$ $(1 \leq n \leq k \leq 10^5)$: the initial number of carrots and the number of rabbits.
The next line contains $n$ integers $a_1, a_2, \ldots, a_n$ $(1 \leq a_i \leq 10^6)$: lengths of carrots.
It is guaranteed that the sum of $a_i$ is at least $k$.
-----Output-----
Output one integer: the minimum sum of time taken for rabbits to eat carrots.
-----Examples-----
Input
3 6
5 3 1
Output
15
Input
1 4
19
Output
91
-----Note-----
For the first test, the optimal sizes of carrots are $\{1,1,1,2,2,2\}$. The time taken is $1^2+1^2+1^2+2^2+2^2+2^2=15$
For the second test, the optimal sizes of carrots are $\{4,5,5,5\}$. The time taken is $4^2+5^2+5^2+5^2=91$.
|
{"inputs": ["1 1\n1\n", "1 1\n1\n", "1 4\n6\n", "1 4\n19\n", "1 8\n19\n", "1 4\n19\n", "1 15\n19\n", "3 6\n5 3 1\n"], "outputs": ["1\n", "1\n", "10\n", "91\n", "47\n", "91\n", "27\n", "15\n"]}
| 440
| 117
|
coding
|
Solve the programming task below in a Python markdown code block.
collections.deque()
A deque is a double-ended queue. It can be used to add or remove elements from both ends.
Deques support thread safe, memory efficient appends and pops from either side of the deque with approximately the same $O(1)$ performance in either direction.
Click on the link to learn more about deque() methods.
Click on the link to learn more about various approaches to working with deques: Deque Recipes.
Example
Code
>>> from collections import deque
>>> d = deque()
>>> d.append(1)
>>> print d
deque([1])
>>> d.appendleft(2)
>>> print d
deque([2, 1])
>>> d.clear()
>>> print d
deque([])
>>> d.extend('1')
>>> print d
deque(['1'])
>>> d.extendleft('234')
>>> print d
deque(['4', '3', '2', '1'])
>>> d.count('1')
1
>>> d.pop()
'1'
>>> print d
deque(['4', '3', '2'])
>>> d.popleft()
'4'
>>> print d
deque(['3', '2'])
>>> d.extend('7896')
>>> print d
deque(['3', '2', '7', '8', '9', '6'])
>>> d.remove('2')
>>> print d
deque(['3', '7', '8', '9', '6'])
>>> d.reverse()
>>> print d
deque(['6', '9', '8', '7', '3'])
>>> d.rotate(3)
>>> print d
deque(['8', '7', '3', '6', '9'])
Task
Perform append, pop, popleft and appendleft methods on an empty deque $\boldsymbol{d}$.
Input Format
The first line contains an integer $N$, the number of operations.
The next $N$ lines contains the space separated names of methods and their values.
Constraints
$0<N\leq100$
Output Format
Print the space separated elements of deque $\boldsymbol{d}$.
Sample Input
6
append 1
append 2
append 3
appendleft 4
pop
popleft
Sample Output
1 2
|
{"inputs": ["6\nappend 1\nappend 2\nappend 3\nappendleft 4\npop\npopleft\n"], "outputs": ["1 2\n"]}
| 479
| 38
|
coding
|
Solve the programming task below in a Python markdown code block.
Vika has n jars with paints of distinct colors. All the jars are numbered from 1 to n and the i-th jar contains a_{i} liters of paint of color i.
Vika also has an infinitely long rectangular piece of paper of width 1, consisting of squares of size 1 × 1. Squares are numbered 1, 2, 3 and so on. Vika decided that she will start painting squares one by one from left to right, starting from the square number 1 and some arbitrary color. If the square was painted in color x, then the next square will be painted in color x + 1. In case of x = n, next square is painted in color 1. If there is no more paint of the color Vika wants to use now, then she stops.
Square is always painted in only one color, and it takes exactly 1 liter of paint. Your task is to calculate the maximum number of squares that might be painted, if Vika chooses right color to paint the first square.
-----Input-----
The first line of the input contains a single integer n (1 ≤ n ≤ 200 000) — the number of jars with colors Vika has.
The second line of the input contains a sequence of integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10^9), where a_{i} is equal to the number of liters of paint in the i-th jar, i.e. the number of liters of color i that Vika has.
-----Output-----
The only line of the output should contain a single integer — the maximum number of squares that Vika can paint if she follows the rules described above.
-----Examples-----
Input
5
2 4 2 3 3
Output
12
Input
3
5 5 5
Output
15
Input
6
10 10 10 1 10 10
Output
11
-----Note-----
In the first sample the best strategy is to start painting using color 4. Then the squares will be painted in the following colors (from left to right): 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5.
In the second sample Vika can start to paint using any color.
In the third sample Vika should start painting using color number 5.
|
{"inputs": ["2\n2 3\n", "2\n2 3\n", "2\n4 3\n", "2\n1 3\n", "2\n4 1\n", "2\n1 6\n", "2\n7 1\n", "2\n1 1\n"], "outputs": ["5\n", "5\n", "7\n", "3\n", "3\n", "3\n", "3\n", "2\n"]}
| 538
| 102
|
coding
|
Please solve the programming task below using a self-contained code snippet in a markdown code block.
Given an array nums that represents a permutation of integers from 1 to n. We are going to construct a binary search tree (BST) by inserting the elements of nums in order into an initially empty BST. Find the number of different ways to reorder nums so that the constructed BST is identical to that formed from the original array nums.
For example, given nums = [2,1,3], we will have 2 as the root, 1 as a left child, and 3 as a right child. The array [2,3,1] also yields the same BST but [3,2,1] yields a different BST.
Return the number of ways to reorder nums such that the BST formed is identical to the original BST formed from nums.
Since the answer may be very large, return it modulo 109 + 7.
Please complete the following python code precisely:
```python
class Solution:
def numOfWays(self, nums: List[int]) -> int:
```
|
{"functional": "def check(candidate):\n assert candidate(nums = [2,1,3]) == 1\n assert candidate(nums = [3,4,5,1,2]) == 5\n assert candidate(nums = [1,2,3]) == 0\n\n\ncheck(Solution().numOfWays)"}
| 222
| 73
|
coding
|
Solve the programming task below in a Python markdown code block.
A sequence $(b_1, b_2, \ldots, b_k)$ is called strange, if the absolute difference between any pair of its elements is greater than or equal to the maximum element in the sequence. Formally speaking, it's strange if for every pair $(i, j)$ with $1 \le i<j \le k$, we have $|a_i-a_j|\geq MAX$, where $MAX$ is the largest element of the sequence. In particular, any sequence of length at most $1$ is strange.
For example, the sequences $(-2021, -1, -1, -1)$ and $(-1, 0, 1)$ are strange, but $(3, 0, 1)$ is not, because $|0 - 1| < 3$.
Sifid has an array $a$ of $n$ integers. Sifid likes everything big, so among all the strange subsequences of $a$, he wants to find the length of the longest one. Can you help him?
A sequence $c$ is a subsequence of an array $d$ if $c$ can be obtained from $d$ by deletion of several (possibly, zero or all) elements.
-----Input-----
The first line contains an integer $t$ $(1\le t\le 10^4)$ — the number of test cases. The description of the test cases follows.
The first line of each test case contains an integer $n$ $(1\le n\le 10^5)$ — the length of the array $a$.
The second line of each test case contains $n$ integers $a_1, a_2, \ldots, a_n$ $(-10^9\le a_i \le 10^9)$ — the elements of the array $a$.
It is guaranteed that the sum of $n$ over all test cases doesn't exceed $10^5$.
-----Output-----
For each test case output a single integer — the length of the longest strange subsequence of $a$.
-----Examples-----
Input
6
4
-1 -2 0 0
7
-3 4 -2 0 -4 6 1
5
0 5 -3 2 -5
3
2 3 1
4
-3 0 2 0
6
-3 -2 -1 1 1 1
Output
4
5
4
1
3
4
-----Note-----
In the first test case, one of the longest strange subsequences is $(a_1, a_2, a_3, a_4)$
In the second test case, one of the longest strange subsequences is $(a_1, a_3, a_4, a_5, a_7)$.
In the third test case, one of the longest strange subsequences is $(a_1, a_3, a_4, a_5)$.
In the fourth test case, one of the longest strange subsequences is $(a_2)$.
In the fifth test case, one of the longest strange subsequences is $(a_1, a_2, a_4)$.
|
{"inputs": ["1\n1\n0\n", "1\n1\n0\n", "1\n1\n1\n", "1\n1\n2\n", "1\n2\n0 1\n", "1\n2\n0 1\n", "1\n3\n0 0 3\n", "1\n3\n0 0 4\n"], "outputs": ["1\n", "1\n", "1\n", "1\n", "2\n", "2\n", "2\n", "2\n"]}
| 701
| 114
|
coding
|
Solve the programming task below in a Python markdown code block.
There are three cells on an infinite 2-dimensional grid, labeled $A$, $B$, and $F$. Find the length of the shortest path from $A$ to $B$ if:
in one move you can go to any of the four adjacent cells sharing a side;
visiting the cell $F$ is forbidden (it is an obstacle).
-----Input-----
The first line contains an integer $t$ ($1 \le t \le 10^4$) — the number of test cases in the input. Then $t$ test cases follow. Before each test case, there is an empty line.
Each test case contains three lines. The first one contains two integers $x_A, y_A$ ($1 \le x_A, y_A \le 1000$) — coordinates of the start cell $A$. The second one contains two integers $x_B, y_B$ ($1 \le x_B, y_B \le 1000$) — coordinates of the finish cell $B$. The third one contains two integers $x_F, y_F$ ($1 \le x_F, y_F \le 1000$) — coordinates of the forbidden cell $F$. All cells are distinct.
Coordinate $x$ corresponds to the column number and coordinate $y$ corresponds to the row number (see the pictures below).
-----Output-----
Output $t$ lines. The $i$-th line should contain the answer for the $i$-th test case: the length of the shortest path from the cell $A$ to the cell $B$ if the cell $F$ is not allowed to be visited.
-----Examples-----
Input
7
1 1
3 3
2 2
2 5
2 1
2 3
1000 42
1000 1
1000 1000
1 10
3 10
2 10
3 8
7 8
3 7
2 1
4 1
1 1
1 344
1 10
1 1
Output
4
6
41
4
4
2
334
-----Note-----
An example of a possible shortest path for the first test case.
An example of a possible shortest path for the second test case.
|
{"inputs": ["7\n\n1 2\n3 3\n2 2\n\n2 5\n0 0\n2 3\n\n0000 16\n1010 1\n1010 1000\n\n1 10\n0 10\n2 10\n\n3 8\n8 2\n3 7\n\n2 0\n2 1\n1 1\n\n1 578\n1 6\n0 1\n", "7\n\n1 2\n3 3\n2 2\n\n2 5\n0 0\n2 3\n\n0000 16\n1010 1\n1010 1000\n\n1 10\n0 17\n2 10\n\n3 8\n8 2\n3 7\n\n2 0\n2 1\n1 1\n\n1 578\n1 6\n0 1\n", "7\n\n1 2\n3 3\n2 2\n\n2 7\n0 0\n2 3\n\n0000 16\n1010 1\n1010 1000\n\n1 10\n0 17\n2 10\n\n3 8\n8 2\n3 7\n\n2 0\n2 1\n1 1\n\n1 578\n1 6\n0 1\n", "7\n\n1 2\n3 3\n2 2\n\n2 7\n0 0\n2 3\n\n0000 16\n1010 1\n1010 1000\n\n1 10\n0 17\n2 10\n\n3 8\n8 2\n3 7\n\n2 0\n2 2\n1 1\n\n1 578\n1 6\n0 1\n", "7\n\n1 2\n3 3\n2 2\n\n2 7\n0 0\n2 3\n\n0000 16\n1010 1\n1010 1000\n\n1 10\n0 17\n2 10\n\n3 2\n8 2\n3 7\n\n2 0\n2 2\n1 1\n\n1 578\n1 6\n0 1\n", "7\n\n1 2\n3 3\n2 2\n\n2 8\n0 0\n2 3\n\n0000 16\n1010 1\n1010 1000\n\n1 10\n0 17\n2 10\n\n3 2\n8 2\n3 7\n\n2 0\n2 2\n1 1\n\n1 578\n1 6\n0 1\n", "7\n\n1 1\n3 3\n2 2\n\n2 5\n2 1\n2 3\n\n1000 42\n1000 1\n1000 1000\n\n1 10\n3 10\n2 10\n\n3 8\n7 8\n3 7\n\n2 1\n4 1\n1 1\n\n1 344\n1 10\n1 1\n", "7\n\n1 1\n3 3\n2 2\n\n2 5\n2 1\n2 3\n\n1000 42\n1000 1\n1000 1000\n\n1 10\n3 10\n2 10\n\n3 8\n7 8\n3 7\n\n2 1\n4 1\n1 1\n\n1 413\n1 10\n1 1\n"], "outputs": ["3\n7\n1025\n1\n11\n1\n572\n", "3\n7\n1025\n8\n11\n1\n572\n", "3\n9\n1025\n8\n11\n1\n572\n", "3\n9\n1025\n8\n11\n2\n572\n", "3\n9\n1025\n8\n5\n2\n572\n", "3\n10\n1025\n8\n5\n2\n572\n", "4\n6\n41\n4\n4\n2\n334\n", "4\n6\n41\n4\n4\n2\n403\n"]}
| 516
| 1,081
|
coding
|
Please solve the programming task below using a self-contained code snippet in a markdown code block.
You would like to make dessert and are preparing to buy the ingredients. You have n ice cream base flavors and m types of toppings to choose from. You must follow these rules when making your dessert:
There must be exactly one ice cream base.
You can add one or more types of topping or have no toppings at all.
There are at most two of each type of topping.
You are given three inputs:
baseCosts, an integer array of length n, where each baseCosts[i] represents the price of the ith ice cream base flavor.
toppingCosts, an integer array of length m, where each toppingCosts[i] is the price of one of the ith topping.
target, an integer representing your target price for dessert.
You want to make a dessert with a total cost as close to target as possible.
Return the closest possible cost of the dessert to target. If there are multiple, return the lower one.
Please complete the following python code precisely:
```python
class Solution:
def closestCost(self, baseCosts: List[int], toppingCosts: List[int], target: int) -> int:
```
|
{"functional": "def check(candidate):\n assert candidate(baseCosts = [1,7], toppingCosts = [3,4], target = 10) == 10\n assert candidate(baseCosts = [2,3], toppingCosts = [4,5,100], target = 18) == 17\n assert candidate(baseCosts = [3,10], toppingCosts = [2,5], target = 9) == 8\n assert candidate(baseCosts = [10], toppingCosts = [1], target = 1) == 10\n\n\ncheck(Solution().closestCost)"}
| 250
| 146
|
coding
|
Solve the programming task below in a Python markdown code block.
Let's define a split of $n$ as a nonincreasing sequence of positive integers, the sum of which is $n$.
For example, the following sequences are splits of $8$: $[4, 4]$, $[3, 3, 2]$, $[2, 2, 1, 1, 1, 1]$, $[5, 2, 1]$.
The following sequences aren't splits of $8$: $[1, 7]$, $[5, 4]$, $[11, -3]$, $[1, 1, 4, 1, 1]$.
The weight of a split is the number of elements in the split that are equal to the first element. For example, the weight of the split $[1, 1, 1, 1, 1]$ is $5$, the weight of the split $[5, 5, 3, 3, 3]$ is $2$ and the weight of the split $[9]$ equals $1$.
For a given $n$, find out the number of different weights of its splits.
-----Input-----
The first line contains one integer $n$ ($1 \leq n \leq 10^9$).
-----Output-----
Output one integer — the answer to the problem.
-----Examples-----
Input
7
Output
4
Input
8
Output
5
Input
9
Output
5
-----Note-----
In the first sample, there are following possible weights of splits of $7$:
Weight 1: [$\textbf 7$]
Weight 2: [$\textbf 3$, $\textbf 3$, 1]
Weight 3: [$\textbf 2$, $\textbf 2$, $\textbf 2$, 1]
Weight 7: [$\textbf 1$, $\textbf 1$, $\textbf 1$, $\textbf 1$, $\textbf 1$, $\textbf 1$, $\textbf 1$]
|
{"inputs": ["7\n", "8\n", "9\n", "1\n", "2\n", "3\n", "1\n", "3\n"], "outputs": ["4\n", "5\n", "5\n", "1\n", "2\n", "2\n", "1\n", "2\n"]}
| 459
| 70
|
coding
|
Solve the programming task below in a Python markdown code block.
You are given a text consisting of n lines. Each line contains some space-separated words, consisting of lowercase English letters.
We define a syllable as a string that contains exactly one vowel and any arbitrary number (possibly none) of consonants. In English alphabet following letters are considered to be vowels: 'a', 'e', 'i', 'o', 'u' and 'y'.
Each word of the text that contains at least one vowel can be divided into syllables. Each character should be a part of exactly one syllable. For example, the word "mamma" can be divided into syllables as "ma" and "mma", "mam" and "ma", and "mamm" and "a". Words that consist of only consonants should be ignored.
The verse patterns for the given text is a sequence of n integers p_1, p_2, ..., p_{n}. Text matches the given verse pattern if for each i from 1 to n one can divide words of the i-th line in syllables in such a way that the total number of syllables is equal to p_{i}.
You are given the text and the verse pattern. Check, if the given text matches the given verse pattern.
-----Input-----
The first line of the input contains a single integer n (1 ≤ n ≤ 100) — the number of lines in the text.
The second line contains integers p_1, ..., p_{n} (0 ≤ p_{i} ≤ 100) — the verse pattern.
Next n lines contain the text itself. Text consists of lowercase English letters and spaces. It's guaranteed that all lines are non-empty, each line starts and ends with a letter and words are separated by exactly one space. The length of each line doesn't exceed 100 characters.
-----Output-----
If the given text matches the given verse pattern, then print "YES" (without quotes) in the only line of the output. Otherwise, print "NO" (without quotes).
-----Examples-----
Input
3
2 2 3
intel
code
ch allenge
Output
YES
Input
4
1 2 3 1
a
bcdefghi
jklmnopqrstu
vwxyz
Output
NO
Input
4
13 11 15 15
to be or not to be that is the question
whether tis nobler in the mind to suffer
the slings and arrows of outrageous fortune
or to take arms against a sea of troubles
Output
YES
-----Note-----
In the first sample, one can split words into syllables in the following way: in-tel
co-de
ch al-len-ge
Since the word "ch" in the third line doesn't contain vowels, we can ignore it. As the result we get 2 syllabels in first two lines and 3 syllables in the third one.
|
{"inputs": ["1\n1\naa\n", "1\n1\naa\n", "1\n2\naa\n", "1\n0\naa\n", "1\n0\na`\n", "1\n0\n`a\n", "1\n1\naaa\n", "1\n1\naaa\n"], "outputs": ["NO\n", "NO\n", "YES\n", "NO\n", "NO\n", "NO\n", "NO\n", "NO\n"]}
| 626
| 104
|
coding
|
Solve the programming task below in a Python markdown code block.
After lessons Nastya decided to read a book. The book contains $n$ chapters, going one after another, so that one page of the book belongs to exactly one chapter and each chapter contains at least one page.
Yesterday evening Nastya did not manage to finish reading the book, so she marked the page with number $k$ as the first page which was not read (i.e. she read all pages from the $1$-st to the $(k-1)$-th).
The next day Nastya's friend Igor came and asked her, how many chapters remain to be read by Nastya? Nastya is too busy now, so she asks you to compute the number of chapters she has not completely read yet (i.e. the number of chapters she has not started to read or has finished reading somewhere in the middle).
-----Input-----
The first line contains a single integer $n$ ($1 \leq n \leq 100$) — the number of chapters in the book.
There are $n$ lines then. The $i$-th of these lines contains two integers $l_i$, $r_i$ separated by space ($l_1 = 1$, $l_i \leq r_i$) — numbers of the first and the last pages of the $i$-th chapter. It's guaranteed that $l_{i+1} = r_i + 1$ for all $1 \leq i \leq n-1$, and also that every chapter contains at most $100$ pages.
The $(n+2)$-th line contains a single integer $k$ ($1 \leq k \leq r_n$) — the index of the marked page.
-----Output-----
Print a single integer — the number of chapters which has not been completely read so far.
-----Examples-----
Input
3
1 3
4 7
8 11
2
Output
3
Input
3
1 4
5 9
10 12
9
Output
2
Input
1
1 7
4
Output
1
-----Note-----
In the first example the book contains $11$ pages and $3$ chapters — $[1;3]$, $[4;7]$ and $[8;11]$. Nastya marked the $2$-nd page, so she finished in the middle of the $1$-st chapter. So, all chapters has not been read so far, so the answer is $3$.
The book in the second example contains $12$ pages and $3$ chapters too, but Nastya finished reading in the middle of the $2$-nd chapter, so that the answer is $2$.
|
{"inputs": ["1\n1 7\n4\n", "1\n1 2\n1\n", "1\n1 7\n7\n", "1\n1 1\n1\n", "1\n1 7\n1\n", "1\n1 5\n1\n", "1\n1 5\n1\n", "1\n1 2\n1\n"], "outputs": ["1\n", "1\n", "1\n", "1\n", "1\n", "1\n", "1\n", "1\n"]}
| 602
| 118
|
coding
|
Solve the programming task below in a Python markdown code block.
Bob has ladder. He wants to climb this ladder, but being a precocious child, he wonders about exactly how many ways he could to climb this `n` size ladder using jumps of up to distance `k`.
Consider this example...
n = 5\
k = 3
Here, Bob has ladder of length 5, and with each jump, he can ascend up to 3 steps (he can either jump step 1 or 2 or 3). This gives the below possibilities
```
1 1 1 1 1
1 1 1 2
1 1 2 1
1 2 1 1
2 1 1 1
1 2 2
2 2 1
2 1 2
1 1 3
1 3 1
3 1 1
2 3
3 2
```
Your task to calculate number of ways to climb ladder of length `n` with upto `k` steps for Bob. (13 in above case)
Constraints:
```python
1<=n<=50
1<=k<=15
```
_Tip: try fibonacci._
Also feel free to reuse/extend the following starter code:
```python
def count_ways(n, k):
```
|
{"functional": "_inputs = [[1, 3], [3, 3], [2, 3], [5, 3], [4, 3], [10, 6], [14, 7]]\n_outputs = [[1], [4], [2], [13], [7], [492], [7936]]\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(count_ways(*i), o[0])"}
| 287
| 220
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.