input
stringlengths 50
13.9k
| output_program
stringlengths 5
655k
| output_answer
stringlengths 5
655k
| split
stringclasses 1
value | dataset
stringclasses 1
value |
---|---|---|---|---|
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.
|
from math import gcd
a, res1, res2, memo = 6, [0], [1], {1}
for i in range(1, 1000000):
x = a + gcd(i, a)
a, g = x, x-a
res1.append(res1[-1] + (g == 1))
if g not in memo:
res2.append(max(res2[-1], g))
memo.add(g)
count_ones = res1.__getitem__
max_pn = res2.__getitem__
an_over_average = lambda _: 3
|
from math import gcd
a, res1, res2, memo = 6, [0], [1], {1}
for i in range(1, 1000000):
x = a + gcd(i, a)
a, g = x, x-a
res1.append(res1[-1] + (g == 1))
if g not in memo:
res2.append(max(res2[-1], g))
memo.add(g)
count_ones = res1.__getitem__
max_pn = res2.__getitem__
an_over_average = lambda _: 3
|
train
|
APPS_structured
|
You and your best friend Stripes have just landed your first high school jobs! You'll be delivering newspapers to your neighbourhood on weekends. For your services you'll be charging a set price depending on the quantity of the newspaper bundles.
The cost of deliveries is:
- $3.85 for 40 newspapers
- $1.93 for 20
- $0.97 for 10
- $0.49 for 5
- $0.10 for 1
Stripes is taking care of the footwork doing door-to-door drops and your job is to take care of the finances. What you'll be doing is providing the cheapest possible quotes for your services.
Write a function that's passed an integer representing the amount of newspapers and returns the cheapest price. The returned number must be rounded to two decimal places.

|
bundles = {40:3.85, 20:1.93, 10:0.97, 5:0.49, 1:0.10}
def cheapest_quote(n):
if n == 0 : return 0.00
for i in [40,20,10,5,1] :
if n-i > -1:
return round(int(n/i) * bundles[i] + cheapest_quote(n%i), 2)
|
bundles = {40:3.85, 20:1.93, 10:0.97, 5:0.49, 1:0.10}
def cheapest_quote(n):
if n == 0 : return 0.00
for i in [40,20,10,5,1] :
if n-i > -1:
return round(int(n/i) * bundles[i] + cheapest_quote(n%i), 2)
|
train
|
APPS_structured
|
You are given a string $s[1 \dots n]$ consisting of lowercase Latin letters. It is guaranteed that $n = 2^k$ for some integer $k \ge 0$.
The string $s[1 \dots n]$ is called $c$-good if at least one of the following three conditions is satisfied: The length of $s$ is $1$, and it consists of the character $c$ (i.e. $s_1=c$); The length of $s$ is greater than $1$, the first half of the string consists of only the character $c$ (i.e. $s_1=s_2=\dots=s_{\frac{n}{2}}=c$) and the second half of the string (i.e. the string $s_{\frac{n}{2} + 1}s_{\frac{n}{2} + 2} \dots s_n$) is a $(c+1)$-good string; The length of $s$ is greater than $1$, the second half of the string consists of only the character $c$ (i.e. $s_{\frac{n}{2} + 1}=s_{\frac{n}{2} + 2}=\dots=s_n=c$) and the first half of the string (i.e. the string $s_1s_2 \dots s_{\frac{n}{2}}$) is a $(c+1)$-good string.
For example: "aabc" is 'a'-good, "ffgheeee" is 'e'-good.
In one move, you can choose one index $i$ from $1$ to $n$ and replace $s_i$ with any lowercase Latin letter (any character from 'a' to 'z').
Your task is to find the minimum number of moves required to obtain an 'a'-good string from $s$ (i.e. $c$-good string for $c=$ 'a'). It is guaranteed that the answer always exists.
You have to answer $t$ independent test cases.
Another example of an 'a'-good string is as follows. Consider the string $s = $"cdbbaaaa". It is an 'a'-good string, because: the second half of the string ("aaaa") consists of only the character 'a'; the first half of the string ("cdbb") is 'b'-good string, because: the second half of the string ("bb") consists of only the character 'b'; the first half of the string ("cd") is 'c'-good string, because: the first half of the string ("c") consists of only the character 'c'; the second half of the string ("d") is 'd'-good string.
-----Input-----
The first line of the input contains one integer $t$ ($1 \le t \le 2 \cdot 10^4$) — the number of test cases. Then $t$ test cases follow.
The first line of the test case contains one integer $n$ ($1 \le n \le 131~072$) — the length of $s$. It is guaranteed that $n = 2^k$ for some integer $k \ge 0$. The second line of the test case contains the string $s$ consisting of $n$ lowercase Latin letters.
It is guaranteed that the sum of $n$ does not exceed $2 \cdot 10^5$ ($\sum n \le 2 \cdot 10^5$).
-----Output-----
For each test case, print the answer — the minimum number of moves required to obtain an 'a'-good string from $s$ (i.e. $c$-good string with $c =$ 'a'). It is guaranteed that the answer exists.
-----Example-----
Input
6
8
bbdcaaaa
8
asdfghjk
8
ceaaaabb
8
bbaaddcc
1
z
2
ac
Output
0
7
4
5
1
1
|
def getAns(c, lo, hi, prefixCnt):
if lo+1 == hi:
return 1 - (prefixCnt[c][hi] - prefixCnt[c][lo])
mid = (lo + hi) // 2
ans = 1<<30
ans = min(ans, (hi - lo) // 2 - (prefixCnt[c][mid] - prefixCnt[c][lo]) + getAns(c+1, mid, hi, prefixCnt))
ans = min(ans, (hi - lo) // 2 - (prefixCnt[c][hi] - prefixCnt[c][mid]) + getAns(c+1, lo, mid, prefixCnt))
return ans
for _ in range(int(input())):
n = int(input())
s = input()
prefixCnt = [[0 for _ in range(n+1)] for _ in range(26)]
for i in range(n):
for j in range(26):
prefixCnt[j][i+1] = prefixCnt[j][i]
index = ord(s[i]) - ord('a')
prefixCnt[index][i+1] += 1
print(getAns(0, 0, n, prefixCnt))
|
def getAns(c, lo, hi, prefixCnt):
if lo+1 == hi:
return 1 - (prefixCnt[c][hi] - prefixCnt[c][lo])
mid = (lo + hi) // 2
ans = 1<<30
ans = min(ans, (hi - lo) // 2 - (prefixCnt[c][mid] - prefixCnt[c][lo]) + getAns(c+1, mid, hi, prefixCnt))
ans = min(ans, (hi - lo) // 2 - (prefixCnt[c][hi] - prefixCnt[c][mid]) + getAns(c+1, lo, mid, prefixCnt))
return ans
for _ in range(int(input())):
n = int(input())
s = input()
prefixCnt = [[0 for _ in range(n+1)] for _ in range(26)]
for i in range(n):
for j in range(26):
prefixCnt[j][i+1] = prefixCnt[j][i]
index = ord(s[i]) - ord('a')
prefixCnt[index][i+1] += 1
print(getAns(0, 0, n, prefixCnt))
|
train
|
APPS_structured
|
You are a *khm*mad*khm* scientist and you decided to play with electron distribution among atom's shells.
You know that basic idea of electron distribution is that electrons should fill a shell untill it's holding the maximum number of electrons.
---
Rules:
- Maximum number of electrons in a shell is distributed with a rule of 2n^2 (n being position of a shell).
- For example, maximum number of electrons in 3rd shield is 2*3^2 = 18.
- Electrons should fill the lowest level shell first.
- If the electrons have completely filled the lowest level shell, the other unoccupied electrons will fill the higher level shell and so on.
---
```
Ex.: atomicNumber(1); should return [1]
atomicNumber(10); should return [2, 8]
atomicNumber(11); should return [2, 8, 1]
atomicNumber(47); should return [2, 8, 18, 19]
```
|
def atomic_number(n):
L = []
i = 1
while n > 0:
a = min(2*i**2, n)
L.append(a)
n -= a
i += 1
return L
|
def atomic_number(n):
L = []
i = 1
while n > 0:
a = min(2*i**2, n)
L.append(a)
n -= a
i += 1
return L
|
train
|
APPS_structured
|
In this Kata, you will be given directions and your task will be to find your way back.
```Perl
solve(["Begin on Road A","Right on Road B","Right on Road C","Left on Road D"]) = ['Begin on Road D', 'Right on Road C', 'Left on Road B', 'Left on Road A']
solve(['Begin on Lua Pkwy', 'Right on Sixth Alley', 'Right on 1st Cr']) = ['Begin on 1st Cr', 'Left on Sixth Alley', 'Left on Lua Pkwy']
```
More examples in test cases.
Good luck!
Please also try [Simple remove duplicates](https://www.codewars.com/kata/5ba38ba180824a86850000f7)
|
from collections import deque
def solve(arr):
flip = {'Left': 'Right', 'Right': 'Left'}
# Build the prefixes
directions = deque([
flip.get(s, s)
for s in [s.split()[0] for s in arr]
])
directions.reverse()
directions.rotate(1)
# Get the rest of the directions
streets = [' '.join(s.split()[1:]) for s in arr][::-1]
# Zip and concatenate each pair
return [f'{direction} {street}' for direction, street in zip(directions, streets)]
|
from collections import deque
def solve(arr):
flip = {'Left': 'Right', 'Right': 'Left'}
# Build the prefixes
directions = deque([
flip.get(s, s)
for s in [s.split()[0] for s in arr]
])
directions.reverse()
directions.rotate(1)
# Get the rest of the directions
streets = [' '.join(s.split()[1:]) for s in arr][::-1]
# Zip and concatenate each pair
return [f'{direction} {street}' for direction, street in zip(directions, streets)]
|
train
|
APPS_structured
|
Your task in this kata is to implement the function `create_number_class` which will take a string parameter `alphabet` and return a class representing a number composed of this alphabet.
The class number will implement the four classical arithmetic operations (`+`, `-`, `*`, `//`), a method to convert itself to string, and a `convert_to` method which will take another class number as parameter and will return the value of the actual class number converted to the equivalent value with tha alphabet of the parameter class (return a new instance of this one).
Example:
```python
BinClass = create_number_class('01')
HexClass = create_number_class('0123456789ABCDEF')
x = BinClass('1010')
y = BinClass('10')
print(x+y) => '1100'
isinstance(x+y, BinClass) => True
print(x.convert_to(HexClass) => 'A'
```
___Notes:___
* Only positives integers will be used (either as parameters or results of calculations).
* You'll never encounter invalid calculations (divisions by zero or things like that).
* Alphabets will contain at least 2 characters.
|
def create_number_class(alp):
alphabet = {j: i for i, j in enumerate(alp)}
class BinClass:
def __init__(self, text) : self.text = text
__add__ = lambda self, other:self.op(self.text,other.text,'+')
__sub__ = lambda self, other:self.op(self.text,other.text,'-')
__mul__ = lambda self, other:self.op(self.text,other.text,'*')
__floordiv__ = lambda self, other:self.op(self.text,other.text,'//')
__str__ = lambda self:self.text
op = lambda self,a,b,sign:BinClass(self.from_decimal(eval('{} {} {}'.format(self.to_decimal(a),sign,self.to_decimal(b)))) or alp[0])
convert_to = lambda self, base:base(self.text).from_decimal(self.to_decimal(self.text))
to_decimal = lambda self, s:sum(alphabet[j] * (len(alp) ** (len(s)-1 - i)) for i, j in enumerate(s))
from_decimal = lambda self,s ,li=[]:self.from_decimal(s//len(alp),li+[s%len(alp)]) if s else ''.join([alp[int(i)] for i in li[::-1]])
return BinClass
|
def create_number_class(alp):
alphabet = {j: i for i, j in enumerate(alp)}
class BinClass:
def __init__(self, text) : self.text = text
__add__ = lambda self, other:self.op(self.text,other.text,'+')
__sub__ = lambda self, other:self.op(self.text,other.text,'-')
__mul__ = lambda self, other:self.op(self.text,other.text,'*')
__floordiv__ = lambda self, other:self.op(self.text,other.text,'//')
__str__ = lambda self:self.text
op = lambda self,a,b,sign:BinClass(self.from_decimal(eval('{} {} {}'.format(self.to_decimal(a),sign,self.to_decimal(b)))) or alp[0])
convert_to = lambda self, base:base(self.text).from_decimal(self.to_decimal(self.text))
to_decimal = lambda self, s:sum(alphabet[j] * (len(alp) ** (len(s)-1 - i)) for i, j in enumerate(s))
from_decimal = lambda self,s ,li=[]:self.from_decimal(s//len(alp),li+[s%len(alp)]) if s else ''.join([alp[int(i)] for i in li[::-1]])
return BinClass
|
train
|
APPS_structured
|
In this Kata, you will be given two numbers, n and k and your task will be to return the k-digit array that sums to n and has the maximum possible GCD.
For example, given `n = 12, k = 3`, there are a number of possible `3-digit` arrays that sum to `12`, such as `[1,2,9], [2,3,7], [2,4,6], ...` and so on. Of all the possibilities, the one with the highest GCD is `[2,4,6]`. Therefore, `solve(12,3) = [2,4,6]`.
Note also that digits cannot be repeated within the sub-array, so `[1,1,10]` is not a possibility. Lastly, if there is no such array, return an empty array.
More examples in the test cases.
Good luck!
|
def solve(n,k):
psum = (k * (k+1)) / 2
if n >= psum:
min_int = n // psum
while min_int > 0:
if n % min_int == 0:
return populate(n,min_int,k)
min_int -= 1
return []
def populate(n,s,k):
output = []
m = n
for i in range(1, k):
output.append(i*s)
m -= i*s
output.append(m)
return output
|
def solve(n,k):
psum = (k * (k+1)) / 2
if n >= psum:
min_int = n // psum
while min_int > 0:
if n % min_int == 0:
return populate(n,min_int,k)
min_int -= 1
return []
def populate(n,s,k):
output = []
m = n
for i in range(1, k):
output.append(i*s)
m -= i*s
output.append(m)
return output
|
train
|
APPS_structured
|
Every natural number, ```n```, may have a prime factorization like:
We define the **geometric derivative of n**, as a number with the following value:
For example: calculate the value of ```n*``` for ```n = 24500```.
```
24500 = 2²5³7²
n* = (2*2) * (3*5²) * (2*7) = 4200
```
Make a function, ```f``` that can perform this calculation
```
f(n) ----> n*
```
Every prime number will have ```n* = 1```.
Every number that does not have an exponent ```ki```, higher than 1, will give a ```n* = 1```, too
```python
f(24500) == 4200
f(997) == 1
```
Do your best!
|
def f(n):
factors = []
i = 2
while n > 1:
if n % i == 0:
n = n / i
factors.append(i)
else:
i += 1
from collections import Counter
from numpy import prod
return prod([occurences * factor ** (occurences - 1)
for factor, occurences in Counter(factors).items()])
|
def f(n):
factors = []
i = 2
while n > 1:
if n % i == 0:
n = n / i
factors.append(i)
else:
i += 1
from collections import Counter
from numpy import prod
return prod([occurences * factor ** (occurences - 1)
for factor, occurences in Counter(factors).items()])
|
train
|
APPS_structured
|
You have n tiles, where each tile has one letter tiles[i] printed on it.
Return the number of possible non-empty sequences of letters you can make using the letters printed on those tiles.
Example 1:
Input: tiles = "AAB"
Output: 8
Explanation: The possible sequences are "A", "B", "AA", "AB", "BA", "AAB", "ABA", "BAA".
Example 2:
Input: tiles = "AAABBC"
Output: 188
Example 3:
Input: tiles = "V"
Output: 1
Constraints:
1 <= tiles.length <= 7
tiles consists of uppercase English letters.
|
class Solution:
def numTilePossibilities(self, tiles: str) -> int:
def backtracking(idx=0,seq='',remaining=tiles):
for i, tile in enumerate(remaining):
res.add(seq+tile)
backtracking(idx+1, seq+tile, remaining[:i]+remaining[i+1:])
res = set()
backtracking()
return len(res)
|
class Solution:
def numTilePossibilities(self, tiles: str) -> int:
def backtracking(idx=0,seq='',remaining=tiles):
for i, tile in enumerate(remaining):
res.add(seq+tile)
backtracking(idx+1, seq+tile, remaining[:i]+remaining[i+1:])
res = set()
backtracking()
return len(res)
|
train
|
APPS_structured
|
At the legendary times of Nonsenso wars in ISM Dhanbad, there was a neck to neck competition between Barney Stinson and Sheldon Cooper. They both were on level 19. After trying too hard both of them could not decipher the nonsense, so they decided to play alongside. Sheldon Cooper had to pass a message to Barney Stinson. So he decided to convert each letter of the sentence to their corresponding to their ASCII codes. When Barney received the message he could not get anything. Now you have to design a code which converts the encrypted message to readable format.
-----Input-----
The input will consist of the first line containing the number of test cases ‘n’ followed by n lines of test cases.
-----Output-----
For each input print the decoded line.
-----Example-----
Input:
2
721011081081113287111114108100
871011089911110910132116111327311010010597
Output:
Hello World
Welcome to India
|
for _ in range(int(input())):
code=input().strip()+'0'
message=''
asc=int(code[0])
for i in range(len(code)-1):
if int(str(asc)+code[i+1])>256:
message+=chr(asc)
asc=int(code[i+1])
else:
asc=int(str(asc)+code[i+1])
print(message)
|
for _ in range(int(input())):
code=input().strip()+'0'
message=''
asc=int(code[0])
for i in range(len(code)-1):
if int(str(asc)+code[i+1])>256:
message+=chr(asc)
asc=int(code[i+1])
else:
asc=int(str(asc)+code[i+1])
print(message)
|
train
|
APPS_structured
|
Mary wrote a recipe book and is about to publish it, but because of a new European law, she needs to update and include all measures in grams.
Given all the measures in tablespoon (`tbsp`) and in teaspoon (`tsp`), considering `1 tbsp = 15g` and `1 tsp = 5g`, append to the end of the measurement the biggest equivalent integer (rounding up).
## Examples
```
"2 tbsp of butter" --> "2 tbsp (30g) of butter"
"1/2 tbsp of oregano" --> "1/2 tbsp (8g) of oregano"
"1/2 tsp of salt" --> "1/2 tbsp (3g) of salt"
"Add to the mixing bowl and coat well with 1 tbsp of olive oil & 1/2 tbsp of dried dill" -->
"Add to the mixing bowl and coat well with 1 tbsp (15g) of olive oil & 1/2 tbsp (8g) of dried dill"
```
|
import re,math
def convert_recipe(recipe):
r=re.sub('((\\d+(/\\d+)?) tbsp)',tbsp,recipe)
r=re.sub('((\\d+(/\\d+)?) tsp)',tsp,r)
return r
def tbsp(m):
return m.group(1)+" ("+str(math.ceil(eval('15*'+m.group(2))))+"g)"
def tsp(m):
return m.group(1)+" ("+str(math.ceil(eval('5*'+m.group(2))))+"g)"
|
import re,math
def convert_recipe(recipe):
r=re.sub('((\\d+(/\\d+)?) tbsp)',tbsp,recipe)
r=re.sub('((\\d+(/\\d+)?) tsp)',tsp,r)
return r
def tbsp(m):
return m.group(1)+" ("+str(math.ceil(eval('15*'+m.group(2))))+"g)"
def tsp(m):
return m.group(1)+" ("+str(math.ceil(eval('5*'+m.group(2))))+"g)"
|
train
|
APPS_structured
|
Chef has N subordinates. In order to complete a very important order he will choose exactly K of them. He can't choose less than K since it will be not enough to complete the order in time. On the other hand if he chooses more than K subordinates he can't control them during the operation. Help him to find the number of ways he can choose the team to complete this very important order.
-----Input-----
The first line contains a single positive integer T <= 100, the number of test cases. T test cases follow. The only line of each test case contains two integers N and K, where 0 <= N, K < 2^64. It is guaranteed that the answer will be less than 2^64.
-----Output-----
For each test case, output a single line containing the number of ways to choose the required team.
-----Example-----
Input:
3
2 1
3 3
10 5
Output:
2
1
252
|
T = int(input())
while(T):
s = input().split(' ')
N = int(s[0])
K = int(s[1])
if(N < K):
print('0')
else:
p = max(K,N-K)
q = min(K,N-K)
res = 1
while(N > p):
res *= N
N-=1
while(q > 1):
res /= q
q-=1
print(res)
T-=1
|
T = int(input())
while(T):
s = input().split(' ')
N = int(s[0])
K = int(s[1])
if(N < K):
print('0')
else:
p = max(K,N-K)
q = min(K,N-K)
res = 1
while(N > p):
res *= N
N-=1
while(q > 1):
res /= q
q-=1
print(res)
T-=1
|
train
|
APPS_structured
|
# Palindrome strings
A palindrome is a word, phrase, number, or other sequence of characters which reads the same backward or forward. This includes capital letters, punctuation, and word dividers.
Implement a function that checks if something is a palindrome.
## Examples
```
isPalindrome("anna") ==> true
isPalindrome("walter") ==> false
isPalindrome(12321) ==> true
isPalindrome(123456) ==> false
```
|
def is_palindrome(string):
return "".join("{}".format(string)[::-1])=="{}".format(string)
|
def is_palindrome(string):
return "".join("{}".format(string)[::-1])=="{}".format(string)
|
train
|
APPS_structured
|
Chef wants to teach a lesson of sharing to the students.
There are $N$ students (numbered from $1$ to $N$ from left to right) who are asked to stand in a row. Initially Chef gave $A$$i$ candies to the $i$$th$ child. In one operation any child can give any number of candies to the child standing to his immediate left (i.e. $i$$th$ child can give any amount of candies to the $(i-1)$$th$ child. In particular 1st child cannot give his candies to anyone).
He asked them to minimize the maximum value of candies a student can possess after performing any number of operations (possibly zero).
Help the students finding such maximum value.
-----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.
- First line of each test case contains a single integer $N$ denoting the number of students.
- Second line contains $N$ space-separated integers $A$$1$,$A$$2$,$.....$ $A$$N$ denoting the initial amount of candies chef gave to them.
-----Output:-----
- For each test case, print a single line containing one integer ― maximum value after sharing.
-----Constraints-----
- $1 \leq T \leq 100$
- $1 \leq N \leq 10^5$
- $0$ $\leq$ $A$$i$ $\leq$ $10^9$
- Sum of $N$ over all Test Cases does not exceed $10^5$
-----Sample Input-----
2
5
1 2 3 4 5
5
5 4 3 2 1
-----Sample Output-----
3
5
-----Explanation-----
-
For First Test Case:
The $5$$th$ student will give $2$ candies to $4$$th$ student and $4$$th$ will give $3$ candies to $3$$rd$ and $3$$rd$ will give $3$ candies to $2$$nd$ and $2$$nd$ will give $2$ candies to $1$$st$. So finally the number of candies that they will have are
$[3,3,3,3,3]$ and the value of maximum candies is $3$.
-
For Second Test Case:
Sharing to the left student will not change the maximum value as $1$$st$ cannot share to anyone. So the maximum value will remain $5$.
|
import math
T=int(input())
for _ in range(T):
N=int(input())
A=list(map(int,input().split()))
ans=0
left=0
for i in range(N):
v=A[i]-ans-left
if (v<0):
left=-v
else:
ans=ans+math.ceil(v/(i+1))
left=(math.ceil(v/(i+1))*(i+1))-v
print(ans)
|
import math
T=int(input())
for _ in range(T):
N=int(input())
A=list(map(int,input().split()))
ans=0
left=0
for i in range(N):
v=A[i]-ans-left
if (v<0):
left=-v
else:
ans=ans+math.ceil(v/(i+1))
left=(math.ceil(v/(i+1))*(i+1))-v
print(ans)
|
train
|
APPS_structured
|
Your task is to get Zodiac Sign using input ```day``` and ```month```.
For exapmle:
```python
get_zodiac_sign(1,5) => 'Taurus'
get_zodiac_sign(10,10) => 'Libra'
```
Correct answers are (preloaded):
```python
SIGNS = ['Capricorn', 'Aquarius', 'Pisces', 'Aries', 'Taurus', 'Gemini', 'Cancer', 'Leo', 'Virgo', 'Libra', 'Scorpio', 'Sagittarius']
```
P.S. Each argument is correct integer number.
WESTERN ASTROLOGY STAR SIGN DATES
* Aries (March 21-April 19)
* Taurus (April 20-May 20)
* Gemini (May 21-June 20)
* Cancer (June 21-July 22)
* Leo (July 23-August 22)
* Virgo (August 23-September 22)
* Libra (September 23-October 22)
* Scorpio (October 23-November 21)
* Sagittarius (November 22-December 21)
* Capricorn (December 22-January 19)
* Aquarius (January 20 to February 18)
* Pisces (February 19 to March 20)
|
from datetime import datetime
data = """
Aries March 21 April 19
Taurus April 20 May 20
Gemini May 21 June 20
Cancer June 21 July 22
Leo July 23 August 22
Virgo August 23 September 22
Libra September 23 October 22
Scorpio October 23 November 21
Sagittarius November 22 December 21
Capricorn December 22 January 19
Aquarius January 20 February 18
Pisces February 19 March 20
"""
data = [line.split() for line in data.split('\n') if line.strip()]
month = lambda s: datetime.strptime(s, '%B').month
data = [(z, month(m1), int(d1), month(m2), int(d2)) for z, m1, d1, m2, d2 in data]
def get_zodiac_sign(day, month):
for z, m1, d1, m2, d2 in data:
if (m1 == month and d1 <= day) or (m2 == month and day <= d2):
return z
|
from datetime import datetime
data = """
Aries March 21 April 19
Taurus April 20 May 20
Gemini May 21 June 20
Cancer June 21 July 22
Leo July 23 August 22
Virgo August 23 September 22
Libra September 23 October 22
Scorpio October 23 November 21
Sagittarius November 22 December 21
Capricorn December 22 January 19
Aquarius January 20 February 18
Pisces February 19 March 20
"""
data = [line.split() for line in data.split('\n') if line.strip()]
month = lambda s: datetime.strptime(s, '%B').month
data = [(z, month(m1), int(d1), month(m2), int(d2)) for z, m1, d1, m2, d2 in data]
def get_zodiac_sign(day, month):
for z, m1, d1, m2, d2 in data:
if (m1 == month and d1 <= day) or (m2 == month and day <= d2):
return z
|
train
|
APPS_structured
|
Given a string s of zeros and ones, return the maximum score after splitting the string into two non-empty substrings (i.e. left substring and right substring).
The score after splitting a string is the number of zeros in the left substring plus the number of ones in the right substring.
Example 1:
Input: s = "011101"
Output: 5
Explanation:
All possible ways of splitting s into two non-empty substrings are:
left = "0" and right = "11101", score = 1 + 4 = 5
left = "01" and right = "1101", score = 1 + 3 = 4
left = "011" and right = "101", score = 1 + 2 = 3
left = "0111" and right = "01", score = 1 + 1 = 2
left = "01110" and right = "1", score = 2 + 1 = 3
Example 2:
Input: s = "00111"
Output: 5
Explanation: When left = "00" and right = "111", we get the maximum score = 2 + 3 = 5
Example 3:
Input: s = "1111"
Output: 3
Constraints:
2 <= s.length <= 500
The string s consists of characters '0' and '1' only.
|
class Solution:
def maxScore(self, s: str) -> int:
def countchar(given, char):
count = 0
for x in given:
if x == char:
count += 1
return count
maxans = 0
for i in range(len(s)-1):
ans = 0
if s[:i+1]:
leftcount = countchar(s[:i+1], '0')
ans += leftcount
if s[i+1:]:
rightcount = countchar(s[i+1:], '1')
ans += rightcount
maxans = max(maxans, ans)
return maxans
|
class Solution:
def maxScore(self, s: str) -> int:
def countchar(given, char):
count = 0
for x in given:
if x == char:
count += 1
return count
maxans = 0
for i in range(len(s)-1):
ans = 0
if s[:i+1]:
leftcount = countchar(s[:i+1], '0')
ans += leftcount
if s[i+1:]:
rightcount = countchar(s[i+1:], '1')
ans += rightcount
maxans = max(maxans, ans)
return maxans
|
train
|
APPS_structured
|
The chess knight has a unique movement, it may move two squares vertically and one square horizontally, or two squares horizontally and one square vertically (with both forming the shape of an L). The possible movements of chess knight are shown in this diagaram:
A chess knight can move as indicated in the chess diagram below:
We have a chess knight and a phone pad as shown below, the knight can only stand on a numeric cell (i.e. blue cell).
Given an integer n, return how many distinct phone numbers of length n we can dial.
You are allowed to place the knight on any numeric cell initially and then you should perform n - 1 jumps to dial a number of length n. All jumps should be valid knight jumps.
As the answer may be very large, return the answer modulo 109 + 7.
Example 1:
Input: n = 1
Output: 10
Explanation: We need to dial a number of length 1, so placing the knight over any numeric cell of the 10 cells is sufficient.
Example 2:
Input: n = 2
Output: 20
Explanation: All the valid number we can dial are [04, 06, 16, 18, 27, 29, 34, 38, 40, 43, 49, 60, 61, 67, 72, 76, 81, 83, 92, 94]
Example 3:
Input: n = 3
Output: 46
Example 4:
Input: n = 4
Output: 104
Example 5:
Input: n = 3131
Output: 136006598
Explanation: Please take care of the mod.
Constraints:
1 <= n <= 5000
|
class Solution:
def knightDialer(self, n: int) -> int:
'''
0: 4,6
1: 6,8
2: 7,9
3: 4,8
4: 0,3,9
5: None
6: 1,7,0
7: 2,6
8: 1,3
9: 2,4
'''
mod = 10**9+7
nxt_pos = [[4,6],[6,8],[7,9],[4,8],[0,3,9],[],[1,7,0],[2,6],[1,3],[2,4]]
dp = [1 for _ in range(10)]
for _ in range(1,n):
new_dp = [0 for _ in range(10)]
for val,times in enumerate(dp):
for i in nxt_pos[val]:
new_dp[i] += times
new_dp[i] %= mod
dp = new_dp
return sum(dp)%mod
|
class Solution:
def knightDialer(self, n: int) -> int:
'''
0: 4,6
1: 6,8
2: 7,9
3: 4,8
4: 0,3,9
5: None
6: 1,7,0
7: 2,6
8: 1,3
9: 2,4
'''
mod = 10**9+7
nxt_pos = [[4,6],[6,8],[7,9],[4,8],[0,3,9],[],[1,7,0],[2,6],[1,3],[2,4]]
dp = [1 for _ in range(10)]
for _ in range(1,n):
new_dp = [0 for _ in range(10)]
for val,times in enumerate(dp):
for i in nxt_pos[val]:
new_dp[i] += times
new_dp[i] %= mod
dp = new_dp
return sum(dp)%mod
|
train
|
APPS_structured
|
There are n games in a football tournament. Three teams are participating in it. Currently k games had already been played.
You are an avid football fan, but recently you missed the whole k games. Fortunately, you remember a guess of your friend for these k games. Your friend did not tell exact number of wins of each team, instead he thought that absolute difference between number of wins of first and second team will be d_1 and that of between second and third team will be d_2.
You don't want any of team win the tournament, that is each team should have the same number of wins after n games. That's why you want to know: does there exist a valid tournament satisfying the friend's guess such that no team will win this tournament?
Note that outcome of a match can not be a draw, it has to be either win or loss.
-----Input-----
The first line of the input contains a single integer corresponding to number of test cases t (1 ≤ t ≤ 10^5).
Each of the next t lines will contain four space-separated integers n, k, d_1, d_2 (1 ≤ n ≤ 10^12; 0 ≤ k ≤ n; 0 ≤ d_1, d_2 ≤ k) — data for the current test case.
-----Output-----
For each test case, output a single line containing either "yes" if it is possible to have no winner of tournament, or "no" otherwise (without quotes).
-----Examples-----
Input
5
3 0 0 0
3 3 0 0
6 4 1 0
6 3 3 0
3 3 3 2
Output
yes
yes
yes
no
no
-----Note-----
Sample 1. There has not been any match up to now (k = 0, d_1 = 0, d_2 = 0). If there will be three matches (1-2, 2-3, 3-1) and each team wins once, then at the end each team will have 1 win.
Sample 2. You missed all the games (k = 3). As d_1 = 0 and d_2 = 0, and there is a way to play three games with no winner of tournament (described in the previous sample), the answer is "yes".
Sample 3. You missed 4 matches, and d_1 = 1, d_2 = 0. These four matches can be: 1-2 (win 2), 1-3 (win 3), 1-2 (win 1), 1-3 (win 1). Currently the first team has 2 wins, the second team has 1 win, the third team has 1 win. Two remaining matches can be: 1-2 (win 2), 1-3 (win 3). In the end all the teams have equal number of wins (2 wins).
|
read = lambda: list(map(int, input().split()))
f = lambda x, y, a, b: x > a or y > b or (a - x) % 3 or (b - y) % 3
g = lambda x, y, a, b: f(x, y, a, b) and f(x, y, b, a)
t = int(input())
for i in range(t):
n, k, d1, d2 = read()
r = n - k
d = d1 + d2
p = 2 * d2 - d1 if d2 > d1 else 2 * d1 - d2
print('no' if g(d, p, k, r) and g(d + d1, d + d2, k, r) else 'yes')
|
read = lambda: list(map(int, input().split()))
f = lambda x, y, a, b: x > a or y > b or (a - x) % 3 or (b - y) % 3
g = lambda x, y, a, b: f(x, y, a, b) and f(x, y, b, a)
t = int(input())
for i in range(t):
n, k, d1, d2 = read()
r = n - k
d = d1 + d2
p = 2 * d2 - d1 if d2 > d1 else 2 * d1 - d2
print('no' if g(d, p, k, r) and g(d + d1, d + d2, k, r) else 'yes')
|
train
|
APPS_structured
|
Problem description.
This problem is simple and will introduce you to the Dynamic Programming.
You will be given an array and a key value.
You will have to find out the occurrences of the key value depending upon the query using Brute Force and Top Down Dynamic Programming.
-----Brute-Force: -----
You will check the query, and calculate the occurrences.
-----DP: -----
You will check the query; check whether the memoized solution is already available.
If the memoized solution is available, no need to calculate the number of occurrences again.
If the memoized solution is not available, then calculate the number of occurrences and memoize it for future use.
-----Pseudo Code for DP:-----
countOccurences(key,from):
if (from = size of array) then
return 0
endif
if dp[from] is availabe then
return dp[from]
endif
if( array[from] == key) then
dp[from] = 1+countOccurences(key,from+1)
else
dp[from] = countOccurences(key,from+1)
endif
return dp[from]
-----Input:-----
The first line of input is the number of test cases (t).
The first line of each test case is the number of array elements (n).
The next will contain n space separated integers.
The next line will have the key element (k).
The next will have number of queries (q).
The next q lines will contain an integer A such that 0<=A < n.
You have to find out the number of occurrences from a to end of the array using both brute force and DP.
Everything will fit into the range of int.
-----Output:-----
For each test case, the output will have q lines with 3 space separated integers.
The first will be the number of occurrences, other will be the loop count/function calls,
using brute force and the last will be the number of loop count/function calls using DP.
-----Sample Input:-----
1
10
1 2 3 1 2 3 1 2 3 1
3
5
2
4
6
8
2
-----Sample output:-----
3 8 9
2 6 1
1 4 1
1 2 1
3 8 1
-----Explanation:-----
For the first query, we have to find the number of occurrences of 3 from index 2.
Using the brute force, the loop will check each element from index 2 to 9. Thus the loop count is 8.
Using DP, the method countOccurences(key,from) will be called like this :
countOccurences(3,2)->countOccurences(3,3)->countOccurences(3,4)->countOccurences(3,5)
->countOccurences(3,6)->countOccurences(3,7)->countOccurences(3,8)
->countOccurences(3,9)->countOccurences(3,10).
When the countOccurences(3,10) is called, it will return 0. Total 9 function calls.
For the second query, the brute force will do the same as above.
But the DP will check whether solution for countOccurences(3,4) is available or not.
As it was calculated while solving the first query, it won’t solve it again and will directly give the answer.
Total 1 function calls.
|
for t in range(int(input())):
n=int(input())
a=list(map(int,input().split()))
k=int(input())
dp=[0]*n
if (a[0]==k):
dp[0]=1
for i in range(1,n):
if (a[i]==k):
dp[i]=dp[i-1]+1
else:
dp[i]=dp[i-1]
dp_index=n
for q in range(int(input())):
x=int(input())
if (x==0):
print(dp[-1], end=' ')
else:
print(dp[-1]-dp[x-1], end=' ')
print(n-x, end=' ')
if (x<dp_index):
print(dp_index-x+1)
dp_index=x
else:
print(1)
|
for t in range(int(input())):
n=int(input())
a=list(map(int,input().split()))
k=int(input())
dp=[0]*n
if (a[0]==k):
dp[0]=1
for i in range(1,n):
if (a[i]==k):
dp[i]=dp[i-1]+1
else:
dp[i]=dp[i-1]
dp_index=n
for q in range(int(input())):
x=int(input())
if (x==0):
print(dp[-1], end=' ')
else:
print(dp[-1]-dp[x-1], end=' ')
print(n-x, end=' ')
if (x<dp_index):
print(dp_index-x+1)
dp_index=x
else:
print(1)
|
train
|
APPS_structured
|
# Story&Task
There are three parties in parliament. The "Conservative Party", the "Reformist Party", and a group of independants.
You are a member of the “Conservative Party” and you party is trying to pass a bill. The “Reformist Party” is trying to block it.
In order for a bill to pass, it must have a majority vote, meaning that more than half of all members must approve of a bill before it is passed . The "Conservatives" and "Reformists" always vote the same as other members of thier parties, meaning that all the members of each party will all vote yes, or all vote no .
However, independants vote individually, and the independant vote is often the determining factor as to whether a bill gets passed or not.
Your task is to find the minimum number of independents that have to vote for your party's (the Conservative Party's) bill so that it is passed .
In each test case the makeup of the Parliament will be different . In some cases your party may make up the majority of parliament, and in others it may make up the minority. If your party is the majority, you may find that you do not neeed any independants to vote in favor of your bill in order for it to pass . If your party is the minority, it may be possible that there are not enough independants for your bill to be passed . If it is impossible for your bill to pass, return `-1`.
# Input/Output
- `[input]` integer `totalMembers`
The total number of members.
- `[input]` integer `conservativePartyMembers`
The number of members in the Conservative Party.
- `[input]` integer `reformistPartyMembers`
The number of members in the Reformist Party.
- `[output]` an integer
The minimum number of independent members that have to vote as you wish so that the bill is passed, or `-1` if you can't pass it anyway.
# Example
For `n = 8, m = 3 and k = 3`, the output should be `2`.
It means:
```
Conservative Party member --> 3
Reformist Party member --> 3
the independent members --> 8 - 3 - 3 = 2
If 2 independent members change their minds
3 + 2 > 3
the bill will be passed.
If 1 independent members change their minds
perhaps the bill will be failed
(If the other independent members is against the bill).
3 + 1 <= 3 + 1
```
For `n = 13, m = 4 and k = 7`, the output should be `-1`.
```
Even if all 2 independent members support the bill
there are still not enough votes to pass the bill
4 + 2 < 7
So the output is -1
```
|
def pass_the_bill(total_members, conservative_party_members, reformist_party_members):
independants = total_members - conservative_party_members - reformist_party_members
majority = total_members // 2 + 1
needed = max(0, majority - conservative_party_members)
return -1 if needed > independants else needed
|
def pass_the_bill(total_members, conservative_party_members, reformist_party_members):
independants = total_members - conservative_party_members - reformist_party_members
majority = total_members // 2 + 1
needed = max(0, majority - conservative_party_members)
return -1 if needed > independants else needed
|
train
|
APPS_structured
|
Given an array A of integers, return the number of (contiguous, non-empty) subarrays that have a sum divisible by K.
Example 1:
Input: A = [4,5,0,-2,-3,1], K = 5
Output: 7
Explanation: There are 7 subarrays with a sum divisible by K = 5:
[4, 5, 0, -2, -3, 1], [5], [5, 0], [5, 0, -2, -3], [0], [0, -2, -3], [-2, -3]
Note:
1 <= A.length <= 30000
-10000 <= A[i] <= 10000
2 <= K <= 10000
|
class Solution:
def subarraysDivByK(self, A: List[int], K: int) -> int:
# (cs - cs[i]) % k == 0
res = 0
cs = 0
seen = collections.Counter({0: 1})
for i in range(len(A)):
x = A[i]
cs += x
if cs % K in seen:
res += seen[cs % K]
seen[cs % K] += 1
return res
|
class Solution:
def subarraysDivByK(self, A: List[int], K: int) -> int:
# (cs - cs[i]) % k == 0
res = 0
cs = 0
seen = collections.Counter({0: 1})
for i in range(len(A)):
x = A[i]
cs += x
if cs % K in seen:
res += seen[cs % K]
seen[cs % K] += 1
return res
|
train
|
APPS_structured
|
Given two strings, the first being a random string and the second being the same as the first, but with three added characters somewhere in the string (three same characters),
Write a function that returns the added character
### E.g
```
string1 = "hello"
string2 = "aaahello"
// => 'a'
```
The above is just an example; the characters could be anywhere in the string and string2 is actually **shuffled**.
### Another example
```
string1 = "abcde"
string2 = "2db2a2ec"
// => '2'
```
Note that the added character could also exist in the original string
```
string1 = "aabbcc"
string2 = "aacccbbcc"
// => 'c'
```
You can assume that string2 will aways be larger than string1, and there will always be three added characters in string2.
```if:c
Write the function `added_char()` that takes two strings and return the added character as described above.
```
```if:javascript
Write the function `addedChar()` that takes two strings and return the added character as described above.
```
|
added_char=lambda s1,s2:next(i for i in s2 if s1.count(i)!=s2.count(i))
|
added_char=lambda s1,s2:next(i for i in s2 if s1.count(i)!=s2.count(i))
|
train
|
APPS_structured
|
$n$ robots have escaped from your laboratory! You have to find them as soon as possible, because these robots are experimental, and their behavior is not tested yet, so they may be really dangerous!
Fortunately, even though your robots have escaped, you still have some control over them. First of all, you know the location of each robot: the world you live in can be modeled as an infinite coordinate plane, and the $i$-th robot is currently located at the point having coordinates ($x_i$, $y_i$). Furthermore, you may send exactly one command to all of the robots. The command should contain two integer numbers $X$ and $Y$, and when each robot receives this command, it starts moving towards the point having coordinates ($X$, $Y$). The robot stops its movement in two cases: either it reaches ($X$, $Y$); or it cannot get any closer to ($X$, $Y$).
Normally, all robots should be able to get from any point of the coordinate plane to any other point. Each robot usually can perform four actions to move. Let's denote the current coordinates of the robot as ($x_c$, $y_c$). Then the movement system allows it to move to any of the four adjacent points: the first action allows it to move from ($x_c$, $y_c$) to ($x_c - 1$, $y_c$); the second action allows it to move from ($x_c$, $y_c$) to ($x_c$, $y_c + 1$); the third action allows it to move from ($x_c$, $y_c$) to ($x_c + 1$, $y_c$); the fourth action allows it to move from ($x_c$, $y_c$) to ($x_c$, $y_c - 1$).
Unfortunately, it seems that some movement systems of some robots are malfunctioning. For each robot you know which actions it can perform, and which it cannot perform.
You want to send a command so all robots gather at the same point. To do so, you have to choose a pair of integer numbers $X$ and $Y$ so that each robot can reach the point ($X$, $Y$). Is it possible to find such a point?
-----Input-----
The first line contains one integer $q$ ($1 \le q \le 10^5$) — the number of queries.
Then $q$ queries follow. Each query begins with one line containing one integer $n$ ($1 \le n \le 10^5$) — the number of robots in the query. Then $n$ lines follow, the $i$-th of these lines describes the $i$-th robot in the current query: it contains six integer numbers $x_i$, $y_i$, $f_{i, 1}$, $f_{i, 2}$, $f_{i, 3}$ and $f_{i, 4}$ ($-10^5 \le x_i, y_i \le 10^5$, $0 \le f_{i, j} \le 1$). The first two numbers describe the initial location of the $i$-th robot, and the following four numbers describe which actions the $i$-th robot can use to move ($f_{i, j} = 1$ if the $i$-th robot can use the $j$-th action, and $f_{i, j} = 0$ if it cannot use the $j$-th action).
It is guaranteed that the total number of robots over all queries does not exceed $10^5$.
-----Output-----
You should answer each query independently, in the order these queries appear in the input.
To answer a query, you should do one of the following: if it is impossible to find a point that is reachable by all $n$ robots, print one number $0$ on a separate line; if it is possible to find a point that is reachable by all $n$ robots, print three space-separated integers on the same line: $1$ $X$ $Y$, where $X$ and $Y$ are the coordinates of the point reachable by all $n$ robots. Both $X$ and $Y$ should not exceed $10^5$ by absolute value; it is guaranteed that if there exists at least one point reachable by all robots, then at least one of such points has both coordinates not exceeding $10^5$ by absolute value.
-----Example-----
Input
4
2
-1 -2 0 0 0 0
-1 -2 0 0 0 0
3
1 5 1 1 1 1
2 5 0 1 0 1
3 5 1 0 0 0
2
1337 1337 0 1 1 1
1336 1337 1 1 0 1
1
3 5 1 1 1 1
Output
1 -1 -2
1 2 5
0
1 -100000 -100000
|
for _ in range(int(input())):
n = int(input())
maxx, minx = 100000, -100000
maxy, miny = 100000, -100000
for _ in range(n):
xi, yi, d, r, u, l = tuple(map(int, input().split()))
if d == 0:
minx = xi if xi > minx else minx
if r == 0:
maxy = yi if yi < maxy else maxy
if u == 0:
maxx = xi if xi < maxx else maxx
if l == 0:
miny = yi if yi > miny else miny
if miny <= maxy and minx <= maxx:
print(1, minx, miny)
else:
print(0)
|
for _ in range(int(input())):
n = int(input())
maxx, minx = 100000, -100000
maxy, miny = 100000, -100000
for _ in range(n):
xi, yi, d, r, u, l = tuple(map(int, input().split()))
if d == 0:
minx = xi if xi > minx else minx
if r == 0:
maxy = yi if yi < maxy else maxy
if u == 0:
maxx = xi if xi < maxx else maxx
if l == 0:
miny = yi if yi > miny else miny
if miny <= maxy and minx <= maxx:
print(1, minx, miny)
else:
print(0)
|
train
|
APPS_structured
|
In this kata you will create a function to check a non-negative input to see if it is a prime number.
The function will take in a number and will return True if it is a prime number and False if it is not.
A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself.
### Examples
|
def is_prime(num):
'Return True if n is a prime number otherwise return False'
return num > 1 and not any(num % n == 0 for n in range(2, num))
|
def is_prime(num):
'Return True if n is a prime number otherwise return False'
return num > 1 and not any(num % n == 0 for n in range(2, num))
|
train
|
APPS_structured
|
In this problem, we will deal with binary strings. Each character of a binary string is either a 0 or a 1. We will also deal with substrings; recall that a substring is a contiguous subsequence of a string. We denote the substring of string $s$ starting from the $l$-th character and ending with the $r$-th character as $s[l \dots r]$. The characters of each string are numbered from $1$.
We can perform several operations on the strings we consider. Each operation is to choose a substring of our string and replace it with another string. There are two possible types of operations: replace 011 with 110, or replace 110 with 011. For example, if we apply exactly one operation to the string 110011110, it can be transformed into 011011110, 110110110, or 110011011.
Binary string $a$ is considered reachable from binary string $b$ if there exists a sequence $s_1$, $s_2$, ..., $s_k$ such that $s_1 = a$, $s_k = b$, and for every $i \in [1, k - 1]$, $s_i$ can be transformed into $s_{i + 1}$ using exactly one operation. Note that $k$ can be equal to $1$, i. e., every string is reachable from itself.
You are given a string $t$ and $q$ queries to it. Each query consists of three integers $l_1$, $l_2$ and $len$. To answer each query, you have to determine whether $t[l_1 \dots l_1 + len - 1]$ is reachable from $t[l_2 \dots l_2 + len - 1]$.
-----Input-----
The first line contains one integer $n$ ($1 \le n \le 2 \cdot 10^5$) — the length of string $t$.
The second line contains one string $t$ ($|t| = n$). Each character of $t$ is either 0 or 1.
The third line contains one integer $q$ ($1 \le q \le 2 \cdot 10^5$) — the number of queries.
Then $q$ lines follow, each line represents a query. The $i$-th line contains three integers $l_1$, $l_2$ and $len$ ($1 \le l_1, l_2 \le |t|$, $1 \le len \le |t| - \max(l_1, l_2) + 1$) for the $i$-th query.
-----Output-----
For each query, print either YES if $t[l_1 \dots l_1 + len - 1]$ is reachable from $t[l_2 \dots l_2 + len - 1]$, or NO otherwise. You may print each letter in any register.
-----Example-----
Input
5
11011
3
1 3 3
1 4 2
1 2 3
Output
Yes
Yes
No
|
import sys
input = sys.stdin.readline
MOD = 987654103
n = int(input())
t = input()
place = []
f1 = []
e1 = []
s = []
curr = 0
count1 = 0
for i in range(n):
c = t[i]
if c == '0':
if count1:
e1.append(i - 1)
if count1 & 1:
s.append(1)
curr += 1
e1.append(-1)
f1.append(-1)
count1 = 0
else:
f1.append(-1)
e1.append(-1)
place.append(curr)
curr += 1
s.append(0)
else:
if count1 == 0:
f1.append(i)
count1 += 1
place.append(curr)
if count1:
if count1 & 1:
s.append(1)
else:
s.append(0)
curr += 1
e1.append(n - 1)
e1.append(-1)
f1.append(-1)
place.append(curr)
pref = [0]
val = 0
for i in s:
val *= 3
val += i + 1
val %= MOD
pref.append(val)
q = int(input())
out = []
for _ in range(q):
l1, l2, leng = list(map(int, input().split()))
l1 -= 1
l2 -= 1
starts = (l1, l2)
hashes = []
for start in starts:
end = start + leng - 1
smap = place[start]
emap = place[end]
if t[end] == '1':
emap -= 1
if s[smap] == 1:
smap += 1
prep = False
app = False
if t[start] == '1':
last = e1[place[start]]
last = min(last, end)
count = last - start + 1
if count % 2:
prep = True
if t[end] == '1':
first = f1[place[end]]
first = max(first, start)
count = end - first + 1
if count % 2:
app = True
preHash = 0
length = 0
if smap <= emap:
length = emap - smap + 1
preHash = pref[emap + 1]
preHash -= pref[smap] * pow(3, emap - smap + 1, MOD)
preHash %= MOD
if length == 0 and prep and app:
app = False
#print(preHash, prep, app, length)
if prep:
preHash += pow(3, length, MOD) * 2
length += 1
if app:
preHash *= 3
preHash += 2
#print(preHash)
preHash %= MOD
hashes.append(preHash)
if hashes[0] == hashes[1]:
out.append('Yes')
else:
out.append('No')
print('\n'.join(out))
|
import sys
input = sys.stdin.readline
MOD = 987654103
n = int(input())
t = input()
place = []
f1 = []
e1 = []
s = []
curr = 0
count1 = 0
for i in range(n):
c = t[i]
if c == '0':
if count1:
e1.append(i - 1)
if count1 & 1:
s.append(1)
curr += 1
e1.append(-1)
f1.append(-1)
count1 = 0
else:
f1.append(-1)
e1.append(-1)
place.append(curr)
curr += 1
s.append(0)
else:
if count1 == 0:
f1.append(i)
count1 += 1
place.append(curr)
if count1:
if count1 & 1:
s.append(1)
else:
s.append(0)
curr += 1
e1.append(n - 1)
e1.append(-1)
f1.append(-1)
place.append(curr)
pref = [0]
val = 0
for i in s:
val *= 3
val += i + 1
val %= MOD
pref.append(val)
q = int(input())
out = []
for _ in range(q):
l1, l2, leng = list(map(int, input().split()))
l1 -= 1
l2 -= 1
starts = (l1, l2)
hashes = []
for start in starts:
end = start + leng - 1
smap = place[start]
emap = place[end]
if t[end] == '1':
emap -= 1
if s[smap] == 1:
smap += 1
prep = False
app = False
if t[start] == '1':
last = e1[place[start]]
last = min(last, end)
count = last - start + 1
if count % 2:
prep = True
if t[end] == '1':
first = f1[place[end]]
first = max(first, start)
count = end - first + 1
if count % 2:
app = True
preHash = 0
length = 0
if smap <= emap:
length = emap - smap + 1
preHash = pref[emap + 1]
preHash -= pref[smap] * pow(3, emap - smap + 1, MOD)
preHash %= MOD
if length == 0 and prep and app:
app = False
#print(preHash, prep, app, length)
if prep:
preHash += pow(3, length, MOD) * 2
length += 1
if app:
preHash *= 3
preHash += 2
#print(preHash)
preHash %= MOD
hashes.append(preHash)
if hashes[0] == hashes[1]:
out.append('Yes')
else:
out.append('No')
print('\n'.join(out))
|
train
|
APPS_structured
|
You are given a sequence $A_1, A_2, \ldots, A_N$. You have to split the array into maximum number of non-empty subarrays such that the gcd of elements of each subarray is equal to 1.
-----Input:-----
- The first line of the input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows.
- The first line of each test case contains a single integer $N$.
- 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 number of subarrays formed, or $-1$ if the array cannot be split while satisfying the above condition.
-----Constraints-----
- $1 \le T \le 3$
- $1 \le N \le 5 \cdot 10^5$
- $1 \le A_i \le 10^6$ for each valid $i$
-----Sample Input:-----
2
3
2 2 3
4
2 3 3 2
-----Sample Output:-----
1
2
|
MOD = 1000000007
MOD2 = 998244353
ii = lambda: int(input())
si = lambda: input()
dgl = lambda: list(map(int, input()))
f = lambda: map(int, input().split())
il = lambda: list(map(int, input().split()))
ls = lambda: list(input())
from math import gcd
for _ in range(ii()):
n=ii()
l=il()
c=0
g=0
for i in range(n):
g = gcd(g,l[i])
if g==1:
c+=1
g=0
print(c)
|
MOD = 1000000007
MOD2 = 998244353
ii = lambda: int(input())
si = lambda: input()
dgl = lambda: list(map(int, input()))
f = lambda: map(int, input().split())
il = lambda: list(map(int, input().split()))
ls = lambda: list(input())
from math import gcd
for _ in range(ii()):
n=ii()
l=il()
c=0
g=0
for i in range(n):
g = gcd(g,l[i])
if g==1:
c+=1
g=0
print(c)
|
train
|
APPS_structured
|
# Task
You are a magician. You're going to perform a trick.
You have `b` black marbles and `w` white marbles in your magic hat, and an infinite supply of black and white marbles that you can pull out of nowhere.
You ask your audience to repeatedly remove a pair of marbles from your hat and, for each pair removed, you add one marble to the hat according to the following rule until there is only 1 marble left.
If the marbles of the pair that is removed are of the same color, you add a white marble to the hat. Otherwise, if one is black and one is white, you add a black marble.
Given the initial number of black and white marbles in your hat, your trick is to predict the color of the last marble.
Note: A magician may confuse your eyes, but not your mind ;-)
# Input/Output
- `[input]` integer `b`
Initial number of black marbles in the hat.
`1 <= b <= 10^9`
- `[input]` integer `w`
Initial number of white marbles in the hat.
`1 <= w <= 10^9`
- `[output]` a string
`"Black"` or `"White"` if you can safely predict the color of the last marble. If not, return `"Unsure"`.
|
def not_so_random(b,w):
return ('White', 'Black')[b % 2]
|
def not_so_random(b,w):
return ('White', 'Black')[b % 2]
|
train
|
APPS_structured
|
For encrypting strings this region of chars is given (in this order!):
* all letters (ascending, first all UpperCase, then all LowerCase)
* all digits (ascending)
* the following chars: `.,:;-?! '()$%&"`
These are 77 chars! (This region is zero-based.)
Write two methods:
```python
def encrypt(text)
def decrypt(encrypted_text)
```
Prechecks:
1. If the input-string has chars, that are not in the region, throw an Exception(C#, Python) or Error(JavaScript).
2. If the input-string is null or empty return exactly this value!
For building the encrypted string:
1. For every second char do a switch of the case.
2. For every char take the index from the region. Take the difference from the region-index of the char before (from the input text! Not from the fresh encrypted char before!). (Char2 = Char1-Char2)
Replace the original char by the char of the difference-value from the region. In this step the first letter of the text is unchanged.
3. Replace the first char by the mirror in the given region. (`'A' -> '"'`, `'B' -> '&'`, ...)
Simple example:
* Input: `"Business"`
* Step 1: `"BUsInEsS"`
* Step 2: `"B61kujla"`
* `B -> U`
* `B (1) - U (20) = -19`
* `-19 + 77 = 58`
* `Region[58] = "6"`
* `U -> s`
* `U (20) - s (44) = -24`
* `-24 + 77 = 53`
* `Region[53] = "1"`
* Step 3: `"&61kujla"`
This kata is part of the Simple Encryption Series:
Simple Encryption #1 - Alternating Split
Simple Encryption #2 - Index-Difference
Simple Encryption #3 - Turn The Bits Around
Simple Encryption #4 - Qwerty
Have fun coding it and please don't forget to vote and rank this kata! :-)
|
from string import ascii_lowercase as l, ascii_uppercase as u, digits as di
encrypt=lambda s:doall(s)
decrypt=lambda s:doall(s,True)
def doall(s,d=False):
if not s:return s
all_char = list(u+l+di+".,:;-?! '()$%&" + '"')
s = "".join([j.swapcase() if i & 1 else j for i, j in enumerate(s)]) if not d else s
new,well = [],[all_char[-1-all_char.index(s[0])]]
for i in range(len(s) - 1):
c_ = well[-1] if d else s[i]
t_ = s[i + 1]
diff = all_char.index(c_) - all_char.index(t_)
well.append(all_char[diff])
new.append(all_char[diff])
encode = all_char[-1 - all_char.index(s[0])] + "".join(new)
decode = "".join([j.swapcase()if i&1 else j for i,j in enumerate("".join(well))])
return [encode,decode][d]
|
from string import ascii_lowercase as l, ascii_uppercase as u, digits as di
encrypt=lambda s:doall(s)
decrypt=lambda s:doall(s,True)
def doall(s,d=False):
if not s:return s
all_char = list(u+l+di+".,:;-?! '()$%&" + '"')
s = "".join([j.swapcase() if i & 1 else j for i, j in enumerate(s)]) if not d else s
new,well = [],[all_char[-1-all_char.index(s[0])]]
for i in range(len(s) - 1):
c_ = well[-1] if d else s[i]
t_ = s[i + 1]
diff = all_char.index(c_) - all_char.index(t_)
well.append(all_char[diff])
new.append(all_char[diff])
encode = all_char[-1 - all_char.index(s[0])] + "".join(new)
decode = "".join([j.swapcase()if i&1 else j for i,j in enumerate("".join(well))])
return [encode,decode][d]
|
train
|
APPS_structured
|
Task
Create a top-down movement system that would feel highly responsive to the player. In your Update method you have to check for the keys that are currently being pressed, the keys correspond to the enum Direction shown below, based on which key is pressed or released your method should behave this way:
1) When a key is first pressed, the player has to change his direction to that of the current key, without moving
2) If the key is still being pressed during the next Update, the player will move towards his current direction using these vectors: (Up = { 0, +1 } , Down = { 0, -1 }, Left = { -1, 0 }, Right = { +1, 0 })
3) If a new key is pressed, it will gain precedence over the previous key and the player will act as per 1)
4-A) If the current key (A) is released, then the precedence will go back to the previous key (B) (or the one before it, if (B) is not pressed anymore, and so on), then the player will behave as per 1).
4-B) If the current key is released, and no other keys are being pressed, the player will stand still
5) If all keys are released at once, the player will not move nor change direction
6) If multiple keys are pressed at once, the order of precedence will be the following { Up, Down, Left, Right }
Examples
(n = pressed key, [n] = current key, p() = press, r() = release, (8,2,4,6 = up, down, left, right)):
[] , p(8) -> [8] , p(4,6) -> 86[4] , r(6) -> 8[4] , r(4) -> [8] , r(8) -> []
[] , p(2486) -> 642[8] , r(2,8) -> 6[4] , r(4,6) -> []
This is what you'll need to use in your code (NB: the tile coordinates cannot be changed, you'll need to assign a new Tile each time the player moves):
```python
class Tile:
@property
def x(self):
return self._x
@property
def y(self):
return self._y
def __str__(self):
return "({},{})".format(self._x, self._y)
class Input:
@staticmethod
def get_state(direction): # 2, 4, 6, 8
return Input.STATES[direction] # pressed = true, released = false
```
|
class PlayerMovement: # class by MMMAAANNN @ codewars.com
KEYS = 6, 4, 2, 8 # In order of reverse priority
DIRS = dict(list(zip(KEYS, (( 1, 0), # Associating with directions
(-1, 0),
( 0, -1),
( 0, 1)))))
def __init__(self, x, y):
self.position = Tile(x, y)
self.direction = 8
self.previous = {i: False for i in self.KEYS} # Event detection
self.keystack = [0] # The order of keypress
def update(self):
current = dict(list(Input.STATES.items())) # Read current state
if (current != self.previous): # Skip recalc if no events happened
change = {i : current[i] - self.previous[i] # Calculate type of change
for i in self.KEYS}
for key in self.KEYS: # Update the status of keystack
if change[key] > 0:
self.keystack.append(key)
elif change[key] < 0:
self.keystack.remove(key)
if (self.keystack[-1] == self.direction # Movement only if no turn required
and sum(self.previous.values())): # Avoid moving if first event after idle
dx, dy = self.DIRS[self.direction] # Reading the movement vector
self.position = Tile(self.position.x + dx, # Updating coordinates: x
self.position.y + dy) # ... and y
else:
self.direction = self.keystack[-1] or self.direction # Turning if needed
self.previous = current # Remember state to detect next event
|
class PlayerMovement: # class by MMMAAANNN @ codewars.com
KEYS = 6, 4, 2, 8 # In order of reverse priority
DIRS = dict(list(zip(KEYS, (( 1, 0), # Associating with directions
(-1, 0),
( 0, -1),
( 0, 1)))))
def __init__(self, x, y):
self.position = Tile(x, y)
self.direction = 8
self.previous = {i: False for i in self.KEYS} # Event detection
self.keystack = [0] # The order of keypress
def update(self):
current = dict(list(Input.STATES.items())) # Read current state
if (current != self.previous): # Skip recalc if no events happened
change = {i : current[i] - self.previous[i] # Calculate type of change
for i in self.KEYS}
for key in self.KEYS: # Update the status of keystack
if change[key] > 0:
self.keystack.append(key)
elif change[key] < 0:
self.keystack.remove(key)
if (self.keystack[-1] == self.direction # Movement only if no turn required
and sum(self.previous.values())): # Avoid moving if first event after idle
dx, dy = self.DIRS[self.direction] # Reading the movement vector
self.position = Tile(self.position.x + dx, # Updating coordinates: x
self.position.y + dy) # ... and y
else:
self.direction = self.keystack[-1] or self.direction # Turning if needed
self.previous = current # Remember state to detect next event
|
train
|
APPS_structured
|
A circle is defined by three coplanar points that are not aligned.
You will be given a list of circles and a point [xP, yP]. You have to create a function, ```count_circles()``` (Javascript ```countCircles()```), that will count the amount of circles that contains the point P inside (the circle border line is included).
```python
list_of_circles = ([[[-3,2], [1,1], [6,4]], [[-3,2], [1,1], [2,6]], [[1,1], [2,6], [6,4]], [[[-3,2],[2,6], [6,4]]]
point1 = [1, 4] # P1
count_circles(list_of_circles, point1) == 4 #(The four circles have P1 inside)
```
It may happen that the point may be external to all the circles.
```python
list_of_circles = ([[[-3,2], [1,1], [6,4]], [[-3,2], [1,1], [2,6]], [[1,1], [2,6], [6,4]], [[-3,2],[2,6], [6,4]]]
point2 = [10, 6] # P2
count_circles(list_of_circles, point2) == 0 #(P2 is exterior to the four circles)
```
The point may be in the circle line and that will be consider as an internal point of it, too.
For practical purposes a given point ```P``` will be in the circle line if:
|r - d|/r < 10^(-10)
```r```: radius of the circle that should be calculated from the coordinates of the three given points.
```d```: distance from the point ```P``` to the center of the circle. Again we have to do a calculation, the coordinates of the center should be calculated using the coordinates of the three given points.
Let's see a case when the pints is in the circle line.
```python
list_of_circles = ([[[-3,2], [1,1], [6,4]], [[-3,2], [1,1], [2,6]], [[1,1], [2,6], [6,4]], [[[-3,2],[2,6], [6,4]]]
point3 = point2 = [2, 6] # P3
count_circles(list_of_circles, point3) == 4 #(P3 is an internal point of the four circles)
```
All these three cases are shown in the image below:
Your code should be able to skip these cases:
- inexistent circle when we have three points aligned
- undefined circles when two or three of given points coincides.
First ten people to solve it will receive extra points.
Hints: This kata will give you important formulas: ```Give The Center And The Radius of Circumscribed Circle. (A warm up challenge)```
```http://www.codewars.com/kata/give-the-center-and-the-radius-of-circumscribed-circle-a-warm-up-challenge```
Features of the tests:
```N: amount of Tests```
```n: amount of given circles```
```x, y: coordinates of the points that define the circle```
```xP, yP: coordinates of the point P```
```N = 500```
```10 < n < 500```
```-500 < x < 500, -500 < y < 500```
```-750 < xP < -750, -750 < yP < -750```
|
def count_circles(list_of_circles, point, count = 0):
return sum(1 for circle in list_of_circles if point_in(circle, point))
def point_in(points, point):
helper = lambda x,y: (-1)**y*(points[(x+1)%3][(y+1)%2] - points[(x+2)%3][(y+1)%2])
D = 2*sum(points[i][0]*helper(i,0) for i in range(3))
U = [1.0 * sum(sum(points[i][j]**2 for j in range(2))*helper(i,k) for i in range(3))/D for k in range(2)]
return compare(point, U, radius(points,D)) if (not invalid(points, D)) else False
compare = lambda p, U, r: ((distance(U,p) < r) or (abs(r-distance(U,p))/r < 10**-10))
distance = lambda p1, p2: ((p2[0] - p1[0])**2 + (p2[1] - p1[1])**2)**0.5
invalid = lambda p, D: ((D == 0) or (p[0] == p[1]) or (p[0] == p[2]) or (p[1] == p[2]))
radius = lambda p, D: distance(p[0],p[1])*distance(p[0],p[2])*distance(p[1],p[2])/abs(D)
|
def count_circles(list_of_circles, point, count = 0):
return sum(1 for circle in list_of_circles if point_in(circle, point))
def point_in(points, point):
helper = lambda x,y: (-1)**y*(points[(x+1)%3][(y+1)%2] - points[(x+2)%3][(y+1)%2])
D = 2*sum(points[i][0]*helper(i,0) for i in range(3))
U = [1.0 * sum(sum(points[i][j]**2 for j in range(2))*helper(i,k) for i in range(3))/D for k in range(2)]
return compare(point, U, radius(points,D)) if (not invalid(points, D)) else False
compare = lambda p, U, r: ((distance(U,p) < r) or (abs(r-distance(U,p))/r < 10**-10))
distance = lambda p1, p2: ((p2[0] - p1[0])**2 + (p2[1] - p1[1])**2)**0.5
invalid = lambda p, D: ((D == 0) or (p[0] == p[1]) or (p[0] == p[2]) or (p[1] == p[2]))
radius = lambda p, D: distance(p[0],p[1])*distance(p[0],p[2])*distance(p[1],p[2])/abs(D)
|
train
|
APPS_structured
|
# Task
Mr.Nam has `n` candies, he wants to put one candy in each cell of a table-box. The table-box has `r` rows and `c` columns.
Each candy was labeled by its cell number. The cell numbers are in range from 1 to N and the direction begins from right to left and from bottom to top.
Nam wants to know the position of a specific `candy` and which box is holding it.
The result should be an array and contain exactly 3 elements. The first element is the `label` of the table; The second element is the `row` of the candy; The third element is the `column` of the candy.
If there is no candy with the given number, return `[-1, -1, -1]`.
Note:
When the current box is filled up, Nam buys another one.
The boxes are labeled from `1`.
Rows and columns are `0`-based numbered from left to right and from top to bottom.
# Example
For `n=6,r=2,c=2,candy=3`, the result should be `[1,0,1]`
the candies will be allocated like this:
```
Box 1
+-----+-----+
| 4 | (3) | --> box 1,row 0, col 1
+-----+-----+
| 2 | 1 |
+-----+-----+
Box 2
+-----+-----+
| x | x |
+-----+-----+
| 6 | (5) | --> box 2,row 1, col 1
+-----+-----+```
For `candy = 5(n,r,c same as above)`, the output should be `[2,1,1]`.
For `candy = 7(n,r,c same as above)`, the output should be `[-1,-1,-1]`.
For `n=8,r=4,c=2,candy=3`, the result should be `[1,2,1]`
```
Box 1
+-----+-----+
| 8 | 7 |
+-----+-----+
| 6 | 5 |
+-----+-----+
| 4 | (3) |--> box 1,row 2, col 1
+-----+-----+
| 2 | 1 |
+-----+-----+
```
# Input/Output
- `[input]` integer `n`
The number of candies.
`0 < n <= 100`
- `[input]` integer `r`
The number of rows.
`0 < r <= 100`
- `[input]` integer `c`
The number of columns.
`0 < c <= 100`
- `[input]` integer `candy`
The label of the candy Nam wants to get position of.
`0 < c <= 120`
- `[output]` an integer array
Array of 3 elements: a label, a row and a column.
|
def get_candy_position(n, r, c, candy):
if min(n, r, c, candy)<=0 or candy>n:
return [-1]*3
box, candy = divmod(candy-1, r*c)
row, col = divmod(candy, c)
return [box+1, r-row-1, c-col-1]
|
def get_candy_position(n, r, c, candy):
if min(n, r, c, candy)<=0 or candy>n:
return [-1]*3
box, candy = divmod(candy-1, r*c)
row, col = divmod(candy, c)
return [box+1, r-row-1, c-col-1]
|
train
|
APPS_structured
|
Given the array favoriteCompanies where favoriteCompanies[i] is the list of favorites companies for the ith person (indexed from 0).
Return the indices of people whose list of favorite companies is not a subset of any other list of favorites companies. You must return the indices in increasing order.
Example 1:
Input: favoriteCompanies = [["leetcode","google","facebook"],["google","microsoft"],["google","facebook"],["google"],["amazon"]]
Output: [0,1,4]
Explanation:
Person with index=2 has favoriteCompanies[2]=["google","facebook"] which is a subset of favoriteCompanies[0]=["leetcode","google","facebook"] corresponding to the person with index 0.
Person with index=3 has favoriteCompanies[3]=["google"] which is a subset of favoriteCompanies[0]=["leetcode","google","facebook"] and favoriteCompanies[1]=["google","microsoft"].
Other lists of favorite companies are not a subset of another list, therefore, the answer is [0,1,4].
Example 2:
Input: favoriteCompanies = [["leetcode","google","facebook"],["leetcode","amazon"],["facebook","google"]]
Output: [0,1]
Explanation: In this case favoriteCompanies[2]=["facebook","google"] is a subset of favoriteCompanies[0]=["leetcode","google","facebook"], therefore, the answer is [0,1].
Example 3:
Input: favoriteCompanies = [["leetcode"],["google"],["facebook"],["amazon"]]
Output: [0,1,2,3]
Constraints:
1 <= favoriteCompanies.length <= 100
1 <= favoriteCompanies[i].length <= 500
1 <= favoriteCompanies[i][j].length <= 20
All strings in favoriteCompanies[i] are distinct.
All lists of favorite companies are distinct, that is, If we sort alphabetically each list then favoriteCompanies[i] != favoriteCompanies[j].
All strings consist of lowercase English letters only.
|
class Solution:
def peopleIndexes(self, favoriteCompanies: List[List[str]]) -> List[int]:
length = len(favoriteCompanies)
for i in range(length):
favoriteCompanies[i] = set(favoriteCompanies[i])
res = []
for i in range(length):
pattern = favoriteCompanies[i]
for flist in favoriteCompanies:
if pattern < flist: break
else:
res.append(i)
return res
|
class Solution:
def peopleIndexes(self, favoriteCompanies: List[List[str]]) -> List[int]:
length = len(favoriteCompanies)
for i in range(length):
favoriteCompanies[i] = set(favoriteCompanies[i])
res = []
for i in range(length):
pattern = favoriteCompanies[i]
for flist in favoriteCompanies:
if pattern < flist: break
else:
res.append(i)
return res
|
train
|
APPS_structured
|
Snakeland is a well organised city. The houses of the city are organised in an orderly rectangular fashion with dimensions 2 * n, i.e. there are total two rows and n columns. The house in the i-th row and j-th column is also said to be the house at coordinates (i, j). Some of the houses are occupied by snakes, while the others are empty. You are given this information through an array s of dimension 2 * n, where, if s[i][j] = '*', it denotes that there is a snake in the house at coordinates (i, j), and if s[i][j] = '.', it denotes that the house is empty.
These snakes are planning a coup against a mongoose who controls their city from outside. So, they are trying their best to meet with other snakes and spread information about the date of the coup. For spreading this information, they can just hiss from their house and usually their hiss is so loud that it will be heard in all the cells except if there is a soundproof fence built that cuts the voice. Note that the external borders of Snakeland are already built of soundproof material. The mongoose got to know about the plan, and he wants to construct sound proof fences along the borders of the houses so that no two people should be able to communicate with each other. The fence can be either vertical or horizontal. Each fence can be of any length, but the mongoose wants to minimize the number of fences to be built. Find out the minimum number of fences that the mongoose should build.
-----Input-----
The first line of the input contains an integer T denoting number of test cases. The descriptions of the T test cases follow.
The first line of each test case contains a single integer, n.
Each of the next two lines contains n characters denoting the first and the second rows of Snakeland respectively.
-----Output-----
For each test case, output a single integer corresponding to the minimum number of fences that the mongoose needs to build.
-----Constraints-----
- 1 ≤ T ≤ 10
- 1 ≤ n ≤ 105
-----Example-----
Input
3
2
**
**
3
***
*..
3
*..
.*.
Output
2
3
1
-----Explanation-----
All the examples are shown in the pictures. The fences built are shown by red colored horizontal or vertical segments. You can see that after putting these borders no snake can talk with any another snake.
|
# cook your dish here
t=int(input())
while t:
n=int(input())
r1=input()
r2=input()
r1count=0
r2count=0
count=0
for i in range(n):
if(r1[i]=="*"):
r1count+=1
if(r2[i]=="*"):
r2count+=1
if(r1count>0) and (r2count>0):
count=1
r1count=0
r2count=0
i=0
while(i<n):
if(r1[i]=="*"):
r1count+=1
if(r2[i]=="*"):
r2count+=1
if(r1count>1) or (r2count>1):
count+=1
r1count=0
r2count=0
i-=1
i+=1
elif(r1count==0 and r2count>0) or (r2count==0 and r1count>0):
count=max(r1count,r2count)-1
else:
count=0
print(count)
t-=1
|
# cook your dish here
t=int(input())
while t:
n=int(input())
r1=input()
r2=input()
r1count=0
r2count=0
count=0
for i in range(n):
if(r1[i]=="*"):
r1count+=1
if(r2[i]=="*"):
r2count+=1
if(r1count>0) and (r2count>0):
count=1
r1count=0
r2count=0
i=0
while(i<n):
if(r1[i]=="*"):
r1count+=1
if(r2[i]=="*"):
r2count+=1
if(r1count>1) or (r2count>1):
count+=1
r1count=0
r2count=0
i-=1
i+=1
elif(r1count==0 and r2count>0) or (r2count==0 and r1count>0):
count=max(r1count,r2count)-1
else:
count=0
print(count)
t-=1
|
train
|
APPS_structured
|
Mash 2 arrays together so that the returning array has alternating elements of the 2 arrays . Both arrays will always be the same length.
eg. [1,2,3] + ['a','b','c'] = [1, 'a', 2, 'b', 3, 'c']
|
def array_mash(a, b):
return [x for xs in zip(a, b) for x in xs]
|
def array_mash(a, b):
return [x for xs in zip(a, b) for x in xs]
|
train
|
APPS_structured
|
You have a rectangular chocolate bar consisting of n × m single squares. You want to eat exactly k squares, so you may need to break the chocolate bar.
In one move you can break any single rectangular piece of chocolate in two rectangular pieces. You can break only by lines between squares: horizontally or vertically. The cost of breaking is equal to square of the break length.
For example, if you have a chocolate bar consisting of 2 × 3 unit squares then you can break it horizontally and get two 1 × 3 pieces (the cost of such breaking is 3^2 = 9), or you can break it vertically in two ways and get two pieces: 2 × 1 and 2 × 2 (the cost of such breaking is 2^2 = 4).
For several given values n, m and k find the minimum total cost of breaking. You can eat exactly k squares of chocolate if after all operations of breaking there is a set of rectangular pieces of chocolate with the total size equal to k squares. The remaining n·m - k squares are not necessarily form a single rectangular piece.
-----Input-----
The first line of the input contains a single integer t (1 ≤ t ≤ 40910) — the number of values n, m and k to process.
Each of the next t lines contains three integers n, m and k (1 ≤ n, m ≤ 30, 1 ≤ k ≤ min(n·m, 50)) — the dimensions of the chocolate bar and the number of squares you want to eat respectively.
-----Output-----
For each n, m and k print the minimum total cost needed to break the chocolate bar, in order to make it possible to eat exactly k squares.
-----Examples-----
Input
4
2 2 1
2 2 3
2 2 2
2 2 4
Output
5
5
4
0
-----Note-----
In the first query of the sample one needs to perform two breaks: to split 2 × 2 bar into two pieces of 2 × 1 (cost is 2^2 = 4), to split the resulting 2 × 1 into two 1 × 1 pieces (cost is 1^2 = 1).
In the second query of the sample one wants to eat 3 unit squares. One can use exactly the same strategy as in the first query of the sample.
|
mem = [[[0 for i in range(51)] for j in range(31)] for k in range(31)]
def f(n, m, k):
if mem[n][m][k]:
return mem[n][m][k]
if (n*m == k) or (k == 0):
return 0
cost = 10**9
for x in range(1, n//2 + 1):
for z in range(k+1):
cost = min(cost, m*m + f(n-x, m, k-z) + f(x, m, z))
for y in range(1, m//2 + 1):
for z in range(k+1):
cost = min(cost, n*n + f(n, m-y, k-z) + f(n, y, z))
mem[n][m][k] = cost
return cost
t = int(input())
for i in range(t):
n, m, k = list(map(int, input().split()))
print(f(n, m, k))
|
mem = [[[0 for i in range(51)] for j in range(31)] for k in range(31)]
def f(n, m, k):
if mem[n][m][k]:
return mem[n][m][k]
if (n*m == k) or (k == 0):
return 0
cost = 10**9
for x in range(1, n//2 + 1):
for z in range(k+1):
cost = min(cost, m*m + f(n-x, m, k-z) + f(x, m, z))
for y in range(1, m//2 + 1):
for z in range(k+1):
cost = min(cost, n*n + f(n, m-y, k-z) + f(n, y, z))
mem[n][m][k] = cost
return cost
t = int(input())
for i in range(t):
n, m, k = list(map(int, input().split()))
print(f(n, m, k))
|
train
|
APPS_structured
|
These days, chef is very much interested in Mathematics. He has started attending Recitations too! His hunger for problems is increasing day by day!
Today, chef was a given a crumpled maths problem, which he is stuck with . He needs your help to do it
Here's what his teacher said: "Find sum of all numbers till N, do not include numbers which are powers of K from K, K2, K3... which are less than or equal to N"
Easy, right? Can you solve it?
-----INPUT-----
The first line of the input contains an integer T, denoting the number of test cases. The description of T test cases follows. The first line of each test contains two integers N and K, as per the above given problem specification.
-----OUTPUT-----
For each test case, output a single line printing the sum of the each test case, in format Case #T: S, where T is the Tth test case running and S is sum of corresponding test case.
-----CONSTRAINTS-----
10 < T < 50
10 < N < 104
0 < K < 100
-----EXAMPLE-----
Input:
2
10 3
20 2
Output:
Case #1: 43
Case #2: 180
|
for j in range(int(input())):
n,k = list(map(int, input().split()))
s = (n*(n+1))/2
i = k
while i<=n:
s -= i
i *= k
print("Case #%d: %d" % (j+1, s))
|
for j in range(int(input())):
n,k = list(map(int, input().split()))
s = (n*(n+1))/2
i = k
while i<=n:
s -= i
i *= k
print("Case #%d: %d" % (j+1, s))
|
train
|
APPS_structured
|
We have 3 equations with 3 unknowns x, y, and z and we are to solve for these unknowns.
Equations 4x -3y +z = -10, 2x +y +3z = 0, and -x +2y -5z = 17 will be passed in as an array of [[4, -3, 1, -10], [2, 1, 3, 0], [-1, 2, -5, 17]] and the result should be returned as an array like [1, 4, -2] (i.e. [x, y, z]).
Note: In C++ do not use new or malloc to allocate memory for the returned variable as allocated memory will not be freed in the Test Cases. Setting the variable as static will do.
|
import numpy as np
def solve_eq(eq):
[p, q, r] = eq
a = np.array([p[:-1], q[:-1], r[:-1]])
b = np.array([p[-1], q[-1], r[-1]])
return list(map(round,np.linalg.solve(a, b).tolist()))
|
import numpy as np
def solve_eq(eq):
[p, q, r] = eq
a = np.array([p[:-1], q[:-1], r[:-1]])
b = np.array([p[-1], q[-1], r[-1]])
return list(map(round,np.linalg.solve(a, b).tolist()))
|
train
|
APPS_structured
|
Polycarp is making a quest for his friends. He has already made n tasks, for each task the boy evaluated how interesting it is as an integer q_{i}, and the time t_{i} in minutes needed to complete the task.
An interesting feature of his quest is: each participant should get the task that is best suited for him, depending on his preferences. The task is chosen based on an interactive quiz that consists of some questions. The player should answer these questions with "yes" or "no". Depending on the answer to the question, the participant either moves to another question or goes to one of the tasks that are in the quest. In other words, the quest is a binary tree, its nodes contain questions and its leaves contain tasks.
We know that answering any of the questions that are asked before getting a task takes exactly one minute from the quest player. Polycarp knows that his friends are busy people and they can't participate in the quest for more than T minutes. Polycarp wants to choose some of the n tasks he made, invent the corresponding set of questions for them and use them to form an interactive quiz as a binary tree so that no matter how the player answers quiz questions, he spends at most T minutes on completing the whole quest (that is, answering all the questions and completing the task). Specifically, the quest can contain zero questions and go straight to the task. Each task can only be used once (i.e., the people who give different answers to questions should get different tasks).
Polycarp wants the total "interest" value of the tasks involved in the quest to be as large as possible. Help him determine the maximum possible total interest value of the task considering that the quest should be completed in T minutes at any variant of answering questions.
-----Input-----
The first line contains two integers n and T (1 ≤ n ≤ 1000, 1 ≤ T ≤ 100) — the number of tasks made by Polycarp and the maximum time a quest player should fit into.
Next n lines contain two integers t_{i}, q_{i} (1 ≤ t_{i} ≤ T, 1 ≤ q_{i} ≤ 1000) each — the time in minutes needed to complete the i-th task and its interest value.
-----Output-----
Print a single integer — the maximum possible total interest value of all the tasks in the quest.
-----Examples-----
Input
5 5
1 1
1 1
2 2
3 3
4 4
Output
11
Input
5 5
4 1
4 2
4 3
4 4
4 5
Output
9
Input
2 2
1 1
2 10
Output
10
-----Note-----
In the first sample test all the five tasks can be complemented with four questions and joined into one quest.
In the second sample test it is impossible to use all the five tasks, but you can take two of them, the most interesting ones.
In the third sample test the optimal strategy is to include only the second task into the quest.
Here is the picture that illustrates the answers to the sample tests. The blue circles represent the questions, the two arrows that go from every circle represent where a person goes depending on his answer to that question. The tasks are the red ovals. [Image]
|
from collections import defaultdict
def __starting_point():
n, T = [int(_) for _ in input().split()]
data = defaultdict(list)
for i in range(n):
t, q = [int(_) for _ in input().split()]
data[T - t].append(q)
prev_level = []
for level_id in range(1, T + 1):
level = sorted(data[T - level_id] + prev_level, reverse=True)
if T - level_id <= 10:
max_size = 2 ** (T - level_id)
level = level[:max_size]
if len(level) % 2 == 1:
level.append(0)
prev_level = [
level[i] + level[i + 1]
for i in range(0, len(level), 2)
]
print(prev_level[0])
__starting_point()
|
from collections import defaultdict
def __starting_point():
n, T = [int(_) for _ in input().split()]
data = defaultdict(list)
for i in range(n):
t, q = [int(_) for _ in input().split()]
data[T - t].append(q)
prev_level = []
for level_id in range(1, T + 1):
level = sorted(data[T - level_id] + prev_level, reverse=True)
if T - level_id <= 10:
max_size = 2 ** (T - level_id)
level = level[:max_size]
if len(level) % 2 == 1:
level.append(0)
prev_level = [
level[i] + level[i + 1]
for i in range(0, len(level), 2)
]
print(prev_level[0])
__starting_point()
|
train
|
APPS_structured
|
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
|
import sys
from collections import defaultdict
def fin(): return sys.stdin.readline().strip()
def fout(s, end="\n"): sys.stdout.write(str(s)+end)
t = int(input())
while t>0:
t -= 1
n, k = list(map(int, fin().split()))
a = [int(x) for x in fin().split()]
freq = defaultdict(int)
freq[a[0]] += 1
temp = set([a[0]])
ans = 1
prev = 0
for i in range(1, n):
freq[a[i]] += 1
temp.add(a[i])
if len(temp) < k:
ans = max(ans, i-prev+1)
else:
while len(temp) >= k:
freq[a[prev]] -= 1
if freq[a[prev]] == 0:
temp.remove(a[prev])
prev += 1
print(ans)
|
import sys
from collections import defaultdict
def fin(): return sys.stdin.readline().strip()
def fout(s, end="\n"): sys.stdout.write(str(s)+end)
t = int(input())
while t>0:
t -= 1
n, k = list(map(int, fin().split()))
a = [int(x) for x in fin().split()]
freq = defaultdict(int)
freq[a[0]] += 1
temp = set([a[0]])
ans = 1
prev = 0
for i in range(1, n):
freq[a[i]] += 1
temp.add(a[i])
if len(temp) < k:
ans = max(ans, i-prev+1)
else:
while len(temp) >= k:
freq[a[prev]] -= 1
if freq[a[prev]] == 0:
temp.remove(a[prev])
prev += 1
print(ans)
|
train
|
APPS_structured
|
The Mormons are trying to find new followers and in order to do that they embark on missions.
Each time they go on a mission, every Mormons converts a fixed number of people (reach) into followers. This continues and every freshly converted Mormon as well as every original Mormon go on another mission and convert the same fixed number of people each. The process continues until they reach a predefined target number of followers (input into the model).
Converted Mormons are unique so that there's no duplication amongst them.
Create a function Mormons(startingNumber, reach, target) that calculates how many missions Mormons need to embark on, in order to reach their target. While each correct solution will pass, for more fun try to make a recursive function.
All model inputs are valid positive integers.
|
mormons=lambda a,r,t,m=0:m if a>=t else mormons(a*(r+1),r,t,m+1)
|
mormons=lambda a,r,t,m=0:m if a>=t else mormons(a*(r+1),r,t,m+1)
|
train
|
APPS_structured
|
Given a non-negative integer, return an array / a list of the individual digits in order.
Examples:
```
123 => [1,2,3]
1 => [1]
8675309 => [8,6,7,5,3,0,9]
```
|
def digitize(n):
return [int(n) for n in str(n)]
|
def digitize(n):
return [int(n) for n in str(n)]
|
train
|
APPS_structured
|
Define a "prime prime" number to be a rational number written as one prime number over another prime number: `primeA / primeB` (e.g. `7/31`)
Given a whole number `N`, generate the number of "prime prime" rational numbers less than 1, using only prime numbers between `0` and `N` (non inclusive).
Return the count of these "prime primes", and the integer part of their sum.
## Example
```python
N = 6
# The "prime primes" less than 1 are:
2/3, 2/5, 3/5 # count: 3
2/3 + 2/5 + 3/5 = 1.6667 # integer part: 1
Thus, the function should return 3 and 1.
```
|
def prime_primes(n):
sieve = [0, 0] + [1] * (n - 2)
for k in range(2, int(n ** .5) + 1):
if sieve[k]: sieve[k*k::k] = ((n-k*k-1) // k + 1) * [0]
primes = [p for p, b in enumerate(sieve) if b]
ratios = [b / a for i, a in enumerate(primes) for b in primes[:i]]
return len(ratios), int(sum(ratios))
|
def prime_primes(n):
sieve = [0, 0] + [1] * (n - 2)
for k in range(2, int(n ** .5) + 1):
if sieve[k]: sieve[k*k::k] = ((n-k*k-1) // k + 1) * [0]
primes = [p for p, b in enumerate(sieve) if b]
ratios = [b / a for i, a in enumerate(primes) for b in primes[:i]]
return len(ratios), int(sum(ratios))
|
train
|
APPS_structured
|
A tourist is visiting Byteland. The tourist knows English very well. The language of Byteland is rather different from English. To be exact it differs in following points:
- Bytelandian alphabet has the same letters as English one, but possibly different in meaning. Like 'A' in Bytelandian may be 'M' in English. However this does not mean that 'M' in Bytelandian must be 'A' in English. More formally, Bytelindian alphabet is a permutation of English alphabet. It will be given to you and could be any possible permutation. Don't assume any other condition.
- People of Byteland don't like to use invisible character for separating words. Hence instead of space (' ') they use underscore ('_'). Other punctuation symbols, like '?', '!' remain the same as in English.
The tourist is carrying "The dummies guide to Bytelandian", for translation. The book is serving his purpose nicely. But he is addicted to sharing on BaceFook, and shares his numerous conversations in Byteland on it. The conversations are rather long, and it is quite tedious to translate for his English friends, so he asks you to help him by writing a program to do the same.
-----Input-----
The first line of the input contains an integer T, denoting the length of the conversation, and the string M, denoting the English translation of Bytelandian string "abcdefghijklmnopqrstuvwxyz". T and M are separated by exactly one space. Then T lines follow, each containing a Bytelandian sentence S which you should translate into English. See constraints for details.
-----Output-----
For each of the sentence in the input, output its English translation on a separate line. Replace each underscores ('_') with a space (' ') in the output. Each punctuation symbol (see below) should remain the same. Note that the uppercase letters in Bytelandian remain uppercase in English, and lowercase letters remain lowercase. See the example and its explanation for clarity.
-----Constraints-----
- 1 ≤ T ≤ 100
- M is a permutation of "abcdefghijklmnopqrstuvwxyz"
- Each sentence is non-empty and contains at most 100 characters
- Each sentence may contain only lowercase letters ('a'-'z'), uppercase letters ('A'-'Z'), underscores ('_') and punctuation symbols: dot ('.'), comma (','), exclamation ('!'), question-mark('?')
-----Example-----
Input:
5 qwertyuiopasdfghjklzxcvbnm
Ph
Pcssi
Bpke_kdc_epclc_jcijsc_mihyo?
Epcf_kdc_liswhyo_EIED_hy_Vimcvpcn_Zkdvp_siyo_viyecle.
Ipp!
Output:
Hi
Hello
What are these people doing?
They are solving TOTR in Codechef March long contest.
Ohh!
-----Explanation-----
The string "qwertyuiopasdfghjklzxcvbnm" means that 'a' in Bytelandian is 'q' in English, 'b' in Bytelandian is 'w' in English, 'c' in Bytelandian is 'e' in English and so on.
Thus to translate "Ph" (first sentence in example) to English:
1) We find that 'p' in Bytelandian means 'h' in English. So we replace 'P' with 'H'.
2) Then we see that 'h' in Bytelandian means 'i' in English. So we replace 'h' with 'i'.
3) Therefore, the translation is "Hi".
|
try:
t,m=input().split()
t=int(t)
m=list(m)
letters=list("abcdefghijklmnopqrstuvwxyz")
trans={}
for i in range(len(letters)):
trans[letters[i]]=m[i]
for i in range(t):
x=list(input())
y=""
for j in x:
if(j.isalpha()==True):
if(j.isupper()==True):
y+=trans[j.lower()].upper()
else:
y+=trans[j]
else:
if(j=='_'):
y+=" "
else:
y+=j
print(y)
except:pass
|
try:
t,m=input().split()
t=int(t)
m=list(m)
letters=list("abcdefghijklmnopqrstuvwxyz")
trans={}
for i in range(len(letters)):
trans[letters[i]]=m[i]
for i in range(t):
x=list(input())
y=""
for j in x:
if(j.isalpha()==True):
if(j.isupper()==True):
y+=trans[j.lower()].upper()
else:
y+=trans[j]
else:
if(j=='_'):
y+=" "
else:
y+=j
print(y)
except:pass
|
train
|
APPS_structured
|
Santa has to send presents to the kids. He has a large stack of $n$ presents, numbered from $1$ to $n$; the topmost present has number $a_1$, the next present is $a_2$, and so on; the bottom present has number $a_n$. All numbers are distinct.
Santa has a list of $m$ distinct presents he has to send: $b_1$, $b_2$, ..., $b_m$. He will send them in the order they appear in the list.
To send a present, Santa has to find it in the stack by removing all presents above it, taking this present and returning all removed presents on top of the stack. So, if there are $k$ presents above the present Santa wants to send, it takes him $2k + 1$ seconds to do it. Fortunately, Santa can speed the whole process up — when he returns the presents to the stack, he may reorder them as he wishes (only those which were above the present he wanted to take; the presents below cannot be affected in any way).
What is the minimum time required to send all of the presents, provided that Santa knows the whole list of presents he has to send and reorders the presents optimally? Santa cannot change the order of presents or interact with the stack of presents in any other way.
Your program has to answer $t$ different test cases.
-----Input-----
The first line contains one integer $t$ ($1 \le t \le 100$) — the number of test cases.
Then the test cases follow, each represented by three lines.
The first line contains two integers $n$ and $m$ ($1 \le m \le n \le 10^5$) — the number of presents in the stack and the number of presents Santa wants to send, respectively.
The second line contains $n$ integers $a_1$, $a_2$, ..., $a_n$ ($1 \le a_i \le n$, all $a_i$ are unique) — the order of presents in the stack.
The third line contains $m$ integers $b_1$, $b_2$, ..., $b_m$ ($1 \le b_i \le n$, all $b_i$ are unique) — the ordered list of presents Santa has to send.
The sum of $n$ over all test cases does not exceed $10^5$.
-----Output-----
For each test case print one integer — the minimum number of seconds which Santa has to spend sending presents, if he reorders the presents optimally each time he returns them into the stack.
-----Example-----
Input
2
3 3
3 1 2
3 2 1
7 2
2 1 7 3 4 5 6
3 1
Output
5
8
|
import sys
input = sys.stdin.readline
t = int(input())
for _ in range(t):
n, m = map(int, input().split())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
memo = {}
for i in range(n):
memo[a[i]] = i
max_num = -1
cnt = 0
ans = 0
for i in range(m):
if max_num < memo[b[i]]:
ans += 2 * (memo[b[i]] - cnt) + 1
max_num = memo[b[i]]
cnt += 1
else:
ans += 1
cnt += 1
print(ans)
|
import sys
input = sys.stdin.readline
t = int(input())
for _ in range(t):
n, m = map(int, input().split())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
memo = {}
for i in range(n):
memo[a[i]] = i
max_num = -1
cnt = 0
ans = 0
for i in range(m):
if max_num < memo[b[i]]:
ans += 2 * (memo[b[i]] - cnt) + 1
max_num = memo[b[i]]
cnt += 1
else:
ans += 1
cnt += 1
print(ans)
|
train
|
APPS_structured
|
Your task is to calculate logical value of boolean array. Test arrays are one-dimensional and their size is in the range 1-50.
Links referring to logical operations: [AND](https://en.wikipedia.org/wiki/Logical_conjunction), [OR](https://en.wikipedia.org/wiki/Logical_disjunction) and [XOR](https://en.wikipedia.org/wiki/Exclusive_or).
You should begin at the first value, and repeatedly apply the logical operation across the remaining elements in the array sequentially.
First Example:
Input: true, true, false, operator: AND
Steps: true AND true -> true, true AND false -> false
Output: false
Second Example:
Input: true, true, false, operator: OR
Steps: true OR true -> true, true OR false -> true
Output: true
Third Example:
Input: true, true, false, operator: XOR
Steps: true XOR true -> false, false XOR false -> false
Output: false
___
Input:
boolean array, string with operator' s name: 'AND', 'OR', 'XOR'.
Output:
calculated boolean
|
from operator import and_
from operator import or_
from operator import xor
from functools import reduce
def logical_calc(array, op):
if op == "XOR":
return reduce(xor, array)
elif op == "AND":
return reduce(and_, array)
elif op == "OR":
return reduce(or_, array)
|
from operator import and_
from operator import or_
from operator import xor
from functools import reduce
def logical_calc(array, op):
if op == "XOR":
return reduce(xor, array)
elif op == "AND":
return reduce(and_, array)
elif op == "OR":
return reduce(or_, array)
|
train
|
APPS_structured
|
## 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
|
from numpy import mean
def find_average(nums):
return mean(nums) if nums else 0
|
from numpy import mean
def find_average(nums):
return mean(nums) if nums else 0
|
train
|
APPS_structured
|
The Chef has a huge square napkin of size 2n X 2n. He folds the napkin n-3 times. Each time he folds its bottom side over its top side, and then its right side over its left side. After each fold, the side length of the napkin is reduced by half. The Chef continues folding until there remains a 8x8 sheet, lying flat on a table.
Oh, did I forget to mention that the Chef was cooking a new brown colored curry while folding the napkin. He drops some brown colored gravy onto some cells in the folded 8x8 napkin. When he drops the gravy, it soaks through all the cells below it.
Now the Chef unfolds the napkin to its original size. There are now many curry stained brown colored cells in the napkin. They form several separate regions, each of which is connected. Could you help the Chef count how many regions of brown cells are there in the napkin?
Note that two cells are adjacent if they share a common edge (they are not considered adjacent if they only share a corner). Two cells are connected if we can go from one cell to the other via adjacent cells. A region is a maximal set of cells such that every two of its cells are connected.
Please see the example test case for more details.
-----Input-----
The first line contains t, the number of test cases (about 50). Then t test cases follow. Each test case has the following form:
- The first line contains N (3 ≤ N ≤ 109)
- Then, 8 lines follow. Each line is a string of 8 characters, 0 or 1, where 1 denotes a stained brown cell in the folded napkin.
-----Output-----
For each test case, print a single number that is the number of disconnected brown regions in the unfolded napkin. Since the result may be a very large number, you only need to print its remainder when dividing by 21945.
-----Example-----
Input:
3
3
01000010
11000001
00000000
00011000
00011000
00010100
00001000
00000000
4
01000010
11000001
00000000
00011000
00011000
00010100
00001000
00000000
1000000000
11111111
11111111
11111111
11111111
11111111
11111111
11111111
11111111
Output:
6
22
1
-----Output details-----
Case 1 and 2: There are 6 brown regions in the 8x8 napkin. If we unfold it once, it has 22 brown regions: 11 regions in the top half and 11 regions in the bottom half (as shown in the figure above).
Case 3: All cells of the napkin are stained, so there is always one brown region, no matter how many times the Chef unfolds the napkin.
|
import sys
t = int(sys.stdin.readline())
def identify(x, y):
rows[x][y] = '2'
r = 0
if x == 0:
r |= 1
elif rows[x-1][y] == '1':
r |= identify(x-1, y)
if x == 7:
r |= 4
elif rows[x+1][y] == '1':
r |= identify(x+1, y)
if y == 0:
r |= 2
elif rows[x][y-1] == '1':
r |= identify(x, y-1)
if y == 7:
r |= 8
elif rows[x][y+1] == '1':
r |= identify(x, y+1)
return r
P = 21945
while t:
t-=1
n = int(sys.stdin.readline())-3
rows = [list(sys.stdin.readline().strip()) for i in range(8)]
total = 0
for i in range(8):
for j in range(8):
if rows[i][j] == '1':
r = identify(i,j)
# print '\n'.join([''.join(ro) for ro in rows])
# print r
if n == 0:
total += 1
# print total
continue
if r == 0:
total += pow(2, 2*n, P)
elif r == 1 or r == 2 or r == 4 or r == 8:
total += pow(2, 2*n-1, P)
if r == 1 or r == 2:
total += pow(2, n, P)
elif r == 5 or r == 10:
total += pow(2, n, P)
elif r == 3 or r == 6 or r == 12 or r == 9:
total += pow(2, 2*n-2, P)
if r == 3:
total += 3 + 2*pow(2, n-1, P) - 2
elif r == 6 or r == 9:
total += pow(2, n-1, P)
elif r == 15:
total += 1
else:
total += pow(2, n-1, P)
if r == 11 or r == 7:
total += 1
# print total
print(total % P)
|
import sys
t = int(sys.stdin.readline())
def identify(x, y):
rows[x][y] = '2'
r = 0
if x == 0:
r |= 1
elif rows[x-1][y] == '1':
r |= identify(x-1, y)
if x == 7:
r |= 4
elif rows[x+1][y] == '1':
r |= identify(x+1, y)
if y == 0:
r |= 2
elif rows[x][y-1] == '1':
r |= identify(x, y-1)
if y == 7:
r |= 8
elif rows[x][y+1] == '1':
r |= identify(x, y+1)
return r
P = 21945
while t:
t-=1
n = int(sys.stdin.readline())-3
rows = [list(sys.stdin.readline().strip()) for i in range(8)]
total = 0
for i in range(8):
for j in range(8):
if rows[i][j] == '1':
r = identify(i,j)
# print '\n'.join([''.join(ro) for ro in rows])
# print r
if n == 0:
total += 1
# print total
continue
if r == 0:
total += pow(2, 2*n, P)
elif r == 1 or r == 2 or r == 4 or r == 8:
total += pow(2, 2*n-1, P)
if r == 1 or r == 2:
total += pow(2, n, P)
elif r == 5 or r == 10:
total += pow(2, n, P)
elif r == 3 or r == 6 or r == 12 or r == 9:
total += pow(2, 2*n-2, P)
if r == 3:
total += 3 + 2*pow(2, n-1, P) - 2
elif r == 6 or r == 9:
total += pow(2, n-1, P)
elif r == 15:
total += 1
else:
total += pow(2, n-1, P)
if r == 11 or r == 7:
total += 1
# print total
print(total % P)
|
train
|
APPS_structured
|
Complete the function that determines the score of a hand in the card game [Blackjack](https://en.wikipedia.org/wiki/Blackjack) (aka 21).
The function receives an array of strings that represent each card in the hand (`"2"`, `"3",` ..., `"10"`, `"J"`, `"Q"`, `"K"` or `"A"`) and should return the score of the hand (integer).
~~~if:c
Note: in C the function receives a character array with the card `10` represented by the character `T`.
~~~
### Scoring rules:
Number cards count as their face value (2 through 10). Jack, Queen and King count as 10. An Ace can be counted as either 1 or 11.
Return the highest score of the cards that is less than or equal to 21. If there is no score less than or equal to 21 return the smallest score more than 21.
## Examples
```
["A"] ==> 11
["A", "J"] ==> 21
["A", "10", "A"] ==> 12
["5", "3", "7"] ==> 15
["5", "4", "3", "2", "A", "K"] ==> 25
```
|
def score_hand(cards):
aces = cards.count("A")
score = sum( int(card) if card.isdigit() else 10 for card in cards ) + aces
if score > 21:
for _ in range(aces):
score -= 10
if score <= 21:
break
return score
|
def score_hand(cards):
aces = cards.count("A")
score = sum( int(card) if card.isdigit() else 10 for card in cards ) + aces
if score > 21:
for _ in range(aces):
score -= 10
if score <= 21:
break
return score
|
train
|
APPS_structured
|
Write a function that, given a string of text (possibly with punctuation and line-breaks),
returns an array of the top-3 most occurring words, in descending order of the number of occurrences.
Assumptions:
------------
- A word is a string of letters (A to Z) optionally containing one or more apostrophes (') in ASCII. (No need to handle fancy punctuation.)
- Matches should be case-insensitive, and the words in the result should be lowercased.
- Ties may be broken arbitrarily.
- If a text contains fewer than three unique words, then either the top-2 or top-1 words should be returned, or an empty array if a text contains no words.
Examples:
------------
```
top_3_words("In a village of La Mancha, the name of which I have no desire to call to
mind, there lived not long since one of those gentlemen that keep a lance
in the lance-rack, an old buckler, a lean hack, and a greyhound for
coursing. An olla of rather more beef than mutton, a salad on most
nights, scraps on Saturdays, lentils on Fridays, and a pigeon or so extra
on Sundays, made away with three-quarters of his income.")
# => ["a", "of", "on"]
top_3_words("e e e e DDD ddd DdD: ddd ddd aa aA Aa, bb cc cC e e e")
# => ["e", "ddd", "aa"]
top_3_words(" //wont won't won't")
# => ["won't", "wont"]
```
```if:java
For java users, the calls will actually be in the form: `TopWords.top3(String s)`, expecting you to return a `List`.
```
Bonus points (not really, but just for fun):
------------
1. Avoid creating an array whose memory footprint is roughly as big as the input text.
2. Avoid sorting the entire array of unique words.
|
from string import punctuation
def top_3_words(text):
for p in punctuation:
if p != "'": text = text.replace(p, " ")
count = {}
for w in text.lower().split():
if w.strip(punctuation) == '':
pass
elif w in count.keys():
count[w] += 1
else:
count[w] = 1
lcount = [(w,c) for w,c in count.items()]
lcount.sort(key=lambda x: x[1], reverse=True)
return [x[0] for x in lcount[:3]]
|
from string import punctuation
def top_3_words(text):
for p in punctuation:
if p != "'": text = text.replace(p, " ")
count = {}
for w in text.lower().split():
if w.strip(punctuation) == '':
pass
elif w in count.keys():
count[w] += 1
else:
count[w] = 1
lcount = [(w,c) for w,c in count.items()]
lcount.sort(key=lambda x: x[1], reverse=True)
return [x[0] for x in lcount[:3]]
|
train
|
APPS_structured
|
# Task
Write a function that accepts `msg` string and returns local tops of string from the highest to the lowest.
The string's tops are from displaying the string in the below way:
```
3
p 2 4
g o q 1
b f h n r z
a c e i m s y
d j l t x
k u w
v
```
The next top is always 1 character higher than the previous one.
For the above example, the solution for the `abcdefghijklmnopqrstuvwxyz1234` input string is `3pgb`.
- When the `msg` string is empty, return an empty string.
- The input strings may be very long. Make sure your solution has good performance.
Check the test cases for more samples.
# **Note** for C++
Do not post an issue in my solution without checking if your returned string doesn't have some invisible characters. You read most probably outside of `msg` string.
|
def tops(msg):
res=''
top=1
diff=5
while top<len(msg):
res+=msg[top]
top+=diff
diff+=4
return res[::-1]
|
def tops(msg):
res=''
top=1
diff=5
while top<len(msg):
res+=msg[top]
top+=diff
diff+=4
return res[::-1]
|
train
|
APPS_structured
|
There are n beacons located at distinct positions on a number line. The i-th beacon has position a_{i} and power level b_{i}. When the i-th beacon is activated, it destroys all beacons to its left (direction of decreasing coordinates) within distance b_{i} inclusive. The beacon itself is not destroyed however. Saitama will activate the beacons one at a time from right to left. If a beacon is destroyed, it cannot be activated.
Saitama wants Genos to add a beacon strictly to the right of all the existing beacons, with any position and any power level, such that the least possible number of beacons are destroyed. Note that Genos's placement of the beacon means it will be the first beacon activated. Help Genos by finding the minimum number of beacons that could be destroyed.
-----Input-----
The first line of input contains a single integer n (1 ≤ n ≤ 100 000) — the initial number of beacons.
The i-th of next n lines contains two integers a_{i} and b_{i} (0 ≤ a_{i} ≤ 1 000 000, 1 ≤ b_{i} ≤ 1 000 000) — the position and power level of the i-th beacon respectively. No two beacons will have the same position, so a_{i} ≠ a_{j} if i ≠ j.
-----Output-----
Print a single integer — the minimum number of beacons that could be destroyed if exactly one beacon is added.
-----Examples-----
Input
4
1 9
3 1
6 1
7 4
Output
1
Input
7
1 1
2 1
3 1
4 1
5 1
6 1
7 1
Output
3
-----Note-----
For the first sample case, the minimum number of beacons destroyed is 1. One way to achieve this is to place a beacon at position 9 with power level 2.
For the second sample case, the minimum number of beacons destroyed is 3. One way to achieve this is to place a beacon at position 1337 with power level 42.
|
from array import *
n = int(input())
Becone = [list(map(int, input().split())) for i in range(n) ]
Becone.sort( key = lambda x : x[0])
dp = array('i', [0]*1000001)
if Becone[0][0] == 0 :
dp[0] = 1
Becone.pop(0)
ans = n - dp[0]
for i in range(1, 1000001) :
if not Becone :
break
if i != Becone[0][0] :
dp[i] = dp[i-1]
continue
a,b = Becone.pop(0)
if a-b <= 0 :
dp[i] = 1
else :
dp[i] = dp[i-b-1]+1
ans = min( ans, n - dp[i] )
print( ans )
|
from array import *
n = int(input())
Becone = [list(map(int, input().split())) for i in range(n) ]
Becone.sort( key = lambda x : x[0])
dp = array('i', [0]*1000001)
if Becone[0][0] == 0 :
dp[0] = 1
Becone.pop(0)
ans = n - dp[0]
for i in range(1, 1000001) :
if not Becone :
break
if i != Becone[0][0] :
dp[i] = dp[i-1]
continue
a,b = Becone.pop(0)
if a-b <= 0 :
dp[i] = 1
else :
dp[i] = dp[i-b-1]+1
ans = min( ans, n - dp[i] )
print( ans )
|
train
|
APPS_structured
|
# Description
"It's the end of trick-or-treating and we have a list/array representing how much candy each child in our group has made out with. We don't want the kids to start arguing, and using our parental intuition we know trouble is brewing as many of the children in the group have received different amounts of candy from each home.
So we want each child to have the same amount of candies, only we can't exactly take any candy away from the kids, that would be even worse. Instead we decide to give each child extra candy until they all have the same amount.
# Task
Your job is to find out how much candy each child has, and give them each additional candy until they too have as much as the child(ren) with the most candy. You also want to keep a total of how much candy you've handed out because reasons."
Your job is to give all the kids the same amount of candies as the kid with the most candies and then return the total number candies that have been given out. If there are no kids, or only one, return -1.
In the first case (look below) the most candies are given to second kid (i.e second place in list/array), 8. Because of that we will give the first kid 3 so he can have 8 and the third kid 2 and the fourth kid 4, so all kids will have 8 candies.So we end up handing out 3 + 2 + 4 = 9.
```python
candies ([5,8,6,4]) # return 9
candies ([1,2,4,6]) # return 11
candies ([1,6]) # return 5
candies ([]) # return -1
candies ([6]) # return -1 (because only one kid)
```
```cs
CandyProblem.GetMissingCandies(new [] {5, 6, 8, 4}) // return 9
CandyProblem.GetMissingCandies(new [] {1, 2, 4, 6}) // return 11
CandyProblem.GetMissingCandies(new [] { }) // return -1
CandyProblem.GetMissingCandies(new [] {1, 6}) // return 5
```
```haskell
candies [5,8,6,4] -- return 9
candies [1,2,4,6] -- return 11
candies [] -- return -1
candies [1,6] -- return 5
```
|
def candies(s):
return sum([max(s)-i for i in s]) if len(s) > 1 else -1
|
def candies(s):
return sum([max(s)-i for i in s]) if len(s) > 1 else -1
|
train
|
APPS_structured
|
As technologies develop, manufacturers are making the process of unlocking a phone as user-friendly as possible. To unlock its new phone, Arkady's pet dog Mu-mu has to bark the password once. The phone represents a password as a string of two lowercase English letters.
Mu-mu's enemy Kashtanka wants to unlock Mu-mu's phone to steal some sensible information, but it can only bark n distinct words, each of which can be represented as a string of two lowercase English letters. Kashtanka wants to bark several words (not necessarily distinct) one after another to pronounce a string containing the password as a substring. Tell if it's possible to unlock the phone in this way, or not.
-----Input-----
The first line contains two lowercase English letters — the password on the phone.
The second line contains single integer n (1 ≤ n ≤ 100) — the number of words Kashtanka knows.
The next n lines contain two lowercase English letters each, representing the words Kashtanka knows. The words are guaranteed to be distinct.
-----Output-----
Print "YES" if Kashtanka can bark several words in a line forming a string containing the password, and "NO" otherwise.
You can print each letter in arbitrary case (upper or lower).
-----Examples-----
Input
ya
4
ah
oy
to
ha
Output
YES
Input
hp
2
ht
tp
Output
NO
Input
ah
1
ha
Output
YES
-----Note-----
In the first example the password is "ya", and Kashtanka can bark "oy" and then "ah", and then "ha" to form the string "oyahha" which contains the password. So, the answer is "YES".
In the second example Kashtanka can't produce a string containing password as a substring. Note that it can bark "ht" and then "tp" producing "http", but it doesn't contain the password "hp" as a substring.
In the third example the string "hahahaha" contains "ah" as a substring.
|
s = input()
n = int(input())
data = []
for i in range(n):
data.append(input())
mark = 0
for i in range(n):
for j in range(n):
if s in (data[i] + data[j]):
mark = 1
if mark:
print("YES")
else:
print("NO")
|
s = input()
n = int(input())
data = []
for i in range(n):
data.append(input())
mark = 0
for i in range(n):
for j in range(n):
if s in (data[i] + data[j]):
mark = 1
if mark:
print("YES")
else:
print("NO")
|
train
|
APPS_structured
|
### The Story:
Bob is working as a bus driver. However, he has become extremely popular amongst the city's residents. With so many passengers wanting to get aboard his bus, he sometimes has to face the problem of not enough space left on the bus! He wants you to write a simple program telling him if he will be able to fit all the passengers.
### Task Overview:
You have to write a function that accepts three parameters:
* `cap` is the amount of people the bus can hold excluding the driver.
* `on` is the number of people on the bus.
* `wait` is the number of people waiting to get on to the bus.
If there is enough space, return 0, and if there isn't, return the number of passengers he can't take.
### Usage Examples:
```python
enough(10, 5, 5)
0 # He can fit all 5 passengers
enough(100, 60, 50)
10 # He can't fit 10 out of 50 waiting
```
```if:csharp
Documentation:
Kata.Enough Method (Int32, Int32, Int32)
Returns the number of passengers the bus cannot fit, or 0 if the bus can fit every passenger.
Syntax
public
static
int Enough(
int cap,
int on,
int wait
)
Parameters
cap
Type: System.Int32
The amount of people that can fit on the bus excluding the driver.
on
Type: System.Int32
The amount of people on the bus excluding the driver.
wait
Type: System.Int32
The amount of people waiting to enter the bus.
Return Value
Type: System.Int32
An integer representing how many passengers cannot fit on the bus, or 0 if every passenger can fit on the bus.
```
|
def enough(cap, on, wait):
if cap - on >= wait: #capacity minus bus occupancy more or equal than of people waiting
return 0 #If there is enough space, return 0.
else:
return abs(cap - (on + wait)) #and if there isn't, return the number of passengers he can't take
#abs() function: return absolute values of a num.
|
def enough(cap, on, wait):
if cap - on >= wait: #capacity minus bus occupancy more or equal than of people waiting
return 0 #If there is enough space, return 0.
else:
return abs(cap - (on + wait)) #and if there isn't, return the number of passengers he can't take
#abs() function: return absolute values of a num.
|
train
|
APPS_structured
|
Given an unsorted array return whether an increasing subsequence of length 3 exists or not in the array.
Formally the function should:
Return true if there exists i, j, k
such that arr[i] < arr[j] < arr[k] given 0 ≤ i < j < k ≤ n-1
else return false.
Your algorithm should run in O(n) time complexity and O(1) space complexity.
Examples:
Given [1, 2, 3, 4, 5],
return true.
Given [5, 4, 3, 2, 1],
return false.
Credits:Special thanks to @DjangoUnchained for adding this problem and creating all test cases.
|
class Solution:
def increasingTriplet(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
# keep track of the two minimum elements and see if we have a element that is larger than two
if len(nums) < 3:
return False
minN = nums[0]
minSecond = None
for i in range(1, len(nums)):
if type(minSecond) == int and nums[i] > minSecond:
return True
if minN < nums[i]:
if type(minSecond) == int and minSecond > nums[i]:
minSecond = nums[i]
elif not type(minSecond) == int:
minSecond = nums[i]
minN = min(minN, nums[i])
return False
|
class Solution:
def increasingTriplet(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
# keep track of the two minimum elements and see if we have a element that is larger than two
if len(nums) < 3:
return False
minN = nums[0]
minSecond = None
for i in range(1, len(nums)):
if type(minSecond) == int and nums[i] > minSecond:
return True
if minN < nums[i]:
if type(minSecond) == int and minSecond > nums[i]:
minSecond = nums[i]
elif not type(minSecond) == int:
minSecond = nums[i]
minN = min(minN, nums[i])
return False
|
train
|
APPS_structured
|
In Ciel's restaurant, a waiter is training.
Since the waiter isn't good at arithmetic, sometimes he gives guests wrong change.
Ciel gives him a simple problem.
What is A-B (A minus B) ?
Surprisingly, his answer is wrong.
To be more precise, his answer has exactly one wrong digit.
Can you imagine this?
Can you make the same mistake in this problem?
-----Input-----
An input contains 2 integers A and B.
-----Output-----
Print a wrong answer of A-B.
Your answer must be a positive integer containing the same number of digits as the correct answer, and exactly one digit must differ from the correct answer.
Leading zeros are not allowed.
If there are multiple answers satisfying the above conditions, anyone will do.
-----Constraints-----
1 ≤ B < A ≤ 10000
-----Sample Input-----
5858 1234
-----Sample Output-----
1624
-----Output details-----
The correct answer of 5858-1234 is 4624.
So, for instance, 2624, 4324, 4623, 4604 and 4629 will be accepted, but 0624, 624, 5858, 4624 and 04624 will be rejected.
-----Notes-----
The problem setter is also not good at arithmetic.
|
a, b = [int(x) for x in input().split()]
r = list(str(a-b))
if r[0] == "1":
r[0] = "2"
else:
r[0]="1"
print("".join(r))
|
a, b = [int(x) for x in input().split()]
r = list(str(a-b))
if r[0] == "1":
r[0] = "2"
else:
r[0]="1"
print("".join(r))
|
train
|
APPS_structured
|
# Introduction
The first century spans from the **year 1** *up to* and **including the year 100**, **The second** - *from the year 101 up to and including the year 200*, etc.
# Task :
Given a year, return the century it is in.
|
def century(year):
return year // 100 + 1 if year % 100 else year // 100
|
def century(year):
return year // 100 + 1 if year % 100 else year // 100
|
train
|
APPS_structured
|
Note : Issues Fixed with python 2.7.6 , Use any one you like :D , ( Thanks to
Time , time , time . Your task is to write a function that will return the degrees on a analog clock from a digital time that is passed in as parameter . The digital time is type string and will be in the format 00:00 . You also need to return the degrees on the analog clock in type string and format 360:360 . Remember to round of the degrees . Remeber the basic time rules and format like 24:00 = 00:00 and 12:60 = 13:00 . Create your own validation that should return "Check your time !" in any case the time is incorrect or the format is wrong , remember this includes passing in negatives times like "-01:-10".
```
A few examples :
clock_degree("00:00") will return : "360:360"
clock_degree("01:01") will return : "30:6"
clock_degree("00:01") will return : "360:6"
clock_degree("01:00") will return : "30:360"
clock_degree("01:30") will return : "30:180"
clock_degree("24:00") will return : "Check your time !"
clock_degree("13:60") will return : "Check your time !"
clock_degree("20:34") will return : "240:204"
```
Remember that discrete hour hand movement is required - snapping to each hour position and also coterminal angles are not allowed. Goodluck and Enjoy !
|
def clock_degree(stg):
try:
h, m = (int(n) for n in stg.split(":"))
if not (0 <= h < 24 and 0 <= m < 60):
raise ValueError
except ValueError:
return "Check your time !"
return f"{((h % 12) or 12)* 30}:{(m or 60) * 6}"
|
def clock_degree(stg):
try:
h, m = (int(n) for n in stg.split(":"))
if not (0 <= h < 24 and 0 <= m < 60):
raise ValueError
except ValueError:
return "Check your time !"
return f"{((h % 12) or 12)* 30}:{(m or 60) * 6}"
|
train
|
APPS_structured
|
Rick and Morty are playing their own version of Berzerk (which has nothing in common with the famous Berzerk game). This game needs a huge space, so they play it with a computer.
In this game there are n objects numbered from 1 to n arranged in a circle (in clockwise order). Object number 1 is a black hole and the others are planets. There's a monster in one of the planet. Rick and Morty don't know on which one yet, only that he's not initially in the black hole, but Unity will inform them before the game starts. But for now, they want to be prepared for every possible scenario. [Image]
Each one of them has a set of numbers between 1 and n - 1 (inclusive). Rick's set is s_1 with k_1 elements and Morty's is s_2 with k_2 elements. One of them goes first and the player changes alternatively. In each player's turn, he should choose an arbitrary number like x from his set and the monster will move to his x-th next object from its current position (clockwise). If after his move the monster gets to the black hole he wins.
Your task is that for each of monster's initial positions and who plays first determine if the starter wins, loses, or the game will stuck in an infinite loop. In case when player can lose or make game infinity, it more profitable to choose infinity game.
-----Input-----
The first line of input contains a single integer n (2 ≤ n ≤ 7000) — number of objects in game.
The second line contains integer k_1 followed by k_1 distinct integers s_{1, 1}, s_{1, 2}, ..., s_{1, }k_1 — Rick's set.
The third line contains integer k_2 followed by k_2 distinct integers s_{2, 1}, s_{2, 2}, ..., s_{2, }k_2 — Morty's set
1 ≤ k_{i} ≤ n - 1 and 1 ≤ s_{i}, 1, s_{i}, 2, ..., s_{i}, k_{i} ≤ n - 1 for 1 ≤ i ≤ 2.
-----Output-----
In the first line print n - 1 words separated by spaces where i-th word is "Win" (without quotations) if in the scenario that Rick plays first and monster is initially in object number i + 1 he wins, "Lose" if he loses and "Loop" if the game will never end.
Similarly, in the second line print n - 1 words separated by spaces where i-th word is "Win" (without quotations) if in the scenario that Morty plays first and monster is initially in object number i + 1 he wins, "Lose" if he loses and "Loop" if the game will never end.
-----Examples-----
Input
5
2 3 2
3 1 2 3
Output
Lose Win Win Loop
Loop Win Win Win
Input
8
4 6 2 3 4
2 3 6
Output
Win Win Win Win Win Win Win
Lose Win Lose Lose Win Lose Lose
|
class T:
h = ('Lose', 'Loop', 'Win')
def __init__(t):
t.s = list(map(int, input().split()))[1:]
t.p = [len(t.s)] * n
t.p[0] = 0
def f(t, i):
for d in t.s:
j = (i - d) % n
if t.p[j] > 0: yield j
def g(t):
print(*[t.h[min(q, 1)] for q in t.p[1:]])
n = int(input())
r, m = T(), T()
q = [(r, m, 0), (m, r, 0)]
while q:
x, y, i = q.pop()
for j in y.f(i):
y.p[j] = -1
for k in x.f(j):
x.p[k] -= 1
if not x.p[k]: q.append((x, y, k))
r.g()
m.g()
|
class T:
h = ('Lose', 'Loop', 'Win')
def __init__(t):
t.s = list(map(int, input().split()))[1:]
t.p = [len(t.s)] * n
t.p[0] = 0
def f(t, i):
for d in t.s:
j = (i - d) % n
if t.p[j] > 0: yield j
def g(t):
print(*[t.h[min(q, 1)] for q in t.p[1:]])
n = int(input())
r, m = T(), T()
q = [(r, m, 0), (m, r, 0)]
while q:
x, y, i = q.pop()
for j in y.f(i):
y.p[j] = -1
for k in x.f(j):
x.p[k] -= 1
if not x.p[k]: q.append((x, y, k))
r.g()
m.g()
|
train
|
APPS_structured
|
-----Problem Statement-----
Chef studies combinatorics. He tries to group objects by their rang (a positive integer associated with each object). He also gives the formula for calculating the number of different objects with rang N as following:
the number of different objects with rang N = F(N) = A0 + A1 * N + A2 * N2 + A3 * N3.
Now Chef wants to know how many different multisets of these objects exist such that sum of rangs of the objects in the multiset equals to S. You are given the coefficients in F(N) and the target sum S. Please, find the number of different multisets modulo 1,000,000,007.
You should consider a multiset as an unordered sequence of integers. Two multisets are different if and only if there at least exists one element which occurs X times in the first multiset but Y times in the second one, where (X ≠ Y).
-----Input-----
The first line of the input contains an integer T denoting the number of test cases. The description of T test cases follows.
The first line of each test case contains four integers A0, A1, A2, A3. The second line contains an integer S.
-----Output-----
For each test case, output a single line containing a single integer - the answer to the test case modulo 1,000,000,007.
-----Constraints-----
- 1 ≤ T ≤ 500
- 1 ≤ S ≤ 100
- 0 ≤ Ai ≤ 1000
- Sum of all S for all test cases is not greater than 500. It's guaranteed that at least one Ai is non-zero.
-----Example-----
Input:
4
1 0 0 0
1
1 0 0 0
3
0 1 0 0
2
2 3 1 4
10
Output:
1
3
3
213986343
-----Explanation-----
Example case 2.
In the second example function looks as follows F(N) = 1. So for each rang there is a single object of the rang. To get multiset with sum of rangs equal to 3, you can pick: three objects of rang 1, or one object of rang 1 and one of rang 2, or only one object of rang 3.
Example case 3.
In the third example function looks as follows F(N) = N. So, you have one distinct object of rang 1, two distinct objects of rang 2, three distinct objects of rang 3 and so on. To get
multiset with sum of rangs equal to 2, you can pick: two objects of rang 1, one of objects of rang 2 (two ways).
|
# cook your dish here
import sys
mod_val = 1000000007
rang = [0]*101
pow_cache = [0]*102
multisets = {}
def mod_pow(base, pow):
result = 1
while pow:
if pow&1:
result = (result*base) % mod_val
base = (base*base) % mod_val
pow = pow>>1
return result
def precalculate():
for i in range(1, 102):
pow_cache[i] = mod_pow(i, mod_val-2)
def cal_recurse(i, target_sum):
if target_sum == 0:
return 1
if i>=target_sum:
return 0
if (i, target_sum) in multisets:
return multisets[(i, target_sum)]
ans = cal_recurse(i+1, target_sum)
max_pos = target_sum//(i+1)
choose = rang[i+1]%mod_val
for j in range(1, max_pos+1):
temp = choose*cal_recurse(i+1, target_sum-j*(i+1))
# temp%=mod_val
ans += temp
ans %= mod_val
choose *= rang[i+1]+j
# choose %= mod_val
choose *= pow_cache[j+1]
choose %= mod_val
multisets[i, target_sum] = ans
return ans
def calculate(target_sum, rang_index):
populate(target_sum, rang_index)
return cal_recurse(0, target_sum)
def populate(target_sum, rang_i):
for i in range(1, target_sum+1):
rang[i] = rang_i[0] + (rang_i[1] + (rang_i[2] + rang_i[3]*i)*i)*i
_test_cases = int(input())
precalculate()
for _a_case in range(_test_cases):
rang = [0]*101
multisets = {}
_rang_index = [int(i) for i in input().split(' ')]
_target_sum = int(input())
print(calculate(_target_sum, _rang_index))
|
# cook your dish here
import sys
mod_val = 1000000007
rang = [0]*101
pow_cache = [0]*102
multisets = {}
def mod_pow(base, pow):
result = 1
while pow:
if pow&1:
result = (result*base) % mod_val
base = (base*base) % mod_val
pow = pow>>1
return result
def precalculate():
for i in range(1, 102):
pow_cache[i] = mod_pow(i, mod_val-2)
def cal_recurse(i, target_sum):
if target_sum == 0:
return 1
if i>=target_sum:
return 0
if (i, target_sum) in multisets:
return multisets[(i, target_sum)]
ans = cal_recurse(i+1, target_sum)
max_pos = target_sum//(i+1)
choose = rang[i+1]%mod_val
for j in range(1, max_pos+1):
temp = choose*cal_recurse(i+1, target_sum-j*(i+1))
# temp%=mod_val
ans += temp
ans %= mod_val
choose *= rang[i+1]+j
# choose %= mod_val
choose *= pow_cache[j+1]
choose %= mod_val
multisets[i, target_sum] = ans
return ans
def calculate(target_sum, rang_index):
populate(target_sum, rang_index)
return cal_recurse(0, target_sum)
def populate(target_sum, rang_i):
for i in range(1, target_sum+1):
rang[i] = rang_i[0] + (rang_i[1] + (rang_i[2] + rang_i[3]*i)*i)*i
_test_cases = int(input())
precalculate()
for _a_case in range(_test_cases):
rang = [0]*101
multisets = {}
_rang_index = [int(i) for i in input().split(' ')]
_target_sum = int(input())
print(calculate(_target_sum, _rang_index))
|
train
|
APPS_structured
|
Given an array of non-negative integers, you are initially positioned at the first index of the array.
Each element in the array represents your maximum jump length at that position.
Your goal is to reach the last index in the minimum number of jumps.
Example:
Input: [2,3,1,1,4]
Output: 2
Explanation: The minimum number of jumps to reach the last index is 2.
Jump 1 step from index 0 to 1, then 3 steps to the last index.
Note:
You can assume that you can always reach the last index.
|
class Solution:
def jump(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if not nums:
return 0
dic = {}
length = len(nums)
dic[length - 1] = 0
for j in range(length - 1)[::-1]:
#print(length - j + 1)
if(nums[j] >= nums[j + 1] + 1 and not j + 1 == length - 1):
minstep = dic[j + 1] - 1
for k in range(max(3, nums[j+1] + 2) ,min(length - j , nums[j] + 1)):
#print(j,k)
if dic[j + k] < minstep:
minstep = dic[j + k]
dic[j] = minstep + 1
continue
minstep = dic[j + 1]
for k in range(2,min(length - j , nums[j] + 1)):
#print(j,k)
if dic[j + k] < minstep:
minstep = dic[j + k]
dic[j] = minstep + 1
#print(dic)
return dic[0]
|
class Solution:
def jump(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if not nums:
return 0
dic = {}
length = len(nums)
dic[length - 1] = 0
for j in range(length - 1)[::-1]:
#print(length - j + 1)
if(nums[j] >= nums[j + 1] + 1 and not j + 1 == length - 1):
minstep = dic[j + 1] - 1
for k in range(max(3, nums[j+1] + 2) ,min(length - j , nums[j] + 1)):
#print(j,k)
if dic[j + k] < minstep:
minstep = dic[j + k]
dic[j] = minstep + 1
continue
minstep = dic[j + 1]
for k in range(2,min(length - j , nums[j] + 1)):
#print(j,k)
if dic[j + k] < minstep:
minstep = dic[j + k]
dic[j] = minstep + 1
#print(dic)
return dic[0]
|
train
|
APPS_structured
|
Say you have an array for which the ith element is the price of a given stock on day i.
Design an algorithm to find the maximum profit. You may complete as many transactions as you like (i.e., buy one and sell one share of the stock multiple times).
Note: You may not engage in multiple transactions at the same time (i.e., you must sell the stock before you buy again).
Example 1:
Input: [7,1,5,3,6,4]
Output: 7
Explanation: Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4.
Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3.
Example 2:
Input: [1,2,3,4,5]
Output: 4
Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4.
Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are
engaging multiple transactions at the same time. You must sell before buying again.
Example 3:
Input: [7,6,4,3,1]
Output: 0
Explanation: In this case, no transaction is done, i.e. max profit = 0.
|
class Solution:
def maxProfit(self, prices):
maxprofit = 0
for i in range(1,len(prices)):
if prices[i] > prices[i-1]:
maxprofit += prices[i] - prices[i-1]
return maxprofit
|
class Solution:
def maxProfit(self, prices):
maxprofit = 0
for i in range(1,len(prices)):
if prices[i] > prices[i-1]:
maxprofit += prices[i] - prices[i-1]
return maxprofit
|
train
|
APPS_structured
|
The new "Avengers" movie has just been released! There are a lot of people at the cinema box office standing in a huge line. Each of them has a single `100`, `50` or `25` dollar bill. An "Avengers" ticket costs `25 dollars`.
Vasya is currently working as a clerk. He wants to sell a ticket to every single person in this line.
Can Vasya sell a ticket to every person and give change if he initially has no money and sells the tickets strictly in the order people queue?
Return `YES`, if Vasya can sell a ticket to every person and give change with the bills he has at hand at that moment. Otherwise return `NO`.
### Examples:
```csharp
Line.Tickets(new int[] {25, 25, 50}) // => YES
Line.Tickets(new int[] {25, 100}) // => NO. Vasya will not have enough money to give change to 100 dollars
Line.Tickets(new int[] {25, 25, 50, 50, 100}) // => NO. Vasya will not have the right bills to give 75 dollars of change (you can't make two bills of 25 from one of 50)
```
```python
tickets([25, 25, 50]) # => YES
tickets([25, 100]) # => NO. Vasya will not have enough money to give change to 100 dollars
tickets([25, 25, 50, 50, 100]) # => NO. Vasya will not have the right bills to give 75 dollars of change (you can't make two bills of 25 from one of 50)
```
```cpp
tickets({25, 25, 50}) // => YES
tickets({25, 100}) // => NO. Vasya will not have enough money to give change to 100 dollars
tickets({25, 25, 50, 50, 100}) // => NO. Vasya will not have the right bills to give 75 dollars of change (you can't make two bills of 25 from one of 50)
```
|
def tickets(people):
change = {
'25': 0,
'50': 0
}
for person in people:
if person == 25:
change['25'] += 1
elif person == 50:
change['50'] += 1
change['25'] -= 1
else:
if change['50'] > 0:
change['50'] -= 1
change['25'] -= 1
else:
change['25'] -= 3
if change['25'] < 0:
return 'NO'
return 'YES'
|
def tickets(people):
change = {
'25': 0,
'50': 0
}
for person in people:
if person == 25:
change['25'] += 1
elif person == 50:
change['50'] += 1
change['25'] -= 1
else:
if change['50'] > 0:
change['50'] -= 1
change['25'] -= 1
else:
change['25'] -= 3
if change['25'] < 0:
return 'NO'
return 'YES'
|
train
|
APPS_structured
|
This problem is different from the easy version. In this version Ujan makes at most $2n$ swaps. In addition, $k \le 1000, n \le 50$ and it is necessary to print swaps themselves. You can hack this problem if you solve it. But you can hack the previous problem only if you solve both problems.
After struggling and failing many times, Ujan decided to try to clean up his house again. He decided to get his strings in order first.
Ujan has two distinct strings $s$ and $t$ of length $n$ consisting of only of lowercase English characters. He wants to make them equal. Since Ujan is lazy, he will perform the following operation at most $2n$ times: he takes two positions $i$ and $j$ ($1 \le i,j \le n$, the values $i$ and $j$ can be equal or different), and swaps the characters $s_i$ and $t_j$.
Ujan's goal is to make the strings $s$ and $t$ equal. He does not need to minimize the number of performed operations: any sequence of operations of length $2n$ or shorter is suitable.
-----Input-----
The first line contains a single integer $k$ ($1 \leq k \leq 1000$), the number of test cases.
For each of the test cases, the first line contains a single integer $n$ ($2 \leq n \leq 50$), the length of the strings $s$ and $t$.
Each of the next two lines contains the strings $s$ and $t$, each having length exactly $n$. The strings consist only of lowercase English letters. It is guaranteed that strings are different.
-----Output-----
For each test case, output "Yes" if Ujan can make the two strings equal with at most $2n$ operations and "No" otherwise. You can print each letter in any case (upper or lower).
In the case of "Yes" print $m$ ($1 \le m \le 2n$) on the next line, where $m$ is the number of swap operations to make the strings equal. Then print $m$ lines, each line should contain two integers $i, j$ ($1 \le i, j \le n$) meaning that Ujan swaps $s_i$ and $t_j$ during the corresponding operation. You do not need to minimize the number of operations. Any sequence of length not more than $2n$ is suitable.
-----Example-----
Input
4
5
souse
houhe
3
cat
dog
2
aa
az
3
abc
bca
Output
Yes
1
1 4
No
No
Yes
3
1 2
3 1
2 3
|
from bisect import *
from collections import *
from itertools import *
import functools
import sys
import math
from decimal import *
from copy import *
from heapq import *
from fractions import *
getcontext().prec = 30
MAX = sys.maxsize
MAXN = 1000010
MOD = 10**9+7
spf = [i for i in range(MAXN)]
def sieve():
for i in range(2,MAXN,2):
spf[i] = 2
for i in range(3,int(MAXN**0.5)+1):
if spf[i]==i:
for j in range(i*i,MAXN,i):
if spf[j]==j:
spf[j]=i
def fib(n,m):
if n == 0:
return [0, 1]
else:
a, b = fib(n // 2)
c = ((a%m) * ((b%m) * 2 - (a%m)))%m
d = ((a%m) * (a%m))%m + ((b)%m * (b)%m)%m
if n % 2 == 0:
return [c, d]
else:
return [d, c + d]
def charIN(x= ' '):
return(sys.stdin.readline().strip().split(x))
def arrIN(x = ' '):
return list(map(int,sys.stdin.readline().strip().split(x)))
def ncr(n,r):
num=den=1
for i in range(r):
num = (num*(n-i))%MOD
den = (den*(i+1))%MOD
return (num*(pow(den,MOD-2,MOD)))%MOD
def flush():
return sys.stdout.flush()
'''*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*'''
for _ in range(int(input())):
n = int(input())
s = [i for i in input()]
t = [i for i in input()]
d = defaultdict(int)
for i in range(n):
d[s[i]]+=1
d[t[i]]+=1
if len(list(d.keys()))>n or sum(i%2 for i in list(d.values())):
print('No')
else:
ans = []
for i in range(n):
if s[i]!=t[i]:
for j in range(i+1,n):
if s[j]!=t[j]:
if s[i]==s[j]:
ans.append([j,i])
s[j],t[i] = t[i],s[j]
break
elif s[i]==t[j]:
ans.append([j,j])
s[j],t[j] = t[j],s[j]
ans.append([j,i])
s[j],t[i] = t[i],s[j]
break
elif t[i]==t[j]:
ans.append([i,j])
s[i],t[j] = t[j],s[i]
break
elif t[i]==s[j]:
ans.append([j,j])
s[j],t[j] = t[j],s[j]
ans.append([i,j])
s[i],t[j] = t[j],s[i]
break
#assert(s[i]==t[i])
#assert(len(ans)<=2*n)
print('Yes')
print(len(ans))
for i in ans:
print(i[0]+1,i[1]+1)
|
from bisect import *
from collections import *
from itertools import *
import functools
import sys
import math
from decimal import *
from copy import *
from heapq import *
from fractions import *
getcontext().prec = 30
MAX = sys.maxsize
MAXN = 1000010
MOD = 10**9+7
spf = [i for i in range(MAXN)]
def sieve():
for i in range(2,MAXN,2):
spf[i] = 2
for i in range(3,int(MAXN**0.5)+1):
if spf[i]==i:
for j in range(i*i,MAXN,i):
if spf[j]==j:
spf[j]=i
def fib(n,m):
if n == 0:
return [0, 1]
else:
a, b = fib(n // 2)
c = ((a%m) * ((b%m) * 2 - (a%m)))%m
d = ((a%m) * (a%m))%m + ((b)%m * (b)%m)%m
if n % 2 == 0:
return [c, d]
else:
return [d, c + d]
def charIN(x= ' '):
return(sys.stdin.readline().strip().split(x))
def arrIN(x = ' '):
return list(map(int,sys.stdin.readline().strip().split(x)))
def ncr(n,r):
num=den=1
for i in range(r):
num = (num*(n-i))%MOD
den = (den*(i+1))%MOD
return (num*(pow(den,MOD-2,MOD)))%MOD
def flush():
return sys.stdout.flush()
'''*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*'''
for _ in range(int(input())):
n = int(input())
s = [i for i in input()]
t = [i for i in input()]
d = defaultdict(int)
for i in range(n):
d[s[i]]+=1
d[t[i]]+=1
if len(list(d.keys()))>n or sum(i%2 for i in list(d.values())):
print('No')
else:
ans = []
for i in range(n):
if s[i]!=t[i]:
for j in range(i+1,n):
if s[j]!=t[j]:
if s[i]==s[j]:
ans.append([j,i])
s[j],t[i] = t[i],s[j]
break
elif s[i]==t[j]:
ans.append([j,j])
s[j],t[j] = t[j],s[j]
ans.append([j,i])
s[j],t[i] = t[i],s[j]
break
elif t[i]==t[j]:
ans.append([i,j])
s[i],t[j] = t[j],s[i]
break
elif t[i]==s[j]:
ans.append([j,j])
s[j],t[j] = t[j],s[j]
ans.append([i,j])
s[i],t[j] = t[j],s[i]
break
#assert(s[i]==t[i])
#assert(len(ans)<=2*n)
print('Yes')
print(len(ans))
for i in ans:
print(i[0]+1,i[1]+1)
|
train
|
APPS_structured
|
Given a string s. An awesome substring is a non-empty substring of s such that we can make any number of swaps in order to make it palindrome.
Return the length of the maximum length awesome substring of s.
Example 1:
Input: s = "3242415"
Output: 5
Explanation: "24241" is the longest awesome substring, we can form the palindrome "24142" with some swaps.
Example 2:
Input: s = "12345678"
Output: 1
Example 3:
Input: s = "213123"
Output: 6
Explanation: "213123" is the longest awesome substring, we can form the palindrome "231132" with some swaps.
Example 4:
Input: s = "00"
Output: 2
Constraints:
1 <= s.length <= 10^5
s consists only of digits.
|
class Solution:
# bit mask, time O(kn), space O(2^k), where k is the number of unique characters we track. We go through the string once, and do k checks for each character.
# similar to 1371. Find the Longest Substring Containing Vowels in Even Counts.
'''
We have 10 + 1 types of palindromes. Use any number as the middle character, or don't have a middle character.
BitMask solution
We don't have to keep track of counters, we are only interested in odd counts in a substring. We can use one bit to say if some digit has even or odd count at any point.
Let 0 represent \"even\" and 1 represent \"odd\".
For example, for an input of \"233\":
i = 0, char = '2', xor 2nd bit from right:
mask = \"100\"
i = 1, char = '3', xor 3rd bit from right:
mask = \"1100\"
i = 2, char = '3', xor 3rd bit from right:
mask = \"0100\"
The last mask is \"0100\" which says it has only one number with odd count, so, the input can be rearranged to make it a palindrome: \"233\" => \"323\".
'''
def longestAwesome(self, s: str) -> int:
n = len(s)
res = mask = 0
seen = [n] * 1024 # length k = 10, 00..000, 00..001, ..., 11..111 states
seen[0] = -1
for i in range(n):
mask ^= 1 << int(s[i])
# check if we have seen similar mask before.
res = max(res, i - seen[mask])
# check if we have seen a mask such that it differs from the current mask by one bit being different.
for num in range(10):
res = max(res, i - seen[mask ^ (1 << num)])
seen[mask] = min(seen[mask], i) # save the earliest position
return res
|
class Solution:
# bit mask, time O(kn), space O(2^k), where k is the number of unique characters we track. We go through the string once, and do k checks for each character.
# similar to 1371. Find the Longest Substring Containing Vowels in Even Counts.
'''
We have 10 + 1 types of palindromes. Use any number as the middle character, or don't have a middle character.
BitMask solution
We don't have to keep track of counters, we are only interested in odd counts in a substring. We can use one bit to say if some digit has even or odd count at any point.
Let 0 represent \"even\" and 1 represent \"odd\".
For example, for an input of \"233\":
i = 0, char = '2', xor 2nd bit from right:
mask = \"100\"
i = 1, char = '3', xor 3rd bit from right:
mask = \"1100\"
i = 2, char = '3', xor 3rd bit from right:
mask = \"0100\"
The last mask is \"0100\" which says it has only one number with odd count, so, the input can be rearranged to make it a palindrome: \"233\" => \"323\".
'''
def longestAwesome(self, s: str) -> int:
n = len(s)
res = mask = 0
seen = [n] * 1024 # length k = 10, 00..000, 00..001, ..., 11..111 states
seen[0] = -1
for i in range(n):
mask ^= 1 << int(s[i])
# check if we have seen similar mask before.
res = max(res, i - seen[mask])
# check if we have seen a mask such that it differs from the current mask by one bit being different.
for num in range(10):
res = max(res, i - seen[mask ^ (1 << num)])
seen[mask] = min(seen[mask], i) # save the earliest position
return res
|
train
|
APPS_structured
|
Complete the function which takes two arguments and returns all numbers which are divisible by the given divisor. First argument is an array of `numbers` and the second is the `divisor`.
## Example
```python
divisible_by([1, 2, 3, 4, 5, 6], 2) == [2, 4, 6]
```
|
def divisible_by(numbers, divisor):
div_by = []
for num in numbers:
if num % divisor == 0:
div_by.append(num)
return div_by
|
def divisible_by(numbers, divisor):
div_by = []
for num in numbers:
if num % divisor == 0:
div_by.append(num)
return div_by
|
train
|
APPS_structured
|
Chef published a blog post, and is now receiving many queries about it. On day $i$, he receives $Q_i$ queries. But Chef can answer at most $k$ queries in a single day.
Chef always answers the maximum number of questions that he can on any given day (note however that this cannot be more than $k$). The remaining questions (if any) will be carried over to the next day.
Fortunately, after $n$ days, the queries have stopped. Chef would like to know the first day during which he has some free time, i.e. the first day when he answered less than $k$ questions.
-----Input:-----
- First line will contain $T$, the number of testcases. Then the testcases follow.
- The first line of each testcase contains two space separated integers $n$ and $k$.
- The second line of each testcase contains $n$ space separated integers, namely $Q_1, Q_2, ... Q_n$.
-----Output:-----
For each testcase, output in a single line the first day during which chef answers less than $k$ questions.
-----Constraints-----
- $1 \leq T \leq 10^5$
- $1 \leq $ sum of $n$ over all testcases $ \leq 10^5$
- $1 \leq k \leq 10^8$
- $0 \leq Q_i \leq 10^8$
-----Subtasks-----
- Subtask 1 - 20% points - Sum of $Q_i$ over all testcases and days $\leq 3 . 10^6$
- Subtask 2 - 80% points - Original constraints
-----Sample Input:-----
2
6 5
10 5 5 3 2 1
1 1
100
-----Sample Output:-----
6
101
-----Explanation:-----
Test Case 1
On the first day, chef answers 5 questions and leaves the remaining 5 (out of the 10) for the future days.
On the second day, chef has 10 questions waiting to be answered (5 received on the second day and 5 unanswered questions from day 1). Chef answers 5 of these questions and leaves the remaining 5 for the future.
On the third day, chef has 10 questions waiting to be answered (5 received on the third day and 5 unanswered questions from earlier). Chef answers 5 of these questions and leaves the remaining 5 for later.
On the fourth day, chef has 8 questions waiting to be answered (3 received on the fourth day and 5 unanswered questions from earlier). Chef answers 5 of these questions and leaves the remaining 3 for later.
On the fifth day, chef has 5 questions waiting to be answered (2 received on the fifth day and 3 unanswered questions from earlier). Chef answers all 5 of these questions.
On the sixth day, chef has 1 question, which he answers. This is the first day he answers less than 5 questions, and so the answer is 6.
Test Case 2
Chef answers 1 question a day for the first 100 days. On day 101, he is free.
|
for i in range(int(input())):
n,k=list(map(int,input().split()))
q=[int(z) for z in input().split()]
carry,flag=0,0
for i in range(n):
if q[i]+carry>=k:
carry+=q[i]-k
else:
flag=1
print(i+1)
break
if carry>0 and flag!=1:
print(carry//k +1+n)
elif carry==0 and flag!=1:
print(n+1)
|
for i in range(int(input())):
n,k=list(map(int,input().split()))
q=[int(z) for z in input().split()]
carry,flag=0,0
for i in range(n):
if q[i]+carry>=k:
carry+=q[i]-k
else:
flag=1
print(i+1)
break
if carry>0 and flag!=1:
print(carry//k +1+n)
elif carry==0 and flag!=1:
print(n+1)
|
train
|
APPS_structured
|
The government has invited bids from contractors to run canteens at all railway stations. Contractors will be allowed to bid for the catering contract at more than one station. However, to avoid monopolistic price-fixing, the government has declared that no contractor may bid for a pair of neighbouring stations.
The railway network has exactly one route between any pair of stations. Each station is directly connected by a railway line to at most $50$ neighbouring stations.
To help contractors plan their bids, the government has provided data on the number of passengers who pass through each station each year. Contractors would like to bid for stations with a higher volume of passenger traffic to increase their turnover.
For instance, suppose the railway network is as follows, where the volume of passenger traffic is indicated by the side of each station.
In this network, the best option for the contractor is to bid for stations $1, 2, 5$ and $6$, for a total passenger volume of $90$.
Your task is to choose a set of stations that the contractor should bid for so that the total volume of traffic across all the stations in the bid is maximized.
-----Input:-----
The first line of the input contains one integer $N$ indicating the number of railways stations in the network. The stations are numbered $1,2,...,N$. This is followed by $N$ lines of input, lines $2, 3,..., N+1$, indicating the volume of traffic at each station. The volume of traffic at station $i, 1 \leq i \leq N$, is given by a single integer in line $i+1$. The next $N-1$ lines of input, lines $N+2, N+3, ..., 2N$, describe the railway network. Each of these lines contains two integers, denoting a pair of stations that are neighbours.
-----Output:-----
The output should be a single integer, corresponding to the total volume of traffic across the set of stations in the optimal bid made by the contractor.
-----Constraints:-----
- $1 \leq N \leq 100000$.
- Each railway station has at most $50$ neighbours.
-----Sample Input-----
6
10
20
25
40
30
30
4 5
1 3
3 4
2 3
6 4
-----Sample Output-----
90
|
n=int(input())
l=[]
dp=[]
d={}
for i in range(n):
l.append(int(input()))
d[i]=[]
dp.append([0,0])
for i in range(n-1):
a,b=list(map(int,input().split()))
d[a-1].append(b-1)
d[b-1].append(a-1)
#print(l)
#print(d)
def dfs(ch,pa,visited):
dp[ch][1]=l[ch]
#print(dp[ch],ch+1)
for i in range(len(d[ch])):
if d[ch][i] not in visited:
visited.add(d[ch][i])
dfs(d[ch][i],ch,visited)
dp[ch][0]+=max(dp[d[ch][i]][0],dp[d[ch][i]][1])
dp[ch][1]+=dp[d[ch][i]][0]
#print(ch+1,dp[ch])
v=set()
v.add(0)
dfs(0,-1,v)
#print(dp)
print(max(dp[0][0],dp[0][1]))
|
n=int(input())
l=[]
dp=[]
d={}
for i in range(n):
l.append(int(input()))
d[i]=[]
dp.append([0,0])
for i in range(n-1):
a,b=list(map(int,input().split()))
d[a-1].append(b-1)
d[b-1].append(a-1)
#print(l)
#print(d)
def dfs(ch,pa,visited):
dp[ch][1]=l[ch]
#print(dp[ch],ch+1)
for i in range(len(d[ch])):
if d[ch][i] not in visited:
visited.add(d[ch][i])
dfs(d[ch][i],ch,visited)
dp[ch][0]+=max(dp[d[ch][i]][0],dp[d[ch][i]][1])
dp[ch][1]+=dp[d[ch][i]][0]
#print(ch+1,dp[ch])
v=set()
v.add(0)
dfs(0,-1,v)
#print(dp)
print(max(dp[0][0],dp[0][1]))
|
train
|
APPS_structured
|
Write a code that receives an array of numbers or strings, goes one by one through it while taking one value out, leaving one value in, taking, leaving, and back again to the beginning until all values are out.
It's like a circle of people who decide that every second person will leave it, until the last person is there. So if the last element of the array is taken, the first element that's still there, will stay.
The code returns a new re-arranged array with the taken values by their order. The first value of the initial array is always taken.
Examples:
|
def yes_no(arr):
result = []
while arr:
result.append(arr.pop(0))
if arr:
arr.append(arr.pop(0))
return result
|
def yes_no(arr):
result = []
while arr:
result.append(arr.pop(0))
if arr:
arr.append(arr.pop(0))
return result
|
train
|
APPS_structured
|
Given a m x n grid. Each cell of the grid has a sign pointing to the next cell you should visit if you are currently in this cell. The sign of grid[i][j] can be:
1 which means go to the cell to the right. (i.e go from grid[i][j] to grid[i][j + 1])
2 which means go to the cell to the left. (i.e go from grid[i][j] to grid[i][j - 1])
3 which means go to the lower cell. (i.e go from grid[i][j] to grid[i + 1][j])
4 which means go to the upper cell. (i.e go from grid[i][j] to grid[i - 1][j])
Notice that there could be some invalid signs on the cells of the grid which points outside the grid.
You will initially start at the upper left cell (0,0). A valid path in the grid is a path which starts from the upper left cell (0,0) and ends at the bottom-right cell (m - 1, n - 1) following the signs on the grid. The valid path doesn't have to be the shortest.
You can modify the sign on a cell with cost = 1. You can modify the sign on a cell one time only.
Return the minimum cost to make the grid have at least one valid path.
Example 1:
Input: grid = [[1,1,1,1],[2,2,2,2],[1,1,1,1],[2,2,2,2]]
Output: 3
Explanation: You will start at point (0, 0).
The path to (3, 3) is as follows. (0, 0) --> (0, 1) --> (0, 2) --> (0, 3) change the arrow to down with cost = 1 --> (1, 3) --> (1, 2) --> (1, 1) --> (1, 0) change the arrow to down with cost = 1 --> (2, 0) --> (2, 1) --> (2, 2) --> (2, 3) change the arrow to down with cost = 1 --> (3, 3)
The total cost = 3.
Example 2:
Input: grid = [[1,1,3],[3,2,2],[1,1,4]]
Output: 0
Explanation: You can follow the path from (0, 0) to (2, 2).
Example 3:
Input: grid = [[1,2],[4,3]]
Output: 1
Example 4:
Input: grid = [[2,2,2],[2,2,2]]
Output: 3
Example 5:
Input: grid = [[4]]
Output: 0
Constraints:
m == grid.length
n == grid[i].length
1 <= m, n <= 100
|
from collections import deque
class Solution:
def minCost(self, grid: List[List[int]]) -> int:
right, left, down, up = (0, 1), (0, -1), (1, 0), (-1, 0)
direction_map = {
1: right,
2: left,
3: down,
4: up
}
directions = [right, left, down, up]
visited = set()
def in_bounds(i, j):
return 0 <= i < len(grid) and 0 <= j < len(grid[i])
def dfs(i, j):
# not in bounds
if not in_bounds(i, j) or (i, j) in visited:
return []
visited.add((i, j))
sign = grid[i][j]
direction = direction_map[sign]
next_i, next_j = i + direction[0], j + direction[1]
return [(i, j)] + dfs(next_i, next_j)
reachable = dfs(0, 0)
curr_cost = 0
while reachable:
next_reachable = []
for (i, j) in reachable:
if i == len(grid) - 1 and j == len(grid[i]) - 1:
return curr_cost
for d in directions:
next_reachable += dfs(i + d[0], j + d[1])
reachable = next_reachable
curr_cost += 1
return -1
|
from collections import deque
class Solution:
def minCost(self, grid: List[List[int]]) -> int:
right, left, down, up = (0, 1), (0, -1), (1, 0), (-1, 0)
direction_map = {
1: right,
2: left,
3: down,
4: up
}
directions = [right, left, down, up]
visited = set()
def in_bounds(i, j):
return 0 <= i < len(grid) and 0 <= j < len(grid[i])
def dfs(i, j):
# not in bounds
if not in_bounds(i, j) or (i, j) in visited:
return []
visited.add((i, j))
sign = grid[i][j]
direction = direction_map[sign]
next_i, next_j = i + direction[0], j + direction[1]
return [(i, j)] + dfs(next_i, next_j)
reachable = dfs(0, 0)
curr_cost = 0
while reachable:
next_reachable = []
for (i, j) in reachable:
if i == len(grid) - 1 and j == len(grid[i]) - 1:
return curr_cost
for d in directions:
next_reachable += dfs(i + d[0], j + d[1])
reachable = next_reachable
curr_cost += 1
return -1
|
train
|
APPS_structured
|
Complete the function `power_of_two`/`powerOfTwo` (or equivalent, depending on your language) that determines if a given non-negative integer is a [power of two](https://en.wikipedia.org/wiki/Power_of_two). From the corresponding Wikipedia entry:
> *a power of two is a number of the form 2^(n) where **n** is an integer, i.e. the result of exponentiation with number two as the base and integer **n** as the exponent.*
You may assume the input is always valid.
## Examples
~~~if-not:nasm
```python
power_of_two(1024) ==> True
power_of_two(4096) ==> True
power_of_two(333) ==> False
```
~~~
~~~if:nasm
```
mov edi, 0
call power_of_two ; returns false (zero)
mov edi, 16
call power_of_two ; returns true (non-zero)
mov edi, 100
call power_of_two ; returns false
mov edi, 1024
call power_of_two ; returns true
mov edi, 20000
call power_of_two ; returns false
```
~~~
Beware of certain edge cases - for example, `1` is a power of `2` since `2^0 = 1` and `0` is not a power of `2`.
|
def power_of_two(n):
if n == 0:
return False
if n & n - 1:
return False
else:
return True
|
def power_of_two(n):
if n == 0:
return False
if n & n - 1:
return False
else:
return True
|
train
|
APPS_structured
|
You are given a positive integer $N$. Consider the sequence $S = (1, 2, \ldots, N)$. You should choose two elements of this sequence and swap them.
A swap is nice if there is an integer $M$ ($1 \le M < N$) such that the sum of the first $M$ elements of the resulting sequence is equal to the sum of its last $N-M$ elements. Find the number of nice swaps.
-----Input-----
- The first line of the input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows.
- The first and only line of each test case contains a single integer $N$.
-----Output-----
For each test case, print a single line containing one integer ― the number of nice swaps.
-----Constraints-----
- $1 \le T \le 10^6$
- $1 \le N \le 10^9$
-----Subtasks-----
Subtask #1 (10 points):
- $T \le 10$
- $N \le 10^3$
Subtask #2 (30 points):
- $T \le 10$
- $N \le 10^6$
Subtask #3 (60 points): original constraints
-----Example Input-----
5
1
2
3
4
7
-----Example Output-----
0
0
2
2
3
|
from math import floor,sqrt
n=int(input())
for i in range(n):
m=int(input())
if m%4==1 or m%4==2:
print(0)
else:
s=m*(m+1)//2
res=0
sm=s//2
p1=floor((sqrt(4*s+1)-1)/2)
s1=p1*(p1+1)//2
p=[p1-1,p1,p1+1]
s=[s1-p1,s1,s1+p[2]]
l=[sm-s[0],sm-s1,sm-s[2]]
for j in range(len(l)):
if l[j]==0:
res+=(p[j]*(p[j]-1)+(m-p[j]-1)*(m-p[j]))//2
elif l[j]>0 and l[j]<m:
res+=min([l[j],m-l[j],p[j],m-p[j]])
print(res)
|
from math import floor,sqrt
n=int(input())
for i in range(n):
m=int(input())
if m%4==1 or m%4==2:
print(0)
else:
s=m*(m+1)//2
res=0
sm=s//2
p1=floor((sqrt(4*s+1)-1)/2)
s1=p1*(p1+1)//2
p=[p1-1,p1,p1+1]
s=[s1-p1,s1,s1+p[2]]
l=[sm-s[0],sm-s1,sm-s[2]]
for j in range(len(l)):
if l[j]==0:
res+=(p[j]*(p[j]-1)+(m-p[j]-1)*(m-p[j]))//2
elif l[j]>0 and l[j]<m:
res+=min([l[j],m-l[j],p[j],m-p[j]])
print(res)
|
train
|
APPS_structured
|
Given a matrix consisting of 0s and 1s, we may choose any number of columns in the matrix and flip every cell in that column. Flipping a cell changes the value of that cell from 0 to 1 or from 1 to 0.
Return the maximum number of rows that have all values equal after some number of flips.
Example 1:
Input: [[0,1],[1,1]]
Output: 1
Explanation: After flipping no values, 1 row has all values equal.
Example 2:
Input: [[0,1],[1,0]]
Output: 2
Explanation: After flipping values in the first column, both rows have equal values.
Example 3:
Input: [[0,0,0],[0,0,1],[1,1,0]]
Output: 2
Explanation: After flipping values in the first two columns, the last two rows have equal values.
Note:
1 <= matrix.length <= 300
1 <= matrix[i].length <= 300
All matrix[i].length's are equal
matrix[i][j] is 0 or 1
|
class Solution:
def maxEqualRowsAfterFlips(self, matrix: List[List[int]]) -> int:
cache = collections.defaultdict(int)
for row in matrix:
vals = []
trans = []
for c in row:
vals.append(c)
trans.append(1 - c)
cache[str(vals)] += 1
cache[str(trans)] += 1
return max(cache.values())
'''
Counter({(0, 0, 0): 1})
===
Counter({(0, 0, 0): 1, (1, 1, 1): 1})
=========
Counter({(0, 0, 0): 1, (1, 1, 1): 1, (0, 0, 1): 1})
=========
Counter({(0, 0, 0): 1, (1, 1, 1): 1, (0, 0, 1): 1, (1, 1, 0): 1})
=========
Counter({(1, 1, 0): 2, (0, 0, 0): 1, (1, 1, 1): 1, (0, 0, 1): 1})
=========
Counter({(0, 0, 1): 2, (1, 1, 0): 2, (0, 0, 0): 1, (1, 1, 1): 1})
=========
'''
|
class Solution:
def maxEqualRowsAfterFlips(self, matrix: List[List[int]]) -> int:
cache = collections.defaultdict(int)
for row in matrix:
vals = []
trans = []
for c in row:
vals.append(c)
trans.append(1 - c)
cache[str(vals)] += 1
cache[str(trans)] += 1
return max(cache.values())
'''
Counter({(0, 0, 0): 1})
===
Counter({(0, 0, 0): 1, (1, 1, 1): 1})
=========
Counter({(0, 0, 0): 1, (1, 1, 1): 1, (0, 0, 1): 1})
=========
Counter({(0, 0, 0): 1, (1, 1, 1): 1, (0, 0, 1): 1, (1, 1, 0): 1})
=========
Counter({(1, 1, 0): 2, (0, 0, 0): 1, (1, 1, 1): 1, (0, 0, 1): 1})
=========
Counter({(0, 0, 1): 2, (1, 1, 0): 2, (0, 0, 0): 1, (1, 1, 1): 1})
=========
'''
|
train
|
APPS_structured
|
Chef had an array A with length N, but some of its elements got lost. Now, each element of this array is either unknown (denoted by -1) or a positive integer not exceeding K.
Chef decided to restore the array A by replacing each unknown element by a positive integer not exceeding K.
However, Chef has M restrictions that must hold for the restored array. There are two types of restrictions:
- I L R, meaning that for each i such that L < i ≤ R, the condition Ai - Ai-1 = 1 should be satisfied.
- D L R, meaning that for each i such that L < i ≤ R, the condition Ai - Ai-1 = -1 should be satisfied.
Chef would like to know the number of ways to restore the array while satisfying all restrictions, modulo 109+7.
-----Input-----
- The first line of the input contains a single integer T denoting the number of test cases. The description of T test cases follows.
- The first line of each test case contains three space-separated integers N, M and K.
- The second line contains N integers A1, A2, ..., AN.
- Each of the following M lines contains one restriction in the form I L R or D L R.
-----Output-----
For each test case, print a single line containing one integer - the number of ways to restore the array modulo 109+7.
-----Constraints-----
- 1 ≤ T ≤ 10
- 1 ≤ N, M ≤ 100,000
- 1 ≤ K ≤ 1,000,000,000
- 1 ≤ L < R ≤ N
- 1 ≤ Ai ≤ K or Ai = -1 for each valid i
- 1 ≤ sum of N over all test cases ≤ 500,000
- 1 ≤ sum of M over all test cases ≤ 500,000
-----Example-----
Input:
3
4 2 10
2 3 5 4
I 1 2
D 3 4
5 2 10
-1 -1 -1 -1 -1
I 1 3
D 3 5
6 2 2
-1 -1 -1 -1 -1 -1
I 1 4
D 4 6
Output:
1
8
0
|
# cook your dish here
MOD = 10 ** 9 + 7
for t in range(int(input())):
N, M, K = map(int, input().split())
A = list(map(int, input().split()))
I, D = [0] * (N + 2), [0] * (N + 2)
for i in range(M):
x, L, R = input().split()
L, R = int(L), int(R)
if x == 'I':
I[L] += 1
I[R] -= 1
else:
D[L] += 1
D[R] -= 1
impossibru = mx = mn = 0
ans = 1
for i in range(N):
I[i] += I[i - 1]
D[i] += D[i - 1]
if I[i] and D[i]:
impossibru = 1
break
if not I[i] and not D[i]:
ans = ans * (mx - mn + 1) % MOD
mn, mx = 1, K
elif I[i]:
mx = min(mx + 1, K)
mn += 1
elif D[i]:
mn = max(1, mn - 1)
mx -= 1
if mn > mx:
impossibru = 1
break
if A[i] != -1:
if not mn <= A[i] <= mx:
impossibru = 1
break
mn = mx = A[i]
ans = ans * (mx - mn + 1) % MOD
print(0 if impossibru else ans)
|
# cook your dish here
MOD = 10 ** 9 + 7
for t in range(int(input())):
N, M, K = map(int, input().split())
A = list(map(int, input().split()))
I, D = [0] * (N + 2), [0] * (N + 2)
for i in range(M):
x, L, R = input().split()
L, R = int(L), int(R)
if x == 'I':
I[L] += 1
I[R] -= 1
else:
D[L] += 1
D[R] -= 1
impossibru = mx = mn = 0
ans = 1
for i in range(N):
I[i] += I[i - 1]
D[i] += D[i - 1]
if I[i] and D[i]:
impossibru = 1
break
if not I[i] and not D[i]:
ans = ans * (mx - mn + 1) % MOD
mn, mx = 1, K
elif I[i]:
mx = min(mx + 1, K)
mn += 1
elif D[i]:
mn = max(1, mn - 1)
mx -= 1
if mn > mx:
impossibru = 1
break
if A[i] != -1:
if not mn <= A[i] <= mx:
impossibru = 1
break
mn = mx = A[i]
ans = ans * (mx - mn + 1) % MOD
print(0 if impossibru else ans)
|
train
|
APPS_structured
|
Given a string, you have to return a string in which each character (case-sensitive) is repeated once.
```python
double_char("String") ==> "SSttrriinngg"
double_char("Hello World") ==> "HHeelllloo WWoorrlldd"
double_char("1234!_ ") ==> "11223344!!__ "
```
Good Luck!
|
def double_char(s):
l = list(s)
r = []
for i in range(len(l)):
r.append(l[i]+l[i])
return ''.join(r)
|
def double_char(s):
l = list(s)
r = []
for i in range(len(l)):
r.append(l[i]+l[i])
return ''.join(r)
|
train
|
APPS_structured
|
You are given a table $a$ of size $2 \times n$ (i.e. two rows and $n$ columns) consisting of integers from $1$ to $n$.
In one move, you can choose some column $j$ ($1 \le j \le n$) and swap values $a_{1, j}$ and $a_{2, j}$ in it. Each column can be chosen no more than once.
Your task is to find the minimum number of moves required to obtain permutations of size $n$ in both first and second rows of the table or determine if it is impossible to do that.
You have to answer $t$ independent test cases.
Recall that the permutation of size $n$ is such an array of size $n$ that contains each integer from $1$ to $n$ exactly once (the order of elements doesn't matter).
-----Input-----
The first line of the input contains one integer $t$ ($1 \le t \le 2 \cdot 10^4$) — the number of test cases. Then $t$ test cases follow.
The first line of the test case contains one integer $n$ ($1 \le n \le 2 \cdot 10^5$) — the number of columns in the table. The second line of the test case contains $n$ integers $a_{1, 1}, a_{1, 2}, \dots, a_{1, n}$ ($1 \le a_{1, i} \le n$), where $a_{1, i}$ is the $i$-th element of the first row of the table. The third line of the test case contains $n$ integers $a_{2, 1}, a_{2, 2}, \dots, a_{2, n}$ ($1 \le a_{2, i} \le n$), where $a_{2, i}$ is the $i$-th element of the second row of the table.
It is guaranteed that the sum of $n$ does not exceed $2 \cdot 10^5$ ($\sum n \le 2 \cdot 10^5$).
-----Output-----
For each test case print the answer: -1 if it is impossible to obtain permutation of size $n$ in both first and the second rows of the table, or one integer $k$ in the first line, where $k$ is the minimum number of moves required to obtain permutations in both rows, and $k$ distinct integers $pos_1, pos_2, \dots, pos_k$ in the second line ($1 \le pos_i \le n$) in any order — indices of columns in which you need to swap values to obtain permutations in both rows. If there are several answers, you can print any.
-----Example-----
Input
6
4
1 2 3 4
2 3 1 4
5
5 3 5 1 4
1 2 3 2 4
3
1 2 1
3 3 2
4
1 2 2 1
3 4 3 4
4
4 3 1 4
3 2 2 1
3
1 1 2
3 2 2
Output
0
2
2 3
1
1
2
3 4
2
3 4
-1
|
import sys
# range = xrange
# input = raw_input
inp = [int(x) for x in sys.stdin.read().split()]
ii = 0
out = []
def solve(n, A):
same = [-1]*(2 * n);pos = [-1] * n
for i in range(2 * n):
a = A[i]
if pos[a] == -1:
pos[a] = i
elif pos[a] == -2:
return None
else:
p = pos[a]
pos[a] = -2
same[p] = i
same[i] = p
ans = []
found = [0] * (2 * n)
for root in range(2 * n):
if found[root]:
continue
count0 = []
count1 = []
node = root
while not found[node]:
found[node] = 1
found[same[node]] = 1
if node & 1:
count0.append(node >> 1)
else:
count1.append(node >> 1)
node = same[node ^ 1]
if len(count0) < len(count1):
ans += count0
else:
ans += count1
return ans
t = inp[ii]
ii += 1
for _ in range(t):
n = inp[ii]
ii += 1
A = [x - 1 for x in inp[ii: ii + n]]
ii += n
B = [x - 1 for x in inp[ii: ii + n]]
ii += n
A = [A[i >> 1] if i & 1 == 0 else B[i >> 1] for i in range(2 * n)]
ans = solve(n, A)
if ans is None:
out.append('-1')
else:
out.append(str(len(ans)))
out.append(' '.join(str(x + 1) for x in ans))
print('\n'.join(out))
|
import sys
# range = xrange
# input = raw_input
inp = [int(x) for x in sys.stdin.read().split()]
ii = 0
out = []
def solve(n, A):
same = [-1]*(2 * n);pos = [-1] * n
for i in range(2 * n):
a = A[i]
if pos[a] == -1:
pos[a] = i
elif pos[a] == -2:
return None
else:
p = pos[a]
pos[a] = -2
same[p] = i
same[i] = p
ans = []
found = [0] * (2 * n)
for root in range(2 * n):
if found[root]:
continue
count0 = []
count1 = []
node = root
while not found[node]:
found[node] = 1
found[same[node]] = 1
if node & 1:
count0.append(node >> 1)
else:
count1.append(node >> 1)
node = same[node ^ 1]
if len(count0) < len(count1):
ans += count0
else:
ans += count1
return ans
t = inp[ii]
ii += 1
for _ in range(t):
n = inp[ii]
ii += 1
A = [x - 1 for x in inp[ii: ii + n]]
ii += n
B = [x - 1 for x in inp[ii: ii + n]]
ii += n
A = [A[i >> 1] if i & 1 == 0 else B[i >> 1] for i in range(2 * n)]
ans = solve(n, A)
if ans is None:
out.append('-1')
else:
out.append(str(len(ans)))
out.append(' '.join(str(x + 1) for x in ans))
print('\n'.join(out))
|
train
|
APPS_structured
|
Everybody know that you passed to much time awake during night time...
Your task here is to define how much coffee you need to stay awake after your night.
You will have to complete a function that take an array of events in arguments, according to this list you will return the number of coffee you need to stay awake during day time. **Note**: If the count exceed 3 please return 'You need extra sleep'.
The list of events can contain the following:
- You come here, to solve some kata ('cw').
- You have a dog or a cat that just decide to wake up too early ('dog' | 'cat').
- You just watch a movie ('movie').
- Other events can be present and it will be represent by arbitrary string, just ignore this one.
Each event can be downcase/lowercase, or uppercase. If it is downcase/lowercase you need 1 coffee by events and if it is uppercase you need 2 coffees.
|
def how_much_coffee(events):
activities = ["cw", "cat", "dog", "movie"]
coffee = 0
for e in events:
if e.lower() in activities:
if e == e.upper():
coffee += 2
else:
coffee += 1
if coffee > 3:
return "You need extra sleep"
return coffee
|
def how_much_coffee(events):
activities = ["cw", "cat", "dog", "movie"]
coffee = 0
for e in events:
if e.lower() in activities:
if e == e.upper():
coffee += 2
else:
coffee += 1
if coffee > 3:
return "You need extra sleep"
return coffee
|
train
|
APPS_structured
|
*** Nova polynomial from roots***
This kata is from a series on polynomial handling. ( [#1](http://www.codewars.com/kata/nova-polynomial-1-add-1) [#2](http://www.codewars.com/kata/570eb07e127ad107270005fe) [#3](http://www.codewars.com/kata/5714041e8807940ff3001140 ) [#4](http://www.codewars.com/kata/571a2e2df24bdfd4e20001f5))
Consider a polynomial in a list where each element in the list element corresponds to the factors. The factor order is the position in the list. The first element is the zero order factor (the constant).
p = [a0, a1, a2, a3] signifies the polynomial a0 + a1x + a2x^2 + a3*x^3
In this kata create the polynomial from a list of roots:
[r0, r1 ,r2, r3 ]
p = (x-r0)(x-r1)(x-r2)(x-r3)
note: no roots should return the identity polynomial.
```python
poly_from_roots([4]) = [-4, 1]
poly_from_roots([0, 0, 0, 0] ) = [0, 0, 0, 0, 1]
poly_from_roots([]) = [1]
```
The first katas of this series is preloaded in the code and can be used: [poly_add](http://www.codewars.com/kata/570eb07e127ad107270005fe) [poly_multiply](http://www.codewars.com/kata/570eb07e127ad107270005fe)
|
from itertools import combinations
from functools import reduce
from operator import mul
def poly_from_roots(r):
res = []
for p in range(len(r)+1):
factor = sum(reduce(mul, [v for v in k], 1)
for k in combinations(r, p))
res.append(-factor if p % 2 else factor)
return res[::-1]
|
from itertools import combinations
from functools import reduce
from operator import mul
def poly_from_roots(r):
res = []
for p in range(len(r)+1):
factor = sum(reduce(mul, [v for v in k], 1)
for k in combinations(r, p))
res.append(-factor if p % 2 else factor)
return res[::-1]
|
train
|
APPS_structured
|
# Task
Consider an array of integers `a`. Let `min(a)` be its minimal element, and let `avg(a)` be its mean.
Define the center of the array `a` as array `b` such that:
```
- b is formed from a by erasing some of its elements.
- For each i, |b[i] - avg(a)| < min(a).
- b has the maximum number of elements among all the arrays
satisfying the above requirements.
```
Given an array of integers, return its center.
# Input/Output
`[input]` integer array `a`
Unsorted non-empty array of integers.
`2 ≤ a.length ≤ 50,`
`1 ≤ a[i] ≤ 350.`
`[output]` an integer array
# Example
For `a = [8, 3, 4, 5, 2, 8]`, the output should be `[4, 5]`.
Here `min(a) = 2, avg(a) = 5`.
For `a = [1, 3, 2, 1]`, the output should be `[1, 2, 1]`.
Here `min(a) = 1, avg(a) = 1.75`.
|
def array_center(arr):
m, a = min(arr), (sum(arr) / len(arr))
return [n for n in arr if abs(n - a) < m]
|
def array_center(arr):
m, a = min(arr), (sum(arr) / len(arr))
return [n for n in arr if abs(n - a) < m]
|
train
|
APPS_structured
|
You are given an array that of arbitrary depth that needs to be nearly flattened into a 2 dimensional array. The given array's depth is also non-uniform, so some parts may be deeper than others.
All of lowest level arrays (most deeply nested) will contain only integers and none of the higher level arrays will contain anything but other arrays. All arrays given will be at least 2 dimensional. All lowest level arrays will contain at least one element.
Your solution should be an array containing all of the lowest level arrays and only these. The sub-arrays should be ordered by the smallest element within each, so `[1,2]` should preceed `[3,4,5]`. Note: integers will not be repeated.
For example:
If you receive `[[[1,2,3],[4,5]],[6,7]]`, your answer should be `[[1,2,3],[4,5],[6,7]]`.
|
def near_flatten(a):
li = []
def do(a):
for i in a:
li.append(i if all(isinstance(k, int) for k in i) else do(i))
do(a)
return sorted([i for i in li if i])
|
def near_flatten(a):
li = []
def do(a):
for i in a:
li.append(i if all(isinstance(k, int) for k in i) else do(i))
do(a)
return sorted([i for i in li if i])
|
train
|
APPS_structured
|
In order to celebrate Twice's 5th anniversary, Tzuyu and Sana decided to play a game.
Tzuyu gave Sana two integers $a$ and $b$ and a really important quest.
In order to complete the quest, Sana has to output the smallest possible value of ($a \oplus x$) + ($b \oplus x$) for any given $x$, where $\oplus$ denotes the bitwise XOR operation.
-----Input-----
Each test contains multiple test cases. The first line contains the number of test cases $t$ ($1 \le t \le 10^{4}$). Description of the test cases follows.
The only line of each test case contains two integers $a$ and $b$ ($1 \le a, b \le 10^{9}$).
-----Output-----
For each testcase, output the smallest possible value of the given expression.
-----Example-----
Input
6
6 12
4 9
59 832
28 14
4925 2912
1 1
Output
10
13
891
18
6237
0
-----Note-----
For the first test case Sana can choose $x=4$ and the value will be ($6 \oplus 4$) + ($12 \oplus 4$) = $2 + 8$ = $10$. It can be shown that this is the smallest possible value.
|
t = int(input())
for _ in range(t):
a,b = map(int,input().split())
if a > b:
a,b = b,a
print(a^b)
|
t = int(input())
for _ in range(t):
a,b = map(int,input().split())
if a > b:
a,b = b,a
print(a^b)
|
train
|
APPS_structured
|
The chef was searching for his pen in the garage but he found his old machine with a display and some numbers on it. If some numbers entered then some different output occurs on the display. Chef wants to crack the algorithm that the machine is following.
Example to identify the pattern :
Input Output
9 36
5 10
1 0
2 1
-----Input:-----
- First-line will contain $T$, the number of test cases. Then the test cases follow.
- Each test case contains a single line of input, $N$.
-----Output:-----
For each test case, output in a single line answer as displayed on the screen.
-----Constraints-----
- $1 \leq T \leq 10^6$
- $1 \leq N \leq 10^6$
-----Sample Input:-----
1
7
-----Sample Output:-----
21
|
# cook your dish here
T = int(input())
for t in range(T):
N = int(input())
print(int(((N-1)*(N))/2))
|
# cook your dish here
T = int(input())
for t in range(T):
N = int(input())
print(int(((N-1)*(N))/2))
|
train
|
APPS_structured
|
There is a one-dimensional garden on the x-axis. The garden starts at the point 0 and ends at the point n. (i.e The length of the garden is n).
There are n + 1 taps located at points [0, 1, ..., n] in the garden.
Given an integer n and an integer array ranges of length n + 1 where ranges[i] (0-indexed) means the i-th tap can water the area [i - ranges[i], i + ranges[i]] if it was open.
Return the minimum number of taps that should be open to water the whole garden, If the garden cannot be watered return -1.
Example 1:
Input: n = 5, ranges = [3,4,1,1,0,0]
Output: 1
Explanation: The tap at point 0 can cover the interval [-3,3]
The tap at point 1 can cover the interval [-3,5]
The tap at point 2 can cover the interval [1,3]
The tap at point 3 can cover the interval [2,4]
The tap at point 4 can cover the interval [4,4]
The tap at point 5 can cover the interval [5,5]
Opening Only the second tap will water the whole garden [0,5]
Example 2:
Input: n = 3, ranges = [0,0,0,0]
Output: -1
Explanation: Even if you activate all the four taps you cannot water the whole garden.
Example 3:
Input: n = 7, ranges = [1,2,1,0,2,1,0,1]
Output: 3
Example 4:
Input: n = 8, ranges = [4,0,0,0,0,0,0,0,4]
Output: 2
Example 5:
Input: n = 8, ranges = [4,0,0,0,4,0,0,0,4]
Output: 1
Constraints:
1 <= n <= 10^4
ranges.length == n + 1
0 <= ranges[i] <= 100
|
class Solution:
def minTaps(self, n: int, ranges: List[int]) -> int:
if not ranges: return 0
N = len(ranges)
# For all location of taps, store the largest right reach point
max_right_end = list(range(N))
for i, a in enumerate(ranges):
max_right_end[max(i - a, 0)] = min(i + a, N-1)
print(max_right_end)
res, l, r = 0, 0, max_right_end[0]
while True:
res += 1
# if r can reach to the end of the whole garden, return res
if r>=N-1:return res
new_r = max(max_right_end[l:r+1])
# if next r is same as current r, it means we can not move forward, return -1
if new_r == r:return -1
l, r = r, new_r
|
class Solution:
def minTaps(self, n: int, ranges: List[int]) -> int:
if not ranges: return 0
N = len(ranges)
# For all location of taps, store the largest right reach point
max_right_end = list(range(N))
for i, a in enumerate(ranges):
max_right_end[max(i - a, 0)] = min(i + a, N-1)
print(max_right_end)
res, l, r = 0, 0, max_right_end[0]
while True:
res += 1
# if r can reach to the end of the whole garden, return res
if r>=N-1:return res
new_r = max(max_right_end[l:r+1])
# if next r is same as current r, it means we can not move forward, return -1
if new_r == r:return -1
l, r = r, new_r
|
train
|
APPS_structured
|
An axis-aligned rectangle is represented as a list [x1, y1, x2, y2], where (x1, y1) is the coordinate of its bottom-left corner, and (x2, y2) is the coordinate of its top-right corner. Its top and bottom edges are parallel to the X-axis, and its left and right edges are parallel to the Y-axis.
Two rectangles overlap if the area of their intersection is positive. To be clear, two rectangles that only touch at the corner or edges do not overlap.
Given two axis-aligned rectangles rec1 and rec2, return true if they overlap, otherwise return false.
Example 1:
Input: rec1 = [0,0,2,2], rec2 = [1,1,3,3]
Output: true
Example 2:
Input: rec1 = [0,0,1,1], rec2 = [1,0,2,1]
Output: false
Example 3:
Input: rec1 = [0,0,1,1], rec2 = [2,2,3,3]
Output: false
Constraints:
rect1.length == 4
rect2.length == 4
-109 <= rec1[i], rec2[i] <= 109
rec1[0] <= rec1[2] and rec1[1] <= rec1[3]
rec2[0] <= rec2[2] and rec2[1] <= rec2[3]
|
class Solution:
def isRectangleOverlap(self, r1: List[int], r2: List[int]) -> bool:
return max(r1[0],r2[0])<min(r1[2],r2[2]) and max(r1[1],r2[1])<min(r1[3],r2[3])
|
class Solution:
def isRectangleOverlap(self, r1: List[int], r2: List[int]) -> bool:
return max(r1[0],r2[0])<min(r1[2],r2[2]) and max(r1[1],r2[1])<min(r1[3],r2[3])
|
train
|
APPS_structured
|
In this problem you are given a sequence of $N$ positive integers $S[1],S[2],\dots,S[N]$. In addition you are given an integer $T$, and your aim is to find the number of quadruples $(i,j,k,l)$, such that $1 \le i < j < k < l \le N$, and $S[i] + S[j] + S[k] + S[l] = T$. That is, the number of ways of picking four numbers from the sequence summing up to $T$.
-----Constraints:-----
For all test cases,
- $1 \le N \le 5000$
- $1 \le T \le 10^6$
- $1 \le S[i] \le 10^9$, for all $i$.
Subtask $1:10\%$
It is guaranteed that $N \le 50$.
Subtask $2:50\%$
It is guaranteed that $N \le 300$.
Subtask $3:40\%$
No additional guarantees.
-----Input Format:-----
There is only one line of input with $N+2$ space separated integers. The first two integers are $N$ and $T$. The next $N$ integers are $S[1],S[2],\dots,S[N]$.
-----Output Format:-----
A single integer which is the number of valid quadruples.
-----Sample Input 1:-----
6 20 3 1 1 2 5 10
-----Sample Output 1:-----
1
-----Explanation 1:-----
The quadruple $(1,4,5,6)$ is valid because $S[1]+S[4]+S[5]+S[6]=3+2+5+10=20$. You can check that no other quadruple is valid and hence the answer is $1$.
-----Sample Input 2:-----
6 13 1 2 3 4 5 4
-----Sample Output 2:-----
3
-----Explanation 2:-----
You can verify that the only quadruples that are valid are $(2,3,4,6),(1,3,4,5)$ and $(1,3,5,6)$. Thus, the answer is $3$.
-----Note:-----
As the answer might be large, please use 64 bit integers (long long int in
C/C++ and long in Java) instead of 32 bit int.
|
x = list(map(int,input().split()))
n = x[0]
t = x[1]
a = x[2:n+2]
a.sort()
sums = [0] * t
count = 0
for i in range(n):
for j in range(i+1,n):
add = a[i] + a[j]
if add < t:
count += sums[t-add]
for k in range(i):
add = a[i] + a[k]
if add<t:
sums[add] += 1
print(count)
|
x = list(map(int,input().split()))
n = x[0]
t = x[1]
a = x[2:n+2]
a.sort()
sums = [0] * t
count = 0
for i in range(n):
for j in range(i+1,n):
add = a[i] + a[j]
if add < t:
count += sums[t-add]
for k in range(i):
add = a[i] + a[k]
if add<t:
sums[add] += 1
print(count)
|
train
|
APPS_structured
|
Write a program that outputs the `n` largest elements from a list.
Example:
```python
largest(2, [7,6,5,4,3,2,1])
# => [6,7]
```
|
def largest(n,xs):
lst = sorted(xs)
new = []
for i in range(n):
new.append(lst[-i-1])
return sorted(new)
|
def largest(n,xs):
lst = sorted(xs)
new = []
for i in range(n):
new.append(lst[-i-1])
return sorted(new)
|
train
|
APPS_structured
|
Just to remind, girls in Arpa's land are really nice.
Mehrdad wants to invite some Hoses to the palace for a dancing party. Each Hos has some weight w_{i} and some beauty b_{i}. Also each Hos may have some friends. Hoses are divided in some friendship groups. Two Hoses x and y are in the same friendship group if and only if there is a sequence of Hoses a_1, a_2, ..., a_{k} such that a_{i} and a_{i} + 1 are friends for each 1 ≤ i < k, and a_1 = x and a_{k} = y.
[Image]
Arpa allowed to use the amphitheater of palace to Mehrdad for this party. Arpa's amphitheater can hold at most w weight on it.
Mehrdad is so greedy that he wants to invite some Hoses such that sum of their weights is not greater than w and sum of their beauties is as large as possible. Along with that, from each friendship group he can either invite all Hoses, or no more than one. Otherwise, some Hoses will be hurt. Find for Mehrdad the maximum possible total beauty of Hoses he can invite so that no one gets hurt and the total weight doesn't exceed w.
-----Input-----
The first line contains integers n, m and w (1 ≤ n ≤ 1000, $0 \leq m \leq \operatorname{min}(\frac{n \cdot(n - 1)}{2}, 10^{5})$, 1 ≤ w ≤ 1000) — the number of Hoses, the number of pair of friends and the maximum total weight of those who are invited.
The second line contains n integers w_1, w_2, ..., w_{n} (1 ≤ w_{i} ≤ 1000) — the weights of the Hoses.
The third line contains n integers b_1, b_2, ..., b_{n} (1 ≤ b_{i} ≤ 10^6) — the beauties of the Hoses.
The next m lines contain pairs of friends, the i-th of them contains two integers x_{i} and y_{i} (1 ≤ x_{i}, y_{i} ≤ n, x_{i} ≠ y_{i}), meaning that Hoses x_{i} and y_{i} are friends. Note that friendship is bidirectional. All pairs (x_{i}, y_{i}) are distinct.
-----Output-----
Print the maximum possible total beauty of Hoses Mehrdad can invite so that no one gets hurt and the total weight doesn't exceed w.
-----Examples-----
Input
3 1 5
3 2 5
2 4 2
1 2
Output
6
Input
4 2 11
2 4 6 6
6 4 2 1
1 2
2 3
Output
7
-----Note-----
In the first sample there are two friendship groups: Hoses {1, 2} and Hos {3}. The best way is to choose all of Hoses in the first group, sum of their weights is equal to 5 and sum of their beauty is 6.
In the second sample there are two friendship groups: Hoses {1, 2, 3} and Hos {4}. Mehrdad can't invite all the Hoses from the first group because their total weight is 12 > 11, thus the best way is to choose the first Hos from the first group and the only one from the second group. The total weight will be 8, and the total beauty will be 7.
|
f = lambda: map(int, input().split())
n, m, w = f()
wb = [(0, 0)] + list(zip(f(), f()))
t = list(range(n + 1))
def g(x):
if x == t[x]: return x
t[x] = g(t[x])
return t[x]
for i in range(m):
x, y = f()
x, y = g(x), g(y)
if x != y: t[y] = x
p = [[] for j in range(n + 1)]
for i in range(1, n + 1): p[g(i)].append(i)
d = [1] + [0] * w
for q in p:
if len(q) > 1:
WB = [wb[i] for i in q]
SW = sum(q[0] for q in WB)
SB = sum(q[1] for q in WB)
for D in range(w, -1, -1):
if d[D]:
if D + SW <= w: d[D + SW] = max(d[D + SW], d[D] + SB)
for W, B in WB:
if D + W <= w: d[D + W] = max(d[D + W], d[D] + B)
elif len(q) == 1:
W, B = wb[q[0]]
for D in range(w - W, -1, -1):
if d[D]: d[D + W] = max(d[D + W], d[D] + B)
print(max(d) - 1)
|
f = lambda: map(int, input().split())
n, m, w = f()
wb = [(0, 0)] + list(zip(f(), f()))
t = list(range(n + 1))
def g(x):
if x == t[x]: return x
t[x] = g(t[x])
return t[x]
for i in range(m):
x, y = f()
x, y = g(x), g(y)
if x != y: t[y] = x
p = [[] for j in range(n + 1)]
for i in range(1, n + 1): p[g(i)].append(i)
d = [1] + [0] * w
for q in p:
if len(q) > 1:
WB = [wb[i] for i in q]
SW = sum(q[0] for q in WB)
SB = sum(q[1] for q in WB)
for D in range(w, -1, -1):
if d[D]:
if D + SW <= w: d[D + SW] = max(d[D + SW], d[D] + SB)
for W, B in WB:
if D + W <= w: d[D + W] = max(d[D + W], d[D] + B)
elif len(q) == 1:
W, B = wb[q[0]]
for D in range(w - W, -1, -1):
if d[D]: d[D + W] = max(d[D + W], d[D] + B)
print(max(d) - 1)
|
train
|
APPS_structured
|
You are given an array a with n distinct integers. Construct an array b by permuting a such that for every non-empty subset of indices S = {x_1, x_2, ..., x_{k}} (1 ≤ x_{i} ≤ n, 0 < k < n) the sums of elements on that positions in a and b are different, i. e. $\sum_{i = 1}^{k} a_{x_{i}} \neq \sum_{i = 1}^{k} b_{x_{i}}$
-----Input-----
The first line contains one integer n (1 ≤ n ≤ 22) — the size of the array.
The second line contains n space-separated distinct integers a_1, a_2, ..., a_{n} (0 ≤ a_{i} ≤ 10^9) — the elements of the array.
-----Output-----
If there is no such array b, print -1.
Otherwise in the only line print n space-separated integers b_1, b_2, ..., b_{n}. Note that b must be a permutation of a.
If there are multiple answers, print any of them.
-----Examples-----
Input
2
1 2
Output
2 1
Input
4
1000 100 10 1
Output
100 1 1000 10
-----Note-----
An array x is a permutation of y, if we can shuffle elements of y such that it will coincide with x.
Note that the empty subset and the subset containing all indices are not counted.
|
n = int(input())
l = [int(i) for i in input().split(" ")]
index = []
nums = sorted(l)
for i in l:
index.append(nums.index(i))
#print(index)
indexbis = [int(i - 1) for i in index]
for i in range(n):
if indexbis[i] == min(indexbis):
indexbis[i] = n - 1
break
#print(indexbis)
for i in indexbis:
print(l[index.index(i)], end = " ")
|
n = int(input())
l = [int(i) for i in input().split(" ")]
index = []
nums = sorted(l)
for i in l:
index.append(nums.index(i))
#print(index)
indexbis = [int(i - 1) for i in index]
for i in range(n):
if indexbis[i] == min(indexbis):
indexbis[i] = n - 1
break
#print(indexbis)
for i in indexbis:
print(l[index.index(i)], end = " ")
|
train
|
APPS_structured
|
_Friday 13th or Black Friday is considered as unlucky day. Calculate how many unlucky days are in the given year._
Find the number of Friday 13th in the given year.
__Input:__ Year as an integer.
__Output:__ Number of Black Fridays in the year as an integer.
__Examples:__
unluckyDays(2015) == 3
unluckyDays(1986) == 1
***Note:*** In Ruby years will start from 1593.
|
from datetime import datetime
def unlucky_days(year: int) -> sum:
return sum(datetime(year, month, 13).weekday() == 4 for month in range(1, 13))
|
from datetime import datetime
def unlucky_days(year: int) -> sum:
return sum(datetime(year, month, 13).weekday() == 4 for month in range(1, 13))
|
train
|
APPS_structured
|
We partition a row of numbers A into at most K adjacent (non-empty) groups, then our score is the sum of the average of each group. What is the largest score we can achieve?
Note that our partition must use every number in A, and that scores are not necessarily integers.
Example:
Input:
A = [9,1,2,3,9]
K = 3
Output: 20
Explanation:
The best choice is to partition A into [9], [1, 2, 3], [9]. The answer is 9 + (1 + 2 + 3) / 3 + 9 = 20.
We could have also partitioned A into [9, 1], [2], [3, 9], for example.
That partition would lead to a score of 5 + 2 + 6 = 13, which is worse.
Note:
1 <= A.length <= 100.
1 <= A[i] <= 10000.
1 <= K <= A.length.
Answers within 10^-6 of the correct answer will be accepted as correct.
|
class Solution:
def largestSumOfAverages(self, A: List[int], K: int) -> float:
dp = [[0 for j in range(K)] for i in A]
for j in range(len(A)):
for i in range(K):
if i==0:
dp[j][i] = sum(A[:j+1])/len(A[:j+1])
else:
if len(A[:j+1]) < i+1:
break
for k in range(j):
dp[j][i]=max(dp[k][i-1]+sum(A[k+1:j+1])/len(A[k+1:j+1]),dp[j][i])
return dp[-1][-1]
|
class Solution:
def largestSumOfAverages(self, A: List[int], K: int) -> float:
dp = [[0 for j in range(K)] for i in A]
for j in range(len(A)):
for i in range(K):
if i==0:
dp[j][i] = sum(A[:j+1])/len(A[:j+1])
else:
if len(A[:j+1]) < i+1:
break
for k in range(j):
dp[j][i]=max(dp[k][i-1]+sum(A[k+1:j+1])/len(A[k+1:j+1]),dp[j][i])
return dp[-1][-1]
|
train
|
APPS_structured
|
Brief
=====
In this easy kata your function has to take a **string** as input and **return a string** with everything removed (*whitespaces* included) but the **digits**. As you may have guessed **empty strings** are to be returned as they are & if the input string contains no digits then the output will be an **empty string**.By the way , you have to watch out for **non-string** inputs too.Return **'Invalid input !'** for them.
Hint
====
If you're writing more than 1 line of code, then think again! ;)
Good luck!
|
def digit_all (x):
if isinstance(x,str):
return "".join( x for x in x if x.isnumeric())
else:
return 'Invalid input !'
|
def digit_all (x):
if isinstance(x,str):
return "".join( x for x in x if x.isnumeric())
else:
return 'Invalid input !'
|
train
|
APPS_structured
|

Create a class called `Warrior` which calculates and keeps track of their level and skills, and ranks them as the warrior they've proven to be.
Business Rules:
- A warrior starts at level 1 and can progress all the way to 100.
- A warrior starts at rank `"Pushover"` and can progress all the way to `"Greatest"`.
- The only acceptable range of rank values is `"Pushover", "Novice", "Fighter", "Warrior", "Veteran", "Sage", "Elite", "Conqueror", "Champion", "Master", "Greatest"`.
- Warriors will compete in battles. Battles will always accept an enemy level to match against your own.
- With each battle successfully finished, your warrior's experience is updated based on the enemy's level.
- The experience earned from the battle is relative to what the warrior's current level is compared to the level of the enemy.
- A warrior's experience starts from 100. Each time the warrior's experience increases by another 100, the warrior's level rises to the next level.
- A warrior's experience is cumulative, and does not reset with each rise of level. The only exception is when the warrior reaches level 100, with which the experience stops at 10000
- At every 10 levels, your warrior will reach a new rank tier. (ex. levels 1-9 falls within `"Pushover"` tier, levels 80-89 fall within `"Champion"` tier, etc.)
- A warrior cannot progress beyond level 100 and rank `"Greatest"`.
Battle Progress Rules & Calculations:
- If an enemy level does not fall in the range of 1 to 100, the battle cannot happen and should return `"Invalid level"`.
- Completing a battle against an enemy with the same level as your warrior will be worth 10 experience points.
- Completing a battle against an enemy who is one level lower than your warrior will be worth 5 experience points.
- Completing a battle against an enemy who is two levels lower or more than your warrior will give 0 experience points.
- Completing a battle against an enemy who is one level higher or more than your warrior will accelarate your experience gaining. The greater the difference between levels, the more experinece your warrior will gain. The formula is `20 * diff * diff` where `diff` equals the difference in levels between the enemy and your warrior.
- However, if your warrior is at least one rank lower than your enemy, and at least 5 levels lower, your warrior cannot fight against an enemy that strong and must instead return `"You've been defeated"`.
- Every successful battle will also return one of three responses: `"Easy fight", "A good fight", "An intense fight"`. Return `"Easy fight"` if your warrior is 2 or more levels higher than your enemy's level. Return `"A good fight"` if your warrior is either 1 level higher or equal to your enemy's level. Return `"An intense fight"` if your warrior's level is lower than the enemy's level.
Logic Examples:
- If a warrior level 1 fights an enemy level 1, they will receive 10 experience points.
- If a warrior level 1 fights an enemy level 3, they will receive 80 experience points.
- If a warrior level 5 fights an enemy level 4, they will receive 5 experience points.
- If a warrior level 3 fights an enemy level 9, they will receive 720 experience points, resulting in the warrior rising up by at least 7 levels.
- If a warrior level 8 fights an enemy level 13, they will receive 0 experience points and return `"You've been defeated"`. (Remember, difference in rank & enemy level being 5 levels higher or more must be established for this.)
- If a warrior level 6 fights an enemy level 2, they will receive 0 experience points.
Training Rules & Calculations:
- In addition to earning experience point from battles, warriors can also gain experience points from training.
- Training will accept an array of three elements (except in java where you'll get 3 separated arguments): the description, the experience points your warrior earns, and the minimum level requirement.
- If the warrior's level meets the minimum level requirement, the warrior will receive the experience points from it and store the description of the training. It should end up returning that description as well.
- If the warrior's level does not meet the minimum level requirement, the warrior doesn not receive the experience points and description and instead returns `"Not strong enough"`, without any archiving of the result.
Code Examples:
```python
bruce_lee = Warrior()
bruce_lee.level # => 1
bruce_lee.experience # => 100
bruce_lee.rank # => "Pushover"
bruce_lee.achievements # => []
bruce_lee.training(["Defeated Chuck Norris", 9000, 1]) # => "Defeated Chuck Norris"
bruce_lee.experience # => 9100
bruce_lee.level # => 91
bruce_lee.rank # => "Master"
bruce_lee.battle(90) # => "A good fight"
bruce_lee.experience # => 9105
bruce_lee.achievements # => ["Defeated Chuck Norris"]
```
|
class Warrior(object):
MAX_LVL = 100
MAX_XPS = 10000
LVL_XP_RATIO = 100
RANKS = ["", "Pushover", "Novice", "Fighter", "Warrior", "Veteran", "Sage", "Elite", "Conqueror", "Champion", "Master", "Greatest"]
DEF_RET_ACHIEV = "Not strong enough"
INVALID_BATTLE = "Invalid level"
FAILED_BATTLE = "You've been defeated"
STR_BATTLE = ["A good fight", "An intense fight", "Easy fight"]
def __init__(self): self.xps, self.achiev = self.LVL_XP_RATIO, []
@property
def level(self): return self.xps // self.LVL_XP_RATIO
@property
def rank(self): return self.RANKS[self.getRank(self.xps)]
@property
def experience(self): return self.xps
@property
def achievements(self): return self.achiev[:]
def getRank(self,xps): return xps//1000 + 1
def updateXps(self,xp): self.xps = min( self.xps+xp, self.MAX_XPS )
def battle(self, oLvl):
diff = oLvl - self.level
if not (1 <= oLvl <= self.MAX_LVL):
return self.INVALID_BATTLE
if diff >= 5 and self.getRank(self.xps) < self.getRank(oLvl*self.LVL_XP_RATIO):
return self.FAILED_BATTLE
xpGain = 20 * diff**2 if diff > 0 else max(0, 10+5*diff)
iRet = (diff>0)-(diff<0) if diff != -1 else 0
self.updateXps(xpGain)
return self.STR_BATTLE[iRet]
def training(self, event):
ach, xpGain, minLvl = event
if self.level < minLvl: return self.DEF_RET_ACHIEV
self.updateXps(xpGain)
self.achiev.append(ach)
return ach
|
class Warrior(object):
MAX_LVL = 100
MAX_XPS = 10000
LVL_XP_RATIO = 100
RANKS = ["", "Pushover", "Novice", "Fighter", "Warrior", "Veteran", "Sage", "Elite", "Conqueror", "Champion", "Master", "Greatest"]
DEF_RET_ACHIEV = "Not strong enough"
INVALID_BATTLE = "Invalid level"
FAILED_BATTLE = "You've been defeated"
STR_BATTLE = ["A good fight", "An intense fight", "Easy fight"]
def __init__(self): self.xps, self.achiev = self.LVL_XP_RATIO, []
@property
def level(self): return self.xps // self.LVL_XP_RATIO
@property
def rank(self): return self.RANKS[self.getRank(self.xps)]
@property
def experience(self): return self.xps
@property
def achievements(self): return self.achiev[:]
def getRank(self,xps): return xps//1000 + 1
def updateXps(self,xp): self.xps = min( self.xps+xp, self.MAX_XPS )
def battle(self, oLvl):
diff = oLvl - self.level
if not (1 <= oLvl <= self.MAX_LVL):
return self.INVALID_BATTLE
if diff >= 5 and self.getRank(self.xps) < self.getRank(oLvl*self.LVL_XP_RATIO):
return self.FAILED_BATTLE
xpGain = 20 * diff**2 if diff > 0 else max(0, 10+5*diff)
iRet = (diff>0)-(diff<0) if diff != -1 else 0
self.updateXps(xpGain)
return self.STR_BATTLE[iRet]
def training(self, event):
ach, xpGain, minLvl = event
if self.level < minLvl: return self.DEF_RET_ACHIEV
self.updateXps(xpGain)
self.achiev.append(ach)
return ach
|
train
|
APPS_structured
|
Dee is lazy but she's kind and she likes to eat out at all the nice restaurants and gastropubs in town. To make paying quick and easy she uses a simple mental algorithm she's called The Fair %20 Rule. She's gotten so good she can do this in a few seconds and it always impresses her dates but she's perplexingly still single. Like you probably.
This is how she does it:
- She rounds the price `P` at the tens place e.g:
- 25 becomes 30
- 24 becomes 20
- 5 becomes 10
- 4 becomes 0
- She figures out the base tip `T` by dropping the singles place digit e.g:
- when `P = 24` she rounds to 20 drops 0 `T = 2`
- `P = 115` rounds to 120 drops 0 `T = 12`
- `P = 25` rounds to 30 drops 0 `T = 3`
- `P = 5` rounds to 10 drops 0 `T = 1`
- `P = 4` rounds to 0 `T = 0`
- She then applies a 3 point satisfaction rating `R` to `T` i.e:
- When she's satisfied: `R = 1` and she'll add 1 to `T`
- Unsatisfied: `R = 0` and she'll subtract 1 from `T`
- Appalled: `R = -1` she'll divide `T` by 2, **rounds down** and subtracts 1
## Your Task
Implement a method `calc_tip` that takes two integer arguments for price `p`
where `1 <= p <= 1000` and a rating `r` which is one of `-1, 0, 1`.
The return value `T` should be a non negative integer.
*Note: each step should be done in the order listed.*
Dee always politely smiles and says "Thank you" on her way out. Dee is nice. Be like Dee.
|
def calc_tip(p, r):
t = round(p/10 + .00000001)*10 /10
return max(0,t+1 if r==1 else t-1 if r==0 else t//2-1)
|
def calc_tip(p, r):
t = round(p/10 + .00000001)*10 /10
return max(0,t+1 if r==1 else t-1 if r==0 else t//2-1)
|
train
|
APPS_structured
|
You are given an array of integers. Vasya can permute (change order) its integers. He wants to do it so that as many as possible integers will become on a place where a smaller integer used to stand. Help Vasya find the maximal number of such integers.
For instance, if we are given an array $[10, 20, 30, 40]$, we can permute it so that it becomes $[20, 40, 10, 30]$. Then on the first and the second positions the integers became larger ($20>10$, $40>20$) and did not on the third and the fourth, so for this permutation, the number that Vasya wants to maximize equals $2$. Read the note for the first example, there is one more demonstrative test case.
Help Vasya to permute integers in such way that the number of positions in a new array, where integers are greater than in the original one, is maximal.
-----Input-----
The first line contains a single integer $n$ ($1 \leq n \leq 10^5$) — the length of the array.
The second line contains $n$ integers $a_1, a_2, \ldots, a_n$ ($1 \leq a_i \leq 10^9$) — the elements of the array.
-----Output-----
Print a single integer — the maximal number of the array's elements which after a permutation will stand on the position where a smaller element stood in the initial array.
-----Examples-----
Input
7
10 1 1 1 5 5 3
Output
4
Input
5
1 1 1 1 1
Output
0
-----Note-----
In the first sample, one of the best permutations is $[1, 5, 5, 3, 10, 1, 1]$. On the positions from second to fifth the elements became larger, so the answer for this permutation is 4.
In the second sample, there is no way to increase any element with a permutation, so the answer is 0.
|
from collections import *
print(int(input()) - max(Counter(map(int,input().split())).values()))
|
from collections import *
print(int(input()) - max(Counter(map(int,input().split())).values()))
|
train
|
APPS_structured
|
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)'
```
|
def repeating_fractions(num,denom):
ans = str(num / denom)
decimat_at = ans.find('.')
start = ans[decimat_at+1] # beyond the decimal
zgroup = ''
retval = ans[0:decimat_at+1]
for iii in range(decimat_at+1, len(ans)-1):
end = ans[iii+1]
if start == end:
zgroup += end
continue
elif start != end and len(zgroup) > 0:
retval += '('+zgroup[0]+')'
zgroup = ''
start = ans[iii+1]
elif start != end and len(zgroup) == 0:
retval += start
zgroup = ''
start = ans[iii+1]
else:
pass
# Tidy up
end = ans[len(ans)-1]
if zgroup == '':
retval += start
elif len(zgroup) > 1 or start == end :
retval += '('+zgroup[0]+')'
return retval
|
def repeating_fractions(num,denom):
ans = str(num / denom)
decimat_at = ans.find('.')
start = ans[decimat_at+1] # beyond the decimal
zgroup = ''
retval = ans[0:decimat_at+1]
for iii in range(decimat_at+1, len(ans)-1):
end = ans[iii+1]
if start == end:
zgroup += end
continue
elif start != end and len(zgroup) > 0:
retval += '('+zgroup[0]+')'
zgroup = ''
start = ans[iii+1]
elif start != end and len(zgroup) == 0:
retval += start
zgroup = ''
start = ans[iii+1]
else:
pass
# Tidy up
end = ans[len(ans)-1]
if zgroup == '':
retval += start
elif len(zgroup) > 1 or start == end :
retval += '('+zgroup[0]+')'
return retval
|
train
|
APPS_structured
|
*It seemed a good idea at the time...*
# Why I did it?
After a year on **Codewars** I really needed a holiday...
But not wanting to drift backwards in the honour rankings while I was away, I hatched a cunning plan!
# The Cunning Plan
So I borrowed my friend's "Clone Machine" and cloned myself :-)
Now my clone can do my Kata solutions for me and I can relax!
Brilliant!!
Furthermore, at the end of the day my clone can re-clone herself...
Double brilliant!!
I wonder why I didn't think to do this earlier?
So as I left for the airport I gave my clone instructions to:
* do my Kata solutions for me
* feed the cat
* try to keep the house tidy and not eat too much
* sleep
* clone yourself
* repeat same next day
# The Flaw
Well, how was I supposed to know that cloned DNA is faulty?
:-(
Every time they sleep they wake up with decreased ability - they get slower... they get dumber... they are only able to solve 1 less Kata than they could the previous day.
For example, if they can solve 10 Kata today, then tomorrow they can solve only 9 Kata, then 8, 7, 6... Eventually they can't do much more than sit around all day playing video games.
And (unlike me), when the clone cannot solve any more Kata they are no longer clever enough to operate the clone machine either!
# The Return Home
I suspected something was wrong when I noticed my **Codewars** honour had stopped rising.
I made a hasty return home...
...and found 100s of clones scattered through the house. Mostly they sit harmlessly mumbling to themselves. The largest group have made a kind of nest in my loungeroom where they sit catatonic in front of the PlayStation.
The whole place needs fumigating.
The fridge and pantry are empty.
And I can't find the cat.
# Kata Task
Write a method to predict the final outcome where:
Input:
* `kata-per-day` is the number of Kata I can solve per day
Output:
* ```[number-of-clones, number-of-kata-solved-by-clones]```
|
clonewars = lambda k: [2**max(0, k-1), sum(2**max(0, i) * (k - i) for i in range(k))]
|
clonewars = lambda k: [2**max(0, k-1), sum(2**max(0, i) * (k - i) for i in range(k))]
|
train
|
APPS_structured
|
Kira likes to play with strings very much. Moreover he likes the shape of 'W' very much. He takes a string and try to make a 'W' shape out of it such that each angular point is a '#' character and each sides has same characters. He calls them W strings.
For example, the W string can be formed from "aaaaa#bb#cc#dddd" such as:
a
a d
a # d
a b c d
a b c d
# #
He also call the strings which can generate a 'W' shape (satisfying the above conditions) W strings.
More formally, a string S is a W string if and only if it satisfies the following conditions (some terms and notations are explained in Note, please see it if you cannot understand):
- The string S contains exactly 3 '#' characters. Let the indexes of all '#' be P1 < P2 < P3 (indexes are 0-origin).
- Each substring of S[0, P1−1], S[P1+1, P2−1], S[P2+1, P3−1], S[P3+1, |S|−1] contains exactly one kind of characters, where S[a, b] denotes the non-empty substring from a+1th character to b+1th character, and |S| denotes the length of string S (See Note for details).
Now, his friend Ryuk gives him a string S and asks him to find the length of the longest W string which is a subsequence of S, with only one condition that there must not be any '#' symbols between the positions of the first and the second '#' symbol he chooses, nor between the second and the third (here the "positions" we are looking at are in S), i.e. suppose the index of the '#'s he chooses to make the W string are P1, P2, P3 (in increasing order) in the original string S, then there must be no index i such that S[i] = '#' where P1 < i < P2 or P2 < i < P3.
Help Kira and he won't write your name in the Death Note.
Note:
For a given string S, let S[k] denote the k+1th character of string S, and let the index of the character S[k] be k. Let |S| denote the length of the string S. And a substring of a string S is a string S[a, b] = S[a] S[a+1] ... S[b], where 0 ≤ a ≤ b < |S|. And a subsequence of a string S is a string S[i0] S[i1] ... S[in−1], where 0 ≤ i0 < i1 < ... < in−1 < |S|.
For example, let S be the string "kira", then S[0] = 'k', S[1] = 'i', S[3] = 'a', and |S| = 4. All of S[0, 2] = "kir", S[1, 1] = "i", and S[0, 3] = "kira" are substrings of S, but "ik", "kr", and "arik" are not. All of "k", "kr", "kira", "kia" are subsequences of S, but "ik", "kk" are not.
From the above definition of W string, for example, "a#b#c#d", "aaa#yyy#aaa#yy", and "o#oo#ooo#oooo" are W string, but "a#b#c#d#e", "#a#a#a", and "aa##a#a" are not.
-----Input-----
First line of input contains an integer T, denoting the number of test cases. Then T lines follow. Each line contains a string S.
-----Output-----
Output an integer, denoting the length of the longest W string as explained before. If S has no W string as its subsequence, then output 0.
-----Constraints-----
- 1 ≤ T ≤ 100
- 1 ≤ |S| ≤ 10000 (104)
- S contains no characters other than lower English characters ('a' to 'z') and '#' (without quotes)
-----Example-----
Input:
3
aaaaa#bb#cc#dddd
acb#aab#bab#accba
abc#dda#bb#bb#aca
Output:
16
10
11
-----Explanation-----
In the first case: the whole string forms a W String.
In the second case: acb#aab#bab#accba, the longest W string is acb#aab#bab#accba
In the third case: abc#dda#bb#bb#aca, note that even though abc#dda#bb#bb#aca (boldened characters form the subsequence) is a W string of length 12, it violates Ryuk's condition that there should not be any #'s inbetween the 3 chosen # positions. One correct string of length 11 is abc#dda#bb#bb#aca
|
def frequency(s,n):
f=[[0 for i in range(26)]for j in range(n+1)]
count=0
for i in range(n):
if s[i]!="#":
f[count][ord(s[i])-97]+=1
else:
count+=1
for j in range(26):
f[count][j]=f[count-1][j]
return (f,count)
def solve(s):
n=len(s)
f,count=frequency(s,n)
if count<3:
return 0
ans=0
index=[]
for i in range(n-1,-1,-1):
if s[i]=="#":
index.append(i)
for c in range(1,count-2+1):
if index[-2]==index[-1]+1 or index[-3]==index[-2]+1:
index.pop()
continue
left=max(f[c-1])
mid1=0
mid2=0
right=0
for j in range(26):
mid1=max(mid1,f[c][j]-f[c-1][j])
mid2=max(mid2,f[c+1][j]-f[c][j])
right=max(right,f[count][j]-f[c+1][j])
if left and mid1 and mid2 and right:
ans=max(ans,left+mid1+mid2+right)
index.pop()
return ans
for _ in range(int(input())):
s=input()
ans=solve(s)
if ans:
print(ans+3)
else:
print(0)
|
def frequency(s,n):
f=[[0 for i in range(26)]for j in range(n+1)]
count=0
for i in range(n):
if s[i]!="#":
f[count][ord(s[i])-97]+=1
else:
count+=1
for j in range(26):
f[count][j]=f[count-1][j]
return (f,count)
def solve(s):
n=len(s)
f,count=frequency(s,n)
if count<3:
return 0
ans=0
index=[]
for i in range(n-1,-1,-1):
if s[i]=="#":
index.append(i)
for c in range(1,count-2+1):
if index[-2]==index[-1]+1 or index[-3]==index[-2]+1:
index.pop()
continue
left=max(f[c-1])
mid1=0
mid2=0
right=0
for j in range(26):
mid1=max(mid1,f[c][j]-f[c-1][j])
mid2=max(mid2,f[c+1][j]-f[c][j])
right=max(right,f[count][j]-f[c+1][j])
if left and mid1 and mid2 and right:
ans=max(ans,left+mid1+mid2+right)
index.pop()
return ans
for _ in range(int(input())):
s=input()
ans=solve(s)
if ans:
print(ans+3)
else:
print(0)
|
train
|
APPS_structured
|
Laura really hates people using acronyms in her office and wants to force her colleagues to remove all acronyms before emailing her. She wants you to build a system that will edit out all known acronyms or else will notify the sender if unknown acronyms are present.
Any combination of three or more letters in upper case will be considered an acronym. Acronyms will not be combined with lowercase letters, such as in the case of 'KPIs'. They will be kept isolated as a word/words within a string.
For any string:
All instances of 'KPI' must become "key performance indicators"
All instances of 'EOD' must become "the end of the day"
All instances of 'TBD' must become "to be decided"
All instances of 'WAH' must become "work at home"
All instances of 'IAM' must become "in a meeting"
All instances of 'OOO' must become "out of office"
All instances of 'NRN' must become "no reply necessary"
All instances of 'CTA' must become "call to action"
All instances of 'SWOT' must become "strengths, weaknesses, opportunities and threats"
If there are any unknown acronyms in the string, Laura wants you to return only the message:
'[acronym] is an acronym. I do not like acronyms. Please remove them from your email.'
So if the acronym in question was 'BRB', you would return the string:
'BRB is an acronym. I do not like acronyms. Please remove them from your email.'
If there is more than one unknown acronym in the string, return only the first in your answer.
If all acronyms can be replaced with full words according to the above, however, return only the altered string.
If this is the case, ensure that sentences still start with capital letters. '!' or '?' will not be used.
|
import re
def acronym_buster(message):
new_msg = message
subs = {'KPI': "key performance indicators",
'EOD': "the end of the day",
'TBD': "to be decided",
'WAH': "work at home",
'IAM': "in a meeting",
'OOO': "out of office",
'NRN': "no reply necessary",
'CTA': "call to action",
'SWOT': "strengths, weaknesses, opportunities and threats"}
for item in re.findall('(?:\w)*[A-Z]{3,}(?:\w)*', new_msg):
if item in subs:
new_msg = new_msg.replace(item, subs[item])
elif item.isupper():
return '{} is an acronym. I do not like acronyms. Please remove them from your email.'.format(item)
# Now capitalize the first "word" in each sentence
sentences = new_msg.split('. ')
return '. '.join(s[:1].upper() + s[1:] for s in sentences)
|
import re
def acronym_buster(message):
new_msg = message
subs = {'KPI': "key performance indicators",
'EOD': "the end of the day",
'TBD': "to be decided",
'WAH': "work at home",
'IAM': "in a meeting",
'OOO': "out of office",
'NRN': "no reply necessary",
'CTA': "call to action",
'SWOT': "strengths, weaknesses, opportunities and threats"}
for item in re.findall('(?:\w)*[A-Z]{3,}(?:\w)*', new_msg):
if item in subs:
new_msg = new_msg.replace(item, subs[item])
elif item.isupper():
return '{} is an acronym. I do not like acronyms. Please remove them from your email.'.format(item)
# Now capitalize the first "word" in each sentence
sentences = new_msg.split('. ')
return '. '.join(s[:1].upper() + s[1:] for s in sentences)
|
train
|
APPS_structured
|
In some ranking people collects points. The challenge is sort by points and calulate position for every person. But remember if two or more persons have same number of points, they should have same position number and sorted by name (name is unique).
For example:
Input structure:
Output should be:
|
def ranking(people):
pnt = None
res = []
for c, d in enumerate(sorted(people, key=lambda d: (-d['points'], d['name'])), 1):
if pnt != d['points']:
pnt = d['points']
pos = c
res.append(dict({'position':pos}, **d))
return res
|
def ranking(people):
pnt = None
res = []
for c, d in enumerate(sorted(people, key=lambda d: (-d['points'], d['name'])), 1):
if pnt != d['points']:
pnt = d['points']
pos = c
res.append(dict({'position':pos}, **d))
return res
|
train
|
APPS_structured
|
[Chopsticks (singular: chopstick) are short, frequently tapered sticks used in pairs of equal length, which are used as the traditional eating utensils of China, Japan, Korea and Vietnam. Originated in ancient China, they can also be found in some areas of Tibet and Nepal that are close to Han Chinese populations, as well as areas of Thailand, Laos and Burma which have significant Chinese populations. Chopsticks are most commonly made of wood, bamboo or plastic, but in China, most are made out of bamboo. Chopsticks are held in the dominant hand, between the thumb and fingers, and used to pick up pieces of food.]
Retrieved from wikipedia
Actually, the two sticks in a pair of chopsticks need not be of the same length. A pair of sticks can be used to eat as long as the difference in their length is at most D. The Chef has N sticks in which the ith stick is L[i] units long. A stick can't be part of more than one pair of chopsticks. Help the Chef in pairing up the sticks to form the maximum number of usable pairs of chopsticks.
-----Input-----
The first line contains two space-separated integers N and D. The next N lines contain one integer each, the ith line giving the value of L[i].
-----Output-----
Output a single line containing the maximum number of pairs of chopsticks the Chef can form.
-----Constraints-----
- 1 ≤ N ≤ 100,000 (10 5 )
- 0 ≤ D ≤ 1,000,000,000 (10 9 )
- 1 ≤ L[i] ≤ 1,000,000,000 (10 9 ) for all integers i from 1 to N
-----Example-----
Input:
5 2
1
3
3
9
4
Output:
2
-----Explanation-----
The 5 sticks have lengths 1, 3, 3, 9 and 4 respectively. The maximum allowed difference in the lengths of two sticks forming a pair is at most 2.
It is clear that the 4th stick (length 9) cannot be used with any other stick.
The remaining 4 sticks can can be paired as (1st and 3rd) and (2nd and 5th) to form 2 pairs of usable chopsticks.
|
# cook your dish here
n,k=input().split()
n=int(n)
k=int(k)
l=[0]*n
for x in range(n):
l[x]=int(input())
l.sort()
c=0
i=0
while i<n-1:
if l[i+1]-l[i]<=k:
i+=1
c+=1
i+=1
print(c)
|
# cook your dish here
n,k=input().split()
n=int(n)
k=int(k)
l=[0]*n
for x in range(n):
l[x]=int(input())
l.sort()
c=0
i=0
while i<n-1:
if l[i+1]-l[i]<=k:
i+=1
c+=1
i+=1
print(c)
|
train
|
APPS_structured
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.