input
stringlengths 50
13.9k
| output_program
stringlengths 5
655k
| output_answer
stringlengths 5
655k
| split
stringclasses 1
value | dataset
stringclasses 1
value |
---|---|---|---|---|
In this Kata, you will be given an array of arrays and your task will be to return the number of unique arrays that can be formed by picking exactly one element from each subarray.
For example: `solve([[1,2],[4],[5,6]]) = 4`, because it results in only `4` possiblites. They are `[1,4,5],[1,4,6],[2,4,5],[2,4,6]`.
```if:r
In R, we will use a list data structure.
So the argument for `solve` is a list of numeric vectors.
~~~
solve(list(c(1, 2), 4, c(5, 6)))
[1] 4
~~~
```
Make sure that you don't count duplicates; for example `solve([[1,2],[4,4],[5,6,6]]) = 4`, since the extra outcomes are just duplicates.
See test cases for more examples.
Good luck!
If you like this Kata, please try:
[Sum of integer combinations](https://www.codewars.com/kata/59f3178e3640cef6d90000d5)
[Sum of array singles](https://www.codewars.com/kata/59f11118a5e129e591000134) | import functools
from operator import mul
def solve(arr):
return functools.reduce(mul, (len(set(i)) for i in arr)) | import functools
from operator import mul
def solve(arr):
return functools.reduce(mul, (len(set(i)) for i in arr)) | train | APPS_structured |
=====Problem Statement=====
You are given a string and your task is to swap cases. In other words, convert all lowercase letters to uppercase letters and vice versa.
=====Example=====
Www.HackerRank.com → wWW.hACKERrANK.COM
Pythonist 2 → pYTHONIST 2
=====Input Format=====
A single line containing a string S.
=====Output Format=====
Print the modified string S. | def swap_case(s):
out = ''
for ind, let in enumerate(s):
if let.isalpha():
if let.islower():
out += s[ind].capitalize()
else:
out += s[ind].lower()
else:
out += let
return out | def swap_case(s):
out = ''
for ind, let in enumerate(s):
if let.isalpha():
if let.islower():
out += s[ind].capitalize()
else:
out += s[ind].lower()
else:
out += let
return out | train | APPS_structured |
You are given a tree with $N$ vertices (numbered $1$ through $N$) and a bag with $N$ markers. There is an integer written on each marker; each of these integers is $0$, $1$ or $2$. You must assign exactly one marker to each vertex.
Let's define the unattractiveness of the resulting tree as the maximum absolute difference of integers written on the markers in any two vertices which are connected by an edge.
Find the minimum possible unattractiveness of the resulting tree.
-----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 denoting the numbers on markers in the bag.
- Each of the next $N-1$ lines contains two space-separated integers $u$ and $v$ denoting an edge between vertices $u$ and $v$.
-----Output-----
For each test case, print a single line containing one integer — the minimum unattractiveness.
-----Constraints-----
- $1 \le T \le 30$
- $1 \le N \le 100$
- $1 \le u, v \le N$
- the graph described on the input is a tree
-----Example Input-----
3
3
0 1 1
1 2
1 3
3
0 1 2
1 2
1 3
4
2 2 2 2
1 2
1 3
3 4
-----Example Output-----
1
1
0
-----Explanation-----
Example case 1: | # cook your dish here
import numpy as np
tests = int(input())
for _ in range(tests):
n = int(input())
weights = [int(j) for j in input().split()]
edges = [[0] for _ in range(n-1)]
for i in range(n-1):
edges[i] = [int(j)-1 for j in input().split()]
vertex_set = [[] for _ in range(n)]
for i in range(n-1):
vertex_set[edges[i][0]].append(edges[i][1])
vertex_set[edges[i][1]].append(edges[i][0])
counts = [0 for _ in range(3)]
for i in range(n):
counts[weights[i]] += 1
if counts[1] == 0:
print(2 * (counts[0] != 0 and counts[2] != 0))
elif counts[1] == n:
print(0)
else:
visited = [0]
for i in range(n):
vertex = visited[i]
for v in vertex_set[vertex]:
if v not in visited:
visited.append(v)
vertex_nums = [[0] for _ in range(n)]
for i in range(n-1,-1,-1):
vertex = visited[i]
for v in vertex_set[vertex]:
if v in visited[i:]:
vertex_nums[vertex].append(sum(vertex_nums[v])+1)
for i in range(n):
vertex_nums[i].append(n-1-sum(vertex_nums[i]))
sums = np.zeros(n,dtype=bool)
sums[0] = True
for i in range(n):
new_sums = np.zeros(n,dtype=bool)
new_sums[0] = True
for num in vertex_nums[i]:
new_sums[num:n] = np.logical_or(new_sums[num:n],new_sums[:n-num])
sums = np.logical_or(sums,new_sums)
solved = False
for i in range(n):
if sums[i] and counts[0] <= i and counts[2] <= n - 1 - i:
solved = True
break
if solved or counts[1] > 1:
print(1)
else:
print(2) | # cook your dish here
import numpy as np
tests = int(input())
for _ in range(tests):
n = int(input())
weights = [int(j) for j in input().split()]
edges = [[0] for _ in range(n-1)]
for i in range(n-1):
edges[i] = [int(j)-1 for j in input().split()]
vertex_set = [[] for _ in range(n)]
for i in range(n-1):
vertex_set[edges[i][0]].append(edges[i][1])
vertex_set[edges[i][1]].append(edges[i][0])
counts = [0 for _ in range(3)]
for i in range(n):
counts[weights[i]] += 1
if counts[1] == 0:
print(2 * (counts[0] != 0 and counts[2] != 0))
elif counts[1] == n:
print(0)
else:
visited = [0]
for i in range(n):
vertex = visited[i]
for v in vertex_set[vertex]:
if v not in visited:
visited.append(v)
vertex_nums = [[0] for _ in range(n)]
for i in range(n-1,-1,-1):
vertex = visited[i]
for v in vertex_set[vertex]:
if v in visited[i:]:
vertex_nums[vertex].append(sum(vertex_nums[v])+1)
for i in range(n):
vertex_nums[i].append(n-1-sum(vertex_nums[i]))
sums = np.zeros(n,dtype=bool)
sums[0] = True
for i in range(n):
new_sums = np.zeros(n,dtype=bool)
new_sums[0] = True
for num in vertex_nums[i]:
new_sums[num:n] = np.logical_or(new_sums[num:n],new_sums[:n-num])
sums = np.logical_or(sums,new_sums)
solved = False
for i in range(n):
if sums[i] and counts[0] <= i and counts[2] <= n - 1 - i:
solved = True
break
if solved or counts[1] > 1:
print(1)
else:
print(2) | train | APPS_structured |
Polycarp plays a computer game (yet again). In this game, he fights monsters using magic spells.
There are two types of spells: fire spell of power $x$ deals $x$ damage to the monster, and lightning spell of power $y$ deals $y$ damage to the monster and doubles the damage of the next spell Polycarp casts. Each spell can be cast only once per battle, but Polycarp can cast them in any order.
For example, suppose that Polycarp knows three spells: a fire spell of power $5$, a lightning spell of power $1$, and a lightning spell of power $8$. There are $6$ ways to choose the order in which he casts the spells:
first, second, third. This order deals $5 + 1 + 2 \cdot 8 = 22$ damage; first, third, second. This order deals $5 + 8 + 2 \cdot 1 = 15$ damage; second, first, third. This order deals $1 + 2 \cdot 5 + 8 = 19$ damage; second, third, first. This order deals $1 + 2 \cdot 8 + 2 \cdot 5 = 27$ damage; third, first, second. This order deals $8 + 2 \cdot 5 + 1 = 19$ damage; third, second, first. This order deals $8 + 2 \cdot 1 + 2 \cdot 5 = 20$ damage.
Initially, Polycarp knows $0$ spells. His spell set changes $n$ times, each time he either learns a new spell or forgets an already known one. After each change, calculate the maximum possible damage Polycarp may deal using the spells he knows.
-----Input-----
The first line contains one integer $n$ ($1 \le n \le 2 \cdot 10^5$) — the number of changes to the spell set.
Each of the next $n$ lines contains two integers $tp$ and $d$ ($0 \le tp_i \le 1$; $-10^9 \le d \le 10^9$; $d_i \neq 0$) — the description of the change. If $tp_i$ if equal to $0$, then Polycarp learns (or forgets) a fire spell, otherwise he learns (or forgets) a lightning spell.
If $d_i > 0$, then Polycarp learns a spell of power $d_i$. Otherwise, Polycarp forgets a spell with power $-d_i$, and it is guaranteed that he knew that spell before the change.
It is guaranteed that the powers of all spells Polycarp knows after each change are different (Polycarp never knows two spells with the same power).
-----Output-----
After each change, print the maximum damage Polycarp can deal with his current set of spells.
-----Example-----
Input
6
1 5
0 10
1 -5
0 5
1 11
0 -10
Output
5
25
10
15
36
21 | class BIT():
def __init__(self,n):
self.BIT=[0]*(n+1)
self.num=n
def query(self,idx):
res_sum = 0
while idx > 0:
res_sum += self.BIT[idx]
idx -= idx&(-idx)
return res_sum
#Ai += x O(logN)
def update(self,idx,x):
while idx <= self.num:
self.BIT[idx] += x
idx += idx&(-idx)
return
import sys,heapq,random
input=sys.stdin.readline
n=int(input())
spell=[tuple(map(int,input().split())) for i in range(n)]
S=set([])
for i in range(n):
S.add(abs(spell[i][1]))
S=list(S)
S.sort(reverse=True)
comp={i:e+1 for e,i in enumerate(S)}
N=len(S)
x_exist=BIT(N)
y_exist=BIT(N)
power=BIT(N)
X,Y,S=0,0,0
Xmax=[]
Ymin=[]
x_data=[0]*(N+1)
y_data=[0]*(N+1)
for i in range(n):
t,d=spell[i]
S+=d
if d<0:
id=comp[-d]
if t==0:
X-=1
x_exist.update(id,-1)
power.update(id,d)
x_data[id]-=1
else:
Y-=1
y_exist.update(id,-1)
power.update(id,d)
y_data[id]-=1
else:
id=comp[d]
if t==0:
X+=1
x_exist.update(id,1)
power.update(id,d)
heapq.heappush(Xmax,-d)
x_data[id]+=1
else:
Y+=1
y_exist.update(id,1)
power.update(id,d)
heapq.heappush(Ymin,d)
y_data[id]+=1
if X==0:
if Y==0:
print(0)
else:
while not y_data[comp[Ymin[0]]]:
heapq.heappop(Ymin)
print(2*S-Ymin[0])
else:
if Y==0:
print(S)
else:
start=0
end=N
while end-start>1:
test=(end+start)//2
if x_exist.query(test)+y_exist.query(test)<=Y:
start=test
else:
end=test
if y_exist.query(start)!=Y:
print(S+power.query(start))
else:
while not y_data[comp[Ymin[0]]]:
heapq.heappop(Ymin)
while not x_data[comp[-Xmax[0]]]:
heapq.heappop(Xmax)
print(S+power.query(start)-Ymin[0]-Xmax[0])
| class BIT():
def __init__(self,n):
self.BIT=[0]*(n+1)
self.num=n
def query(self,idx):
res_sum = 0
while idx > 0:
res_sum += self.BIT[idx]
idx -= idx&(-idx)
return res_sum
#Ai += x O(logN)
def update(self,idx,x):
while idx <= self.num:
self.BIT[idx] += x
idx += idx&(-idx)
return
import sys,heapq,random
input=sys.stdin.readline
n=int(input())
spell=[tuple(map(int,input().split())) for i in range(n)]
S=set([])
for i in range(n):
S.add(abs(spell[i][1]))
S=list(S)
S.sort(reverse=True)
comp={i:e+1 for e,i in enumerate(S)}
N=len(S)
x_exist=BIT(N)
y_exist=BIT(N)
power=BIT(N)
X,Y,S=0,0,0
Xmax=[]
Ymin=[]
x_data=[0]*(N+1)
y_data=[0]*(N+1)
for i in range(n):
t,d=spell[i]
S+=d
if d<0:
id=comp[-d]
if t==0:
X-=1
x_exist.update(id,-1)
power.update(id,d)
x_data[id]-=1
else:
Y-=1
y_exist.update(id,-1)
power.update(id,d)
y_data[id]-=1
else:
id=comp[d]
if t==0:
X+=1
x_exist.update(id,1)
power.update(id,d)
heapq.heappush(Xmax,-d)
x_data[id]+=1
else:
Y+=1
y_exist.update(id,1)
power.update(id,d)
heapq.heappush(Ymin,d)
y_data[id]+=1
if X==0:
if Y==0:
print(0)
else:
while not y_data[comp[Ymin[0]]]:
heapq.heappop(Ymin)
print(2*S-Ymin[0])
else:
if Y==0:
print(S)
else:
start=0
end=N
while end-start>1:
test=(end+start)//2
if x_exist.query(test)+y_exist.query(test)<=Y:
start=test
else:
end=test
if y_exist.query(start)!=Y:
print(S+power.query(start))
else:
while not y_data[comp[Ymin[0]]]:
heapq.heappop(Ymin)
while not x_data[comp[-Xmax[0]]]:
heapq.heappop(Xmax)
print(S+power.query(start)-Ymin[0]-Xmax[0])
| train | APPS_structured |
Zookeeper is buying a carton of fruit to feed his pet wabbit. The fruits are a sequence of apples and oranges, which is represented by a binary string $s_1s_2\ldots s_n$ of length $n$. $1$ represents an apple and $0$ represents an orange.
Since wabbit is allergic to eating oranges, Zookeeper would like to find the longest contiguous sequence of apples. Let $f(l,r)$ be the longest contiguous sequence of apples in the substring $s_{l}s_{l+1}\ldots s_{r}$.
Help Zookeeper find $\sum_{l=1}^{n} \sum_{r=l}^{n} f(l,r)$, or the sum of $f$ across all substrings.
-----Input-----
The first line contains a single integer $n$ $(1 \leq n \leq 5 \cdot 10^5)$.
The next line contains a binary string $s$ of length $n$ $(s_i \in \{0,1\})$
-----Output-----
Print a single integer: $\sum_{l=1}^{n} \sum_{r=l}^{n} f(l,r)$.
-----Examples-----
Input
4
0110
Output
12
Input
7
1101001
Output
30
Input
12
011100011100
Output
156
-----Note-----
In the first test, there are ten substrings. The list of them (we let $[l,r]$ be the substring $s_l s_{l+1} \ldots s_r$): $[1,1]$: 0 $[1,2]$: 01 $[1,3]$: 011 $[1,4]$: 0110 $[2,2]$: 1 $[2,3]$: 11 $[2,4]$: 110 $[3,3]$: 1 $[3,4]$: 10 $[4,4]$: 0
The lengths of the longest contiguous sequence of ones in each of these ten substrings are $0,1,2,2,1,2,2,1,1,0$ respectively. Hence, the answer is $0+1+2+2+1+2+2+1+1+0 = 12$. |
from sys import stdin
import sys
import heapq
def bitadd(a,w,bit):
x = a+1
while x <= (len(bit)-1):
bit[x] += w
x += x & (-1 * x)
def bitsum(a,bit):
ret = 0
x = a+1
while x > 0:
ret += bit[x]
x -= x & (-1 * x)
return ret
n = int(stdin.readline())
s = stdin.readline()[:-1]
bit = [0] * (n+10)
dp = [0] * (n+10)
y = 0
ans = 0
for i in range(n):
if s[i] == "0":
while y > 0:
dp[y] += 1
bitadd(y,y,bit)
y -= 1
dp[0] += 1
else:
bitadd(y,-1*dp[y]*y,bit)
bitadd(y+1,-1*dp[y+1]*(y+1),bit)
dp[y+1] += dp[y]
dp[y] = 0
y += 1
bitadd(y,dp[y]*y,bit)
now = bitsum(i,bit) + (1+y)*y//2
#print (bitsum(i,bit),(1+y)*y//2,dp)
ans += now
print (ans) |
from sys import stdin
import sys
import heapq
def bitadd(a,w,bit):
x = a+1
while x <= (len(bit)-1):
bit[x] += w
x += x & (-1 * x)
def bitsum(a,bit):
ret = 0
x = a+1
while x > 0:
ret += bit[x]
x -= x & (-1 * x)
return ret
n = int(stdin.readline())
s = stdin.readline()[:-1]
bit = [0] * (n+10)
dp = [0] * (n+10)
y = 0
ans = 0
for i in range(n):
if s[i] == "0":
while y > 0:
dp[y] += 1
bitadd(y,y,bit)
y -= 1
dp[0] += 1
else:
bitadd(y,-1*dp[y]*y,bit)
bitadd(y+1,-1*dp[y+1]*(y+1),bit)
dp[y+1] += dp[y]
dp[y] = 0
y += 1
bitadd(y,dp[y]*y,bit)
now = bitsum(i,bit) + (1+y)*y//2
#print (bitsum(i,bit),(1+y)*y//2,dp)
ans += now
print (ans) | train | APPS_structured |
The chef has a recipe he wishes to use for his guests,
but the recipe will make far more food than he can serve to the guests.
The chef therefore would like to make a reduced version of the recipe which has the same ratios of ingredients, but makes less food.
The chef, however, does not like fractions.
The original recipe contains only whole numbers of ingredients,
and the chef wants the reduced recipe to only contain whole numbers of ingredients as well.
Help the chef determine how much of each ingredient to use in order to make as little food as possible.
-----Input-----
Input will begin with an integer T, the number of test cases.
Each test case consists of a single line.
The line begins with a positive integer N, the number of ingredients.
N integers follow, each indicating the quantity of a particular ingredient that is used.
-----Output-----
For each test case, output exactly N space-separated integers on a line,
giving the quantity of each ingredient that the chef should use in order to make as little food as possible.
-----Sample Input-----
3
2 4 4
3 2 3 4
4 3 15 9 6
-----Sample Output-----
1 1
2 3 4
1 5 3 2
-----Constraints-----
T≤100
2≤N≤50
All ingredient quantities are between 1 and 1000, inclusive. | #! /usr/bin/env python
from sys import stdin
from functools import reduce
def gcd(a,b):
while b!=0:
a,b=b,a%b
return a
def gcdl(l):
return reduce(gcd, l[1:],l[0])
def __starting_point():
T=int(stdin.readline())
for case in range(T):
numbers=list(map(int, stdin.readline().split()[1:]))
g=gcdl(numbers)
numbers=[n/g for n in numbers]
print(" ".join([str(x) for x in numbers]))
__starting_point() | #! /usr/bin/env python
from sys import stdin
from functools import reduce
def gcd(a,b):
while b!=0:
a,b=b,a%b
return a
def gcdl(l):
return reduce(gcd, l[1:],l[0])
def __starting_point():
T=int(stdin.readline())
for case in range(T):
numbers=list(map(int, stdin.readline().split()[1:]))
g=gcdl(numbers)
numbers=[n/g for n in numbers]
print(" ".join([str(x) for x in numbers]))
__starting_point() | train | APPS_structured |
Yesterday, Chef found $K$ empty boxes in the cooler and decided to fill them with apples. He ordered $N$ apples, where $N$ is a multiple of $K$. Now, he just needs to hire someone who will distribute the apples into the boxes with professional passion.
Only two candidates passed all the interviews for the box filling job. In one minute, each candidate can put $K$ apples into boxes, but they do it in different ways: the first candidate puts exactly one apple in each box, while the second one chooses a random box with the smallest number of apples and puts $K$ apples in it.
Chef is wondering if the final distribution of apples can even depend on which candidate he hires. Can you answer that question?
Note: The boxes are distinguishable (labeled), while the apples are not. Therefore, two distributions of apples are different if there is a box such that the number of apples in it when the first candidate finishes working can be different from the number of apples in it when the second candidate finishes working.
-----Input-----
- The first line of the input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows.
- The first and only line of each test case contains two space-separated integers $N$ and $K$.
-----Output-----
For each test case, print a single line containing the string "YES" if the final distributions of apples can be different or "NO" if they will be the same (without quotes).
-----Constraints-----
- $1 \le T \le 250$
- $1 \le N, K \le 10^{18}$
- $N$ is divisible by $K$
-----Subtasks-----
Subtask #1 (30 points): $1 \le N, K \le 10^5$
Subtask #2 (70 points): original constraints
-----Example Input-----
3
5 1
4 2
10 10
-----Example Output-----
NO
NO
YES
-----Explanation-----
Example case 1: No matter who is hired, all apples will be in the only box at the end.
Example case 2: At the end, there will be two apples in each box.
Example case 3: If we hire the first candidate, there will be one apple in each box, but if we hire the second one, there will be $10$ apples in one box and none in all other boxes. | for _ in range(int(input())):
n, k = list(map(int, input().split()))
if n//k%k == 0:
print("NO")
else:
print("YES") | for _ in range(int(input())):
n, k = list(map(int, input().split()))
if n//k%k == 0:
print("NO")
else:
print("YES") | train | APPS_structured |
Chef has a rectangular matrix A of nxm integers. Rows are numbered by integers from 1 to n from top to bottom, columns - from 1 to m from left to right. Ai, j denotes the j-th integer of the i-th row.
Chef wants you to guess his matrix. To guess integers, you can ask Chef questions of next type: "How many integers from submatrix iL, iR, jL, jR are grater than or equal to x and less than or equal to y?". By submatrix iL, iR, jL, jR we mean all elements Ai, j for all iL ≤ i ≤ iR and jL ≤ j ≤ jR.
Also Chef can answer not more than C questions of next type: "What is the sum of integers from submatrix iL, iR, jL, jR?"
As soon as you think you know the Chefs matrix, you can stop asking questions and tell to the Chef your variant of the matrix. Please see "Scoring" part to understand how your solution will be evaluated.
-----Input-----
The first line of the input contains three space-separated integers n, m and C denoting the sizes of the matrix and the maximum number of the second-type questions. After that the judge will answer your questions and evaluate the resuts. Read more about that in the "Interaction with the judge" part of the statement.
-----Interaction with the judge-----
To ask a first-type question you should print to the standard output one line containing seven space-separated integers 1 iL iR jL jR x y. To ask a second-type question you should print one line containing five space-separated integers 2 iL iR jL jR. After that you should read from the standard input one integer - answer to the question. To end the game you should print 3 and starting from next line print n lines, each of them contains m space-separated integers - your variant of the matrix A. After that your program must stop. Remember to flush the output after every line you print.
-----Constraints-----
- 1 ≤ n, m ≤ 2.5 * 105
- 1 ≤ n * m ≤ 2.5 * 105
- 103 ≤ C ≤ 104
- 1 ≤ Ai, j ≤ 50
- 1 ≤ iL ≤ iR ≤ n
- 1 ≤ jL ≤ jR ≤ m
- 1 ≤ x ≤ y ≤ 50
- 0 ≤ number of asked questions ≤ 5 * 105
- 1 ≤ Bi, j ≤ 50
- 1 ≤ a1, a2, a3 ≤ 10
----- Scoring -----
Let B will be the matrix you output and diff = ∑ |Ai, j - Bi, j| for all 1 ≤ i ≤ n, 1 ≤ j ≤ m. The number of questions you asked is questions. The number of integers, you correctly guessed is correct(i. e. the number of elements i, j such that Ai, j = Bi, j).
The score for each test case will be: score = a1 * questions + a2 * diff + a3 * (n * m - correct).
Your goal is to minimize this score.
Your total score for the problem will be the sum of scores on all the test cases.
-----Example-----
Input:
3 3 10
4
0
3
1
6
Output:
1 1 2 1 2 1 3
1 3 3 1 3 1 1
1 3 3 1 3 2 2
1 1 2 3 3 1 1
2 3 3 1 3
3
2 2 1
2 2 1
2 2 2
-----Explanation-----
[1, 2, 3]
A = [3, 2, 1]
[2, 2, 2]
For this test case a1 = 1, a2 = 1 and a3 = 1.
The score for this test case will be 1 * 5 + 1 * 4 + 1 * (9 - 6) = 12.
----- Test data generation -----
There will be four types of the test files.
- Type #1: n = 10, m = 25000
- Type #2: n = 100, m = 2500
- Type #3: n = 250, m = 1000
- Type #4: n = 500, m = 500
There will be 5 test files of each type. During the contest, you will be shown the score for only one test file of each type.
All elements of matrix A are randomly chosen.
For each test case C is randomly chosen from interval [103 .. 104].
For each test case values a1, a2 and a3 are manually chosen. | import sys,numpy as np
def find_nearest(array,value):
idx = (np.abs(array-value)).argmin()
return array[idx]
n,m,c=list(map(int,input().split()))
max=[]
li=[]
options=[]
for i in range(1,51):
print(1,1,n,1,m,i,i)
sys.stdout.flush()
ans=int(input())
max.append(ans)
li.append(ans)
max.sort()
max=max[::-1]
for i in range(50):
options.append(li.index(max[i])+1)
array=np.array(options)
k=1
li=[]
query=m
rem=0
if c<=query:
query=c
rem=m-query
for i in range(query):
print(2,1,n,k,k+1-1)
sys.stdout.flush()
sum=int(input())
li.append((sum/(n)))
#print m,k
if k>=m:break
k+=1
print(3)
for i in range(n):
for j in range(query):
print(str(find_nearest(array,li[j])), end=' ')
print(" ".join([str(options[0])]*rem))
| import sys,numpy as np
def find_nearest(array,value):
idx = (np.abs(array-value)).argmin()
return array[idx]
n,m,c=list(map(int,input().split()))
max=[]
li=[]
options=[]
for i in range(1,51):
print(1,1,n,1,m,i,i)
sys.stdout.flush()
ans=int(input())
max.append(ans)
li.append(ans)
max.sort()
max=max[::-1]
for i in range(50):
options.append(li.index(max[i])+1)
array=np.array(options)
k=1
li=[]
query=m
rem=0
if c<=query:
query=c
rem=m-query
for i in range(query):
print(2,1,n,k,k+1-1)
sys.stdout.flush()
sum=int(input())
li.append((sum/(n)))
#print m,k
if k>=m:break
k+=1
print(3)
for i in range(n):
for j in range(query):
print(str(find_nearest(array,li[j])), end=' ')
print(" ".join([str(options[0])]*rem))
| train | APPS_structured |
After a wonderful evening in the restaurant the time to go home came. Leha as a true gentlemen suggested Noora to give her a lift. Certainly the girl agreed with pleasure. Suddenly one problem appeared: Leha cannot find his car on a huge parking near the restaurant. So he decided to turn to the watchman for help.
Formally the parking can be represented as a matrix 10^9 × 10^9. There is exactly one car in every cell of the matrix. All cars have their own machine numbers represented as a positive integer. Let's index the columns of the matrix by integers from 1 to 10^9 from left to right and the rows by integers from 1 to 10^9 from top to bottom. By coincidence it turned out, that for every cell (x, y) the number of the car, which stands in this cell, is equal to the minimum positive integer, which can't be found in the cells (i, y) and (x, j), 1 ≤ i < x, 1 ≤ j < y. $\left. \begin{array}{|l|l|l|l|l|} \hline 1 & {2} & {3} & {4} & {5} \\ \hline 2 & {1} & {4} & {3} & {6} \\ \hline 3 & {4} & {1} & {2} & {7} \\ \hline 4 & {3} & {2} & {1} & {8} \\ \hline 5 & {6} & {7} & {8} & {1} \\ \hline \end{array} \right.$ The upper left fragment 5 × 5 of the parking
Leha wants to ask the watchman q requests, which can help him to find his car. Every request is represented as five integers x_1, y_1, x_2, y_2, k. The watchman have to consider all cells (x, y) of the matrix, such that x_1 ≤ x ≤ x_2 and y_1 ≤ y ≤ y_2, and if the number of the car in cell (x, y) does not exceed k, increase the answer to the request by the number of the car in cell (x, y). For each request Leha asks the watchman to tell him the resulting sum. Due to the fact that the sum can turn out to be quite large, hacker asks to calculate it modulo 10^9 + 7.
However the requests seem to be impracticable for the watchman. Help the watchman to answer all Leha's requests.
-----Input-----
The first line contains one integer q (1 ≤ q ≤ 10^4) — the number of Leha's requests.
The next q lines contain five integers x_1, y_1, x_2, y_2, k (1 ≤ x_1 ≤ x_2 ≤ 10^9, 1 ≤ y_1 ≤ y_2 ≤ 10^9, 1 ≤ k ≤ 2·10^9) — parameters of Leha's requests.
-----Output-----
Print exactly q lines — in the first line print the answer to the first request, in the second — the answer to the second request and so on.
-----Example-----
Input
4
1 1 1 1 1
3 2 5 4 5
1 1 5 5 10000
1 4 2 5 2
Output
1
13
93
0
-----Note-----
Let's analyze all the requests. In each case the requested submatrix is highlighted in blue.
In the first request (k = 1) Leha asks only about the upper left parking cell. In this cell the car's number is 1. Consequentally the answer is 1.
$\left. \begin{array}{|l|l|l|l|l|} \hline 1 & {2} & {3} & {4} & {5} \\ \hline 2 & {1} & {4} & {3} & {6} \\ \hline 3 & {4} & {1} & {2} & {7} \\ \hline 4 & {3} & {2} & {1} & {8} \\ \hline 5 & {6} & {7} & {8} & {1} \\ \hline \end{array} \right.$
In the second request (k = 5) suitable numbers are 4, 1, 2, 3, 2, 1. Consequentally the answer is 4 + 1 + 2 + 3 + 2 + 1 = 13.
$\left. \begin{array}{|l|l|l|l|l|} \hline 1 & {2} & {3} & {4} & {5} \\ \hline 2 & {1} & {4} & {3} & {6} \\ \hline 3 & {4} & {1} & {2} & {7} \\ \hline 4 & {3} & {2} & {1} & {8} \\ \hline 5 & {6} & {7} & {8} & {1} \\ \hline \end{array} \right.$
In the third request (k = 10000) Leha asks about the upper left frament 5 × 5 of the parking. Since k is big enough, the answer is equal to 93.
$\left. \begin{array}{|l|l|l|l|l|} \hline 1 & {2} & {3} & {4} & {5} \\ \hline 2 & {1} & {4} & {3} & {6} \\ \hline 3 & {4} & {1} & {2} & {7} \\ \hline 4 & {3} & {2} & {1} & {8} \\ \hline 5 & {6} & {7} & {8} & {1} \\ \hline \end{array} \right.$
In the last request (k = 2) none of the cur's numbers are suitable, so the answer is 0.
$\left. \begin{array}{|l|l|l|l|l|} \hline 1 & {2} & {3} & {4} & {5} \\ \hline 2 & {1} & {4} & {3} & {6} \\ \hline 3 & {4} & {1} & {2} & {7} \\ \hline 4 & {3} & {2} & {1} & {8} \\ \hline 5 & {6} & {7} & {8} & {1} \\ \hline \end{array} \right.$ | mod = 1000000007
def sum(x, y, k, add) :
if k < add : return 0
up = x + add
if up > k : up = k
add = add + 1
return y * ( ( (add + up) * (up - add + 1) // 2 ) % mod ) % mod
def solve(x, y, k, add = 0) :
if x == 0 or y == 0 : return 0
if x > y :
x, y = y, x
pw = 1
while (pw << 1) <= y :
pw <<= 1
if pw <= x :
return ( sum(pw, pw, k, add)\
+ sum(pw, x + y - pw - pw, k, add + pw)\
+ solve(x - pw, y - pw, k, add) ) % mod
else :
return ( sum(pw, x, k, add)\
+ solve(x, y - pw, k, add + pw) ) % mod
q = int(input())
for i in range(0, q) :
x1, y1, x2, y2, k = list(map(int, input().split()))
ans = ( solve(x2, y2, k)\
- solve(x1 - 1, y2, k)\
- solve(x2, y1 - 1, k)\
+ solve(x1 - 1, y1 - 1, k) ) % mod
if ans < 0 : ans += mod
print(ans)
| mod = 1000000007
def sum(x, y, k, add) :
if k < add : return 0
up = x + add
if up > k : up = k
add = add + 1
return y * ( ( (add + up) * (up - add + 1) // 2 ) % mod ) % mod
def solve(x, y, k, add = 0) :
if x == 0 or y == 0 : return 0
if x > y :
x, y = y, x
pw = 1
while (pw << 1) <= y :
pw <<= 1
if pw <= x :
return ( sum(pw, pw, k, add)\
+ sum(pw, x + y - pw - pw, k, add + pw)\
+ solve(x - pw, y - pw, k, add) ) % mod
else :
return ( sum(pw, x, k, add)\
+ solve(x, y - pw, k, add + pw) ) % mod
q = int(input())
for i in range(0, q) :
x1, y1, x2, y2, k = list(map(int, input().split()))
ans = ( solve(x2, y2, k)\
- solve(x1 - 1, y2, k)\
- solve(x2, y1 - 1, k)\
+ solve(x1 - 1, y1 - 1, k) ) % mod
if ans < 0 : ans += mod
print(ans)
| train | APPS_structured |
A [Power Law](https://en.wikipedia.org/wiki/Power_law) distribution occurs whenever "a relative change in one quantity results in a proportional relative change in the other quantity." For example, if *y* = 120 when *x* = 1 and *y* = 60 when *x* = 2 (i.e. *y* halves whenever *x* doubles) then when *x* = 4, *y* = 30 and when *x* = 8, *y* = 15.
Therefore, if I give you any pair of co-ordinates (x1,y1) and (x2,y2) in a power law distribution, you can plot the entire rest of the distribution and tell me the value of *y* for any other value of *x*.
Given a pair of co-ordinates (x1,y1) and (x2,y2) and another x co-ordinate *x3*, return the value of *y3*
```
powerLaw(x1y1, x2y2, x3)
e.g. powerLaw([1,120], [2,60], 4)
- when x = 1, y = 120
- when x = 2, y = 60
- therefore whenever x doubles, y halves
- therefore when x = 4, y = 60 * 0.5
- therfore solution = 30
```
(x1,y1) and (x2,y2) will be given as arrays. Answer should be to the nearest integer, but random tests will give you leeway of 1% of the reference solution to account for possible discrepancies from different methods. | import math
def power_law(x1y1, x2y2, x3):
x1=x1y1[0]
y1=x1y1[1]
x2=x2y2[0]
y2=x2y2[1]
x=x2/x1
y=y2/y1
if x1==x2: return y2
return round(y1*y**(math.log(x3/x1)/math.log(x))) | import math
def power_law(x1y1, x2y2, x3):
x1=x1y1[0]
y1=x1y1[1]
x2=x2y2[0]
y2=x2y2[1]
x=x2/x1
y=y2/y1
if x1==x2: return y2
return round(y1*y**(math.log(x3/x1)/math.log(x))) | train | APPS_structured |
In input string ```word```(1 word):
* replace the vowel with the nearest left consonant.
* replace the consonant with the nearest right vowel.
P.S. To complete this task imagine the alphabet is a circle (connect the first and last element of the array in the mind). For example, 'a' replace with 'z', 'y' with 'a', etc.(see below)
For example:
```
'codewars' => 'enedazuu'
'cat' => 'ezu'
'abcdtuvwxyz' => 'zeeeutaaaaa'
```
It is preloaded:
```
const alphabet = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
const consonants = ['b','c','d','f','g','h','j','k','l','m','n','p','q','r','s','t','v','w','x','y','z'];
const vowels = ['a','e','i','o','u'];
```
P.S. You work with lowercase letters only. | def replace_letters(word):
return word.translate(str.maketrans('abcdefghijklmnopqrstuvwxyz','zeeediiihooooonuuuuutaaaaa'))
| def replace_letters(word):
return word.translate(str.maketrans('abcdefghijklmnopqrstuvwxyz','zeeediiihooooonuuuuutaaaaa'))
| train | APPS_structured |
You would like to get the 'weight' of a name by getting the sum of the ascii values. However you believe that capital letters should be worth more than mere lowercase letters. Spaces, numbers, or any other character are worth 0.
Normally in ascii
a has a value of 97
A has a value of 65
' ' has a value of 32
0 has a value of 48
To find who has the 'weightier' name you will switch all the values so:
A will be 97
a will be 65
' ' will be 0
0 will be 0
etc...
For example Joe will have a weight of 254, instead of 286 using normal ascii values. | import string as q
def get_weight(name):
return sum(ord(char.swapcase()) for char in name if char in q.ascii_letters) | import string as q
def get_weight(name):
return sum(ord(char.swapcase()) for char in name if char in q.ascii_letters) | train | APPS_structured |
You are an evil sorcerer at a round table with $N$ sorcerers (including yourself). You can cast $M$ spells which have distinct powers $p_1, p_2, \ldots, p_M$.
You may perform the following operation any number of times (possibly zero):
- Assign a living sorcerer to each positive integer cyclically to your left starting from yourself ― the closest living sorcerer to your left is assigned to $1$, the next living sorcerer to the left is assigned to $2$ and so on. Note that each living sorcerer (including yourself) is assigned to an infinite number of integers.
- Choose a spell $j$ (possibly a spell you have chosen before) and kill the living sorcerer assigned to $p_j$. You may not cast a spell to kill yourself.
What is the maximum number of sorcerers you can kill using zero or more operations?
-----Input-----
- The first line of the input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows.
- The first line of each test case contains two space-separated integers $N$ and $M$.
- The second line contains $M$ space-separated integers $p_1, p_2, \ldots, p_M$.
-----Output-----
For each test case, print a single line containing one integer ― the maximum number of sorcerers you can kill.
-----Constraints-----
- $1 \le T \le 1,000$
- $1 \le N \le 10^9$
- $1 \le M \le 3 \cdot 10^5$
- $1 \le p_i \le 10^9$ for each valid $i$
- $p_1, p_2, \ldots, p_N$ are pairwise distinct
- the sum of $M$ over all test cases does not exceed $3 \cdot 10^5$
-----Example Input-----
5
4 1
5
6 2
2 4
1 4
7 16 8 29
1000000000 1
998244353
1 1
20201220
-----Example Output-----
3
4
0
1755647
0
-----Explanation-----
Example case 1: The initial state is shown in the figure from the statement. We can first use spell $1$ and kill the $5$-th sorcerer to our left, i.e. sorcerer $2$. Now there are $3$ living sorcerers and the state is as shown in the following figure:
We can use spell $1$ again and kill the current $5$-th living sorcerer to our left, i.e. sorcerer $4$. Now there are $2$ living sorcerers and the state is:
Finally, we can use spell $1$ again and kill the only other living sorcerer, i.e. sorcerer $3$. Now, none of the other sorcerers are alive. As we cannot cast a spell to kill ourselves, we cannot improve the answer any further.
Example case 2: We can perform $4$ operations using the spell $p_1 = 2$ each time. We can also instead use $p_2 = 4$ in the first two operations and $p_1 = 2$ in the last two operations. Note that there may be multiple valid sequences of operations that lead to the best answer.
Example case 3: We cannot perform any operations using any of the given spells, so we are unable to kill any sorcerers.
Example case 4: We can perform $1,755,647$ operations, each of them using the spell $p_1 = 998,244,353$. | # cook your dish here
def _gcd(a,b):
while(b!=0):
a,b=b,a%b
return a
def __gcd(mp):
if(len(mp)==1):
return mp[0]
gcd=_gcd(mp[0],mp[1])
for i in range(2,len(mp)):
gcd=_gcd(gcd,mp[i])
return gcd
def factors(hcf):
if(hcf==0):
return [1]
factor_list=[]
for i in range(1,int(hcf**(0.5))+1):
if(hcf%i==0):
factor_list.append(i)
factor_list.append(hcf//i)
return factor_list
t=int(input())
for _ in range(t):
n,m=map(int,input().split())
mp=list(map(int,input().split()))
hcf=0
if(m==1):
hcf=mp[0]
elif(m>1):
hcf=__gcd(mp)
ans=0
factor_list=factors(hcf)
factor_list.sort(reverse=True)
for i in factor_list:
if i<=n:
ans=n-i
break
print(ans) | # cook your dish here
def _gcd(a,b):
while(b!=0):
a,b=b,a%b
return a
def __gcd(mp):
if(len(mp)==1):
return mp[0]
gcd=_gcd(mp[0],mp[1])
for i in range(2,len(mp)):
gcd=_gcd(gcd,mp[i])
return gcd
def factors(hcf):
if(hcf==0):
return [1]
factor_list=[]
for i in range(1,int(hcf**(0.5))+1):
if(hcf%i==0):
factor_list.append(i)
factor_list.append(hcf//i)
return factor_list
t=int(input())
for _ in range(t):
n,m=map(int,input().split())
mp=list(map(int,input().split()))
hcf=0
if(m==1):
hcf=mp[0]
elif(m>1):
hcf=__gcd(mp)
ans=0
factor_list=factors(hcf)
factor_list.sort(reverse=True)
for i in factor_list:
if i<=n:
ans=n-i
break
print(ans) | train | APPS_structured |
You are given an n by n ( square ) grid of characters, for example:
```python
[['m', 'y', 'e'],
['x', 'a', 'm'],
['p', 'l', 'e']]
```
You are also given a list of integers as input, for example:
```python
[1, 3, 5, 8]
```
You have to find the characters in these indexes of the grid if you think of the indexes as:
```python
[[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
```
Remember that the indexes start from one and not zero.
Then you output a string like this:
```python
"meal"
```
All inputs will be valid. | def grid_index(grid, indexes):
flat = tuple(x for e in grid for x in e)
return ''.join(flat[e-1] for e in indexes) | def grid_index(grid, indexes):
flat = tuple(x for e in grid for x in e)
return ''.join(flat[e-1] for e in indexes) | train | APPS_structured |
The purpose of this problem is to verify whether the method you are using to read input data is sufficiently fast to handle problems branded with the enormous Input/Output warning. You are expected to be able to process at least 2.5MB of input data per second at runtime.
-----Input-----
The input begins with two positive integers n k (n, k<=107). The next n lines of input contain one positive integer ti, not greater than 109, each.
-----Output-----
Write a single integer to output, denoting how many integers ti are divisible by k.
-----Example-----
Input:
7 3
1
51
966369
7
9
999996
11
Output:
4 | n,k=map(int,input().split())
ans=0
for i in range(n):
t=int(input())
if t%k==0:
ans+=1
print(ans) | n,k=map(int,input().split())
ans=0
for i in range(n):
t=int(input())
if t%k==0:
ans+=1
print(ans) | train | APPS_structured |
Lеt's create function to play cards. Our rules:
We have the preloaded `deck`:
```
deck = ['joker','2♣','3♣','4♣','5♣','6♣','7♣','8♣','9♣','10♣','J♣','Q♣','K♣','A♣',
'2♦','3♦','4♦','5♦','6♦','7♦','8♦','9♦','10♦','J♦','Q♦','K♦','A♦',
'2♥','3♥','4♥','5♥','6♥','7♥','8♥','9♥','10♥','J♥','Q♥','K♥','A♥',
'2♠','3♠','4♠','5♠','6♠','7♠','8♠','9♠','10♠','J♠','Q♠','K♠','A♠']
```
We have 3 arguments:
`card1` and `card2` - any card of our deck.
`trump` - the main suit of four ('♣', '♦', '♥', '♠').
If both cards have the same suit, the big one wins.
If the cards have different suits (and no one has trump) return 'Let's play again.'
If one card has `trump` unlike another, wins the first one.
If both cards have `trump`, the big one wins.
If `card1` wins, return 'The first card won.' and vice versa.
If the cards are equal, return 'Someone cheats.'
A few games:
```
('3♣', 'Q♣', '♦') -> 'The second card won.'
('5♥', 'A♣', '♦') -> 'Let us play again.'
('8♠', '8♠', '♣') -> 'Someone cheats.'
('2♦', 'A♠', '♦') -> 'The first card won.'
('joker', 'joker', '♦') -> 'Someone cheats.'
```
P.S. As a card you can also get the string 'joker' - it means this card always wins. | def card_game(card_1, card_2, t):
if card_1 == card_2:
return "Someone cheats."
if card_1 == 'joker':
return "The first card won."
if card_2 == 'joker':
return "The second card won."
f_val = lambda v: int(v) if v.isdigit() else 10 + ' JQKA'.index(v)
c1, t1 = f_val(card_1[:-1]), card_1[-1]
c2, t2 = f_val(card_2[:-1]), card_2[-1]
if t1 in [t, t2]:
return f'The {["first", "second"][t2 == t1 and c2 > c1]} card won.'
return "The second card won." if t2 == t else "Let us play again." | def card_game(card_1, card_2, t):
if card_1 == card_2:
return "Someone cheats."
if card_1 == 'joker':
return "The first card won."
if card_2 == 'joker':
return "The second card won."
f_val = lambda v: int(v) if v.isdigit() else 10 + ' JQKA'.index(v)
c1, t1 = f_val(card_1[:-1]), card_1[-1]
c2, t2 = f_val(card_2[:-1]), card_2[-1]
if t1 in [t, t2]:
return f'The {["first", "second"][t2 == t1 and c2 > c1]} card won.'
return "The second card won." if t2 == t else "Let us play again." | train | APPS_structured |
Complete the function/method (depending on the language) to return `true`/`True` when its argument is an array that has the same nesting structures and same corresponding length of nested arrays as the first array.
For example:
```python
# should return True
same_structure_as([ 1, 1, 1 ], [ 2, 2, 2 ] )
same_structure_as([ 1, [ 1, 1 ] ], [ 2, [ 2, 2 ] ] )
# should return False
same_structure_as([ 1, [ 1, 1 ] ], [ [ 2, 2 ], 2 ] )
same_structure_as([ 1, [ 1, 1 ] ], [ [ 2 ], 2 ] )
# should return True
same_structure_as([ [ [ ], [ ] ] ], [ [ [ ], [ ] ] ] )
# should return False
same_structure_as([ [ [ ], [ ] ] ], [ [ 1, 1 ] ] )
```
~~~if:javascript
For your convenience, there is already a function 'isArray(o)' declared and defined that returns true if its argument is an array, false otherwise.
~~~
~~~if:php
You may assume that all arrays passed in will be non-associative.
~~~ | def islist(A):
return isinstance(A, list)
def same_structure_as(original,other):
if islist(original) != islist(other):
return False
elif islist(original):
if len(original) != len(other):
return False
for i in range(len(original)):
if not same_structure_as(original[i], other[i]):
return False
return True
else:
return True | def islist(A):
return isinstance(A, list)
def same_structure_as(original,other):
if islist(original) != islist(other):
return False
elif islist(original):
if len(original) != len(other):
return False
for i in range(len(original)):
if not same_structure_as(original[i], other[i]):
return False
return True
else:
return True | train | APPS_structured |
Write a function
```python
alternate_sort(l)
```
that combines the elements of an array by sorting the elements ascending by their **absolute value** and outputs negative and non-negative integers alternatingly (starting with the negative value, if any).
E.g.
```python
alternate_sort([5, -42, 2, -3, -4, 8, -9,]) == [-3, 2, -4, 5, -9, 8, -42]
alternate_sort([5, -42, 2, -3, -4, 8, 9]) == [-3, 2, -4, 5, -42, 8, 9]
alternate_sort([5, 2, -3, -4, 8, -9]) == [-3, 2, -4, 5, -9, 8]
alternate_sort([5, 2, 9, 3, 8, 4]) == [2, 3, 4, 5, 8, 9]
``` | from itertools import chain, zip_longest
def alternate_sort(l):
return list(filter(lambda x: x is not None, chain(*zip_longest( sorted(filter(lambda x: x<0,l))[::-1],sorted(filter(lambda x: x>-1,l)))))) | from itertools import chain, zip_longest
def alternate_sort(l):
return list(filter(lambda x: x is not None, chain(*zip_longest( sorted(filter(lambda x: x<0,l))[::-1],sorted(filter(lambda x: x>-1,l)))))) | train | APPS_structured |
Given a list of prime factors, ```primesL```, and an integer, ```limit```, try to generate in order, all the numbers less than the value of ```limit```, that have **all and only** the prime factors of ```primesL```
## Example
```python
primesL = [2, 5, 7]
limit = 500
List of Numbers Under 500 Prime Factorization
___________________________________________________________
70 [2, 5, 7]
140 [2, 2, 5, 7]
280 [2, 2, 2, 5, 7]
350 [2, 5, 5, 7]
490 [2, 5, 7, 7]
```
There are ```5``` of these numbers under ```500``` and the largest one is ```490```.
## Task
For this kata you have to create the function ```count_find_num()```, that accepts two arguments: ```primesL``` and ```limit```, and returns the amount of numbers that fulfill the requirements, and the largest number under `limit`.
The example given above will be:
```python
primesL = [2, 5, 7]
limit = 500
count_find_num(primesL, val) == [5, 490]
```
If no numbers can be generated under `limit` then return an empty list:
```python
primesL = [2, 3, 47]
limit = 200
find_nums(primesL, limit) == []
```
The result should consider the limit as inclusive:
```python
primesL = [2, 3, 47]
limit = 282
find_nums(primesL, limit) == [1, 282]
```
Features of the random tests:
```
number of tests = 200
2 <= length_primesL <= 6 // length of the given prime factors array
5000 <= limit <= 1e17
2 <= prime <= 499 // for every prime in primesL
```
Enjoy! | from functools import reduce
from collections import deque
def count_find_num(primesL, limit):
q = deque()
q.append(reduce(lambda x, y: x*y, primesL))
Max, Count = 0, 0
while len(q)!=0:
if q[0] <= limit:
Count += 1
Max = max(Max, q[0])
for i in primesL:
if i * q[0] <= limit and i * q[0] not in q:
q.append(i * q[0])
q.popleft()
return [Count, Max] if Count!=0 and Max!=0 else [] | from functools import reduce
from collections import deque
def count_find_num(primesL, limit):
q = deque()
q.append(reduce(lambda x, y: x*y, primesL))
Max, Count = 0, 0
while len(q)!=0:
if q[0] <= limit:
Count += 1
Max = max(Max, q[0])
for i in primesL:
if i * q[0] <= limit and i * q[0] not in q:
q.append(i * q[0])
q.popleft()
return [Count, Max] if Count!=0 and Max!=0 else [] | train | APPS_structured |
Kim has broken in to the base, but after walking in circles, perplexed by the unintelligible base design of the JSA, he has found himself in a large, empty, and pure white, room.
The room is a grid with H∗W$H*W$ cells, divided into H$H$ rows and W$W$ columns. The cell (i,j)$(i,j)$ is at height A[i][j]$A[i][j]$. Unfortunately, his advanced sense of smell has allowed him to sense a mercury leak, probably brought in by Jishnu to end his meddling. The mercury leak has a power (which determines what height the mercury can reach before dissipating into harmless quantities) and a source cell. It spreads from cells it has already reached to other cells in the four cardinal directions: north, south, east, and west. (That is, the mercury can spread up, down, right, or left in the grid, but not diagonally.) Mercury can only spread to a cell if the cell's height is strictly less than the power value.
Unfortunately, Kim does not exactly know the starting cell or the power value of the mercury leak. However, his impressive brain has determined that it must be one of Q$Q$ (power, starting cell) combinations. For each combination, he wants to find out how many cells are dangerous for him to go to: that is, how many cells will eventually be reached by the mercury. This will help him determine a suitable cell to stay in and slowly fix the leak from above.
Can you help Kim achieve this objective?
Note: If the starting cell's height is not less than the power level, the mercury immediately dissipates. So, in this case, output 0.
-----Input:-----
- First line will contain T$T$, number of testcases. Then the testcases follow.
- The first line in each testcase contains three integers, H$H$, W$W$, and Q$Q$.
- On the 2$2$nd to (H+1)$(H+1)$th lines of each testcase: The (i+1)$(i+1)$th line contains W$W$ space-separated integers, representing the heights of the cells on the i$i$th row of the grid.
- On the (H+2)$(H+2)$th to (H+Q+1)$(H+Q+1)$th lines of each testcase: The (i+H+1)$(i+H+1)$th line contains 3 space-separated integers, r[i]$r[i]$, c[i]$c[i]$, and p[i]$p[i]$, which represents a (power, starting cell) combination. For this specific combination, the mercury leak originates on the cell (r[i],c[i])$(r[i],c[i])$ and has power p[i]$p[i]$.
-----Output:-----
For each testcase, output Q$Q$ lines, with each line containing one integer. The i$i$th line should output the number of dangerous cells, given that the leak originated on cell (r[i],c[i])$(r[i],c[i])$ with power p[i]$p[i]$, as defined in the input. Read the sample and sample explanation for more details.
-----Constraints-----
- 1≤T≤2$1 \leq T \leq 2$
- 1≤H≤1000$1 \leq H \leq 1000$
- 1≤W≤1000$1 \leq W \leq 1000$
- 1≤Q≤2∗105$1 \leq Q \leq 2*10^5$
- 1≤r[i]≤H$1 \leq r[i] \leq H$ for all i$i$
- 1≤c[i]≤W$1 \leq c[i] \leq W$ for all i$i$
- 0≤A[i][j]≤109$0 \leq A[i][j] \leq 10^9$ for all (i,j)$(i,j)$
- 0≤p[i]≤109$0 \leq p[i] \leq 10^9$ for all i$i$.
-----Subtasks-----
- 10 points : A[i][j]=$A[i][j] =$ constant k$k$ for all (i,j)$(i,j)$ (the heights of all cells are equal).
- 20 points : H=1$H=1$, Q≤1000$Q \leq 1000$.
- 30 points: r[i]=$r[i] =$ constant x$x$, c[i]=$c[i] =$ constant y$y$ for all i$i$ (the starting cell is fixed).
- 40 points: No additional constraints.
-----Sample Input:-----
1
5 5 3
4 3 9 7 2
8 6 5 2 8
1 7 3 4 3
2 2 4 5 6
9 9 9 9 9
3 4 6
3 2 5
1 4 9
-----Sample Output:-----
10
0
19
-----EXPLANATION:-----
For the first query, the cell (3,4)$(3,4)$ has height 4. The mercury can reach the following cells: (2,3)$(2,3)$, (2,4)$(2,4)$, (3,1)$(3,1)$, (3,3)$(3,3)$, (3,4)$(3,4)$, (3,5)$(3,5)$, (4,1)$(4,1)$, (4,2)$(4,2)$, (4,3)$(4,3)$, (4,4)$(4,4)$, for a total of 10. Note that it cannot reach cell (4,5)$(4,5)$ because the height (6) is equal to the power value (6).
For the second query, the cell (3,2)$(3,2)$ has height 7. Since the power value of 5 is less than or equal to the height of 7, the mercury immediately dissipates and so it reaches 0 cells.
For the third query, the mercury can reach all cells except the bottom row and the cell (1,3)$(1,3)$.
Note that (x,y)$(x,y)$ means the cell on the x$x$-th row and y$y$-th column. | def traverse(l,h,w,i,j,p):
c=0
queue=[(i,j)]
visited=[[False for i in range(w)] for i in range(h)]
visited[i][j]=True
while queue:
newq=[]
c+=len(queue)
for i in range(len(queue)):
d=queue[i]
x,y=d[0],d[1]
if x+1<h and l[x+1][y]<p and not visited[x+1][y]:
newq.append((x+1,y))
visited[x+1][y]=True
if x-1>=0 and l[x-1][y]<p and not visited[x-1][y]:
newq.append((x-1,y))
visited[x-1][y]=True
if y+1<w and l[x][y+1]<p and not visited[x][y+1]:
newq.append((x,y+1))
visited[x][y+1]=True
if y-1>-1 and l[x][y-1]<p and not visited[x][y-1]:
newq.append((x,y-1))
visited[x][y-1]=True
queue=newq
return c
for i1 in range(int(input())):
h,w,q=map(int, input().split())
l=[]
for i in range(h):
l1=list(map(int, input().split()))
l+=[l1]
for i in range(q):
i,j,p=map(int, input().split())
i-=1
j-=1
if l[i][j]>=p:
print(0)
else:
b=traverse(l,h,w,i,j,p)
print(b)
| def traverse(l,h,w,i,j,p):
c=0
queue=[(i,j)]
visited=[[False for i in range(w)] for i in range(h)]
visited[i][j]=True
while queue:
newq=[]
c+=len(queue)
for i in range(len(queue)):
d=queue[i]
x,y=d[0],d[1]
if x+1<h and l[x+1][y]<p and not visited[x+1][y]:
newq.append((x+1,y))
visited[x+1][y]=True
if x-1>=0 and l[x-1][y]<p and not visited[x-1][y]:
newq.append((x-1,y))
visited[x-1][y]=True
if y+1<w and l[x][y+1]<p and not visited[x][y+1]:
newq.append((x,y+1))
visited[x][y+1]=True
if y-1>-1 and l[x][y-1]<p and not visited[x][y-1]:
newq.append((x,y-1))
visited[x][y-1]=True
queue=newq
return c
for i1 in range(int(input())):
h,w,q=map(int, input().split())
l=[]
for i in range(h):
l1=list(map(int, input().split()))
l+=[l1]
for i in range(q):
i,j,p=map(int, input().split())
i-=1
j-=1
if l[i][j]>=p:
print(0)
else:
b=traverse(l,h,w,i,j,p)
print(b)
| train | APPS_structured |
Base on the fairy tale [Diamonds and Toads](https://en.wikipedia.org/wiki/Diamonds_and_Toads) from Charles Perrault. In this kata you will have to complete a function that take 2 arguments:
- A string, that correspond to what the daugther says.
- A string, that tell you wich fairy the girl have met, this one can be `good` or `evil`.
The function should return the following count as a hash:
- If the girl have met the `good` fairy:
- count 1 `ruby` everytime you see a `r` and 2 everytime you see a `R`
- count 1 `crystal` everytime you see a `c` and 2 everytime you see a `C`
- If the girl have met the `evil` fairy:
- count 1 `python` everytime you see a `p` and 2 everytime uou see a `P`
- count 1 `squirrel` everytime you see a `s` and 2 everytime you see a `S`
**Note**: For this kata I decided to remplace the normal `Diamonds` and `Toads` by some programming languages. And just discover that [Squirrel](https://en.wikipedia.org/wiki/Squirrel_(programming_language) is a programming language. | def diamonds_and_toads(sentence,fairy):
res={}
if fairy == 'good':
res['ruby']=sentence.count('r')+sentence.count('R')*2
res['crystal']=sentence.count('c')+sentence.count('C')*2
elif fairy == 'evil':
res['python']=sentence.count('p')+sentence.count('P')*2
res['squirrel']=sentence.count('s')+sentence.count('S')*2
return res | def diamonds_and_toads(sentence,fairy):
res={}
if fairy == 'good':
res['ruby']=sentence.count('r')+sentence.count('R')*2
res['crystal']=sentence.count('c')+sentence.count('C')*2
elif fairy == 'evil':
res['python']=sentence.count('p')+sentence.count('P')*2
res['squirrel']=sentence.count('s')+sentence.count('S')*2
return res | train | APPS_structured |
For two strings s and t, we say "t divides s" if and only if s = t + ... + t (t concatenated with itself 1 or more times)
Given two strings str1 and str2, return the largest string x such that x divides both str1 and str2.
Example 1:
Input: str1 = "ABCABC", str2 = "ABC"
Output: "ABC"
Example 2:
Input: str1 = "ABABAB", str2 = "ABAB"
Output: "AB"
Example 3:
Input: str1 = "LEET", str2 = "CODE"
Output: ""
Example 4:
Input: str1 = "ABCDEF", str2 = "ABC"
Output: ""
Constraints:
1 <= str1.length <= 1000
1 <= str2.length <= 1000
str1 and str2 consist of English uppercase letters. | class Solution:
def gcdOfStrings(self, str1: str, str2: str) -> str:
contender = ''
for i in str1:
contender += i
if str1.count(contender) * len(contender) == len(str1) and str2.count(contender) * len(contender) == len(str2):
break
orig = contender
ans = None
while len(contender) <= len(str1) and len(contender) <= len(str2):
t1 = str1.replace(contender, '')
t2 = str2.replace(contender, '')
if len(t1) == len(t2) == 0:
ans = contender
contender += orig
return ans if ans else '' | class Solution:
def gcdOfStrings(self, str1: str, str2: str) -> str:
contender = ''
for i in str1:
contender += i
if str1.count(contender) * len(contender) == len(str1) and str2.count(contender) * len(contender) == len(str2):
break
orig = contender
ans = None
while len(contender) <= len(str1) and len(contender) <= len(str2):
t1 = str1.replace(contender, '')
t2 = str2.replace(contender, '')
if len(t1) == len(t2) == 0:
ans = contender
contender += orig
return ans if ans else '' | train | APPS_structured |
When multiple master devices are connected to a single bus (https://en.wikipedia.org/wiki/System_bus), there needs to be an arbitration in order to choose which of them can have access to the bus (and 'talk' with a slave).
We implement here a very simple model of bus mastering. Given `n`, a number representing the number of **masters** connected to the bus, and a fixed priority order (the first master has more access priority than the second and so on...), the task is to choose the selected master.
In practice, you are given a string `inp` of length `n` representing the `n` masters' requests to get access to the bus, and you should return a string representing the masters, showing which (only one) of them was granted access:
```
The string 1101 means that master 0, master 1 and master 3 have requested
access to the bus.
Knowing that master 0 has the greatest priority, the output of the function should be: 1000
```
## Examples
## Notes
* The resulting string (`char* `) should be allocated in the `arbitrate` function, and will be free'ed in the tests.
* `n` is always greater or equal to 1. | import re
def arbitrate(s,_):
p,m,b=s.partition('1')
return p+m+'0'*len(b) | import re
def arbitrate(s,_):
p,m,b=s.partition('1')
return p+m+'0'*len(b) | train | APPS_structured |
# Task
You are given an array of integers `a` and a non-negative number of operations `k`, applied to the array. Each operation consists of two parts:
```
find the maximum element value of the array;
replace each element a[i] with (maximum element value - a[i]).```
How will the array look like after `k` such operations?
# Example
For `a = [-4, 0, -1, 0]` and `k = 2`, the output should be `[0, 4, 3, 4]`.
```
initial array: [-4, 0, -1, 0]
1st operation:
find the maximum value --> 0
replace each element: --> [(0 - -4), (0 - 0), (0 - -1), (0 - 0)]
--> [4, 0, 1, 0]
2nd operation:
find the maximum value --> 4
replace each element: --> [(4 - 4), (4 - 0), (4 - 1), (4 - 0)]
--> [0, 4, 3, 4]
```
For `a = [0, -1, 0, 0, -1, -1, -1, -1, 1, -1]` and `k = 1`,
the output should be `[1, 2, 1, 1, 2, 2, 2, 2, 0, 2]`.
```
initial array: [0, -1, 0, 0, -1, -1, -1, -1, 1, -1]
1st operation:
find the maximum value --> 1
replace each element: -->
[(1-0),(1- -1),(1-0),(1-0),(1- -1),(1- -1),(1- -1),(1- -1),(1-1),(1- -1)]
--> [1, 2, 1, 1, 2, 2, 2, 2, 0, 2]
```
# Input/Output
- `[input]` integer array a
The initial array.
Constraints:
`1 <= a.length <= 100`
`-100 <= a[i] <= 100`
- `[input]` integer `k`
non-negative number of operations.
Constraints: `0 <= k <= 100000`
- [output] an integer array
The array after `k` operations. | def array_operations(a, k):
b = [max(a)-i for i in a]
c = [max(b)-i for i in b]
return b if k%2 else c if k>0 else a | def array_operations(a, k):
b = [max(a)-i for i in a]
c = [max(b)-i for i in b]
return b if k%2 else c if k>0 else a | train | APPS_structured |
Given the values at the leaf nodes of a complete binary tree. The total number of nodes in the binary tree, is also given. Sum of the values at both the children of a node is equal to the value of the node itself. You can add any value or subtract any value from a node. Print the minimum change(difference made) in the sum of values of all the nodes in the tree, such that all the leaf nodes have the same value.
Note: If a value transfers from one node to another, then that is not a change, but if an extra is needed to be added or subtracted to the entire total value of the nodes, then that is a change.
Input Description:
Input will contain an integer N, the number of nodes in the tree on a newline, followed by N space separated integers representing the values at the leaf nodes of the tree.
Output Description:
Print the required value on a newline.
Constraints:
1<=N<=20000
1<=Value at each node in the leaves<=1000
Example 1:
Input:
1
50
Output:
0
Explanation: Since there is only one node, it is a leaf node itself and no change needs to be made.
Example 2:
Input:
3
200 800
Output:
0
Explanation: There are two leaf nodes, and they can be made to 500 500, since no change in the total was made so difference made is 0.
Example 3:
Input:
30
29 33 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
Output:
6
Output: A total change of 6 needs to be changed to the entire value of the nodes, to get the leaf nodes equal. | print(0) | print(0) | train | APPS_structured |
Deoxyribonucleic acid (DNA) is a chemical found in the nucleus of cells and carries the "instructions" for the development and functioning of living organisms.
If you want to know more http://en.wikipedia.org/wiki/DNA
In DNA strings, symbols "A" and "T" are complements of each other, as "C" and "G".
You have function with one side of the DNA (string, except for Haskell); you need to get the other complementary side. DNA strand is never empty or there is no DNA at all (again, except for Haskell).
More similar exercise are found here http://rosalind.info/problems/list-view/ (source)
```python
DNA_strand ("ATTGC") # return "TAACG"
DNA_strand ("GTAT") # return "CATA"
``` | def DNA_strand(dna):
# code here
dnaComplement=""
for string in dna:
if string=="A":
dnaComplement+="T"
elif string =="T":
dnaComplement+="A"
elif string =="G":
dnaComplement+="C"
elif string == "C":
dnaComplement+="G"
return dnaComplement | def DNA_strand(dna):
# code here
dnaComplement=""
for string in dna:
if string=="A":
dnaComplement+="T"
elif string =="T":
dnaComplement+="A"
elif string =="G":
dnaComplement+="C"
elif string == "C":
dnaComplement+="G"
return dnaComplement | train | APPS_structured |
During the archaeological research in the Middle East you found the traces of three ancient religions: First religion, Second religion and Third religion. You compiled the information on the evolution of each of these beliefs, and you now wonder if the followers of each religion could coexist in peace.
The Word of Universe is a long word containing the lowercase English characters only. At each moment of time, each of the religion beliefs could be described by a word consisting of lowercase English characters.
The three religions can coexist in peace if their descriptions form disjoint subsequences of the Word of Universe. More formally, one can paint some of the characters of the Word of Universe in three colors: $1$, $2$, $3$, so that each character is painted in at most one color, and the description of the $i$-th religion can be constructed from the Word of Universe by removing all characters that aren't painted in color $i$.
The religions however evolve. In the beginning, each religion description is empty. Every once in a while, either a character is appended to the end of the description of a single religion, or the last character is dropped from the description. After each change, determine if the religions could coexist in peace.
-----Input-----
The first line of the input contains two integers $n, q$ ($1 \leq n \leq 100\,000$, $1 \leq q \leq 1000$) — the length of the Word of Universe and the number of religion evolutions, respectively. The following line contains the Word of Universe — a string of length $n$ consisting of lowercase English characters.
Each of the following line describes a single evolution and is in one of the following formats: + $i$ $c$ ($i \in \{1, 2, 3\}$, $c \in \{\mathtt{a}, \mathtt{b}, \dots, \mathtt{z}\}$: append the character $c$ to the end of $i$-th religion description. - $i$ ($i \in \{1, 2, 3\}$) – remove the last character from the $i$-th religion description. You can assume that the pattern is non-empty.
You can assume that no religion will have description longer than $250$ characters.
-----Output-----
Write $q$ lines. The $i$-th of them should be YES if the religions could coexist in peace after the $i$-th evolution, or NO otherwise.
You can print each character in any case (either upper or lower).
-----Examples-----
Input
6 8
abdabc
+ 1 a
+ 1 d
+ 2 b
+ 2 c
+ 3 a
+ 3 b
+ 1 c
- 2
Output
YES
YES
YES
YES
YES
YES
NO
YES
Input
6 8
abbaab
+ 1 a
+ 2 a
+ 3 a
+ 1 b
+ 2 b
+ 3 b
- 1
+ 2 z
Output
YES
YES
YES
YES
YES
NO
YES
NO
-----Note-----
In the first example, after the 6th evolution the religion descriptions are: ad, bc, and ab. The following figure shows how these descriptions form three disjoint subsequences of the Word of Universe: $\left. \begin{array}{|c|c|c|c|c|c|c|} \hline \text{Word} & {a} & {b} & {d} & {a} & {b} & {c} \\ \hline ad & {a} & {} & {d} & {} & {} & {} \\ \hline bc & {} & {b} & {} & {} & {} & {c} \\ \hline ab & {} & {} & {} & {a} & {b} & {} \\ \hline \end{array} \right.$ | n, q = map(int, input().split())
s = '!' + input()
nxt = [[n + 1] * (n + 2) for _ in range(26)]
for i in range(n - 1, -1, -1):
c = ord(s[i + 1]) - 97
for j in range(26):
nxt[j][i] = nxt[j][i + 1]
nxt[c][i] = i + 1
w = [[-1], [-1], [-1]]
idx = lambda i, j, k: i * 65536 + j * 256 + k
dp = [0] * (256 * 256 * 256)
def calc(fix=None):
r = list(map(range, (len(w[0]), len(w[1]), len(w[2]))))
if fix is not None: r[fix] = range(len(w[fix]) - 1, len(w[fix]))
for i in r[0]:
for j in r[1]:
for k in r[2]:
dp[idx(i, j, k)] = min(nxt[w[0][i]][dp[idx(i - 1, j, k)]] if i else n + 1,
nxt[w[1][j]][dp[idx(i, j - 1, k)]] if j else n + 1,
nxt[w[2][k]][dp[idx(i, j, k - 1)]] if k else n + 1)
if i == j == k == 0: dp[idx(i, j, k)] = 0
out = []
for _ in range(q):
t, *r = input().split()
if t == '+':
i, c = int(r[0]) - 1, ord(r[1]) - 97
w[i].append(c)
calc(i)
else:
i = int(r[0]) - 1
w[i].pop()
req = dp[idx(len(w[0]) - 1, len(w[1]) - 1, len(w[2]) - 1)]
out.append('YES' if req <= n else 'NO')
print(*out, sep='\n') | n, q = map(int, input().split())
s = '!' + input()
nxt = [[n + 1] * (n + 2) for _ in range(26)]
for i in range(n - 1, -1, -1):
c = ord(s[i + 1]) - 97
for j in range(26):
nxt[j][i] = nxt[j][i + 1]
nxt[c][i] = i + 1
w = [[-1], [-1], [-1]]
idx = lambda i, j, k: i * 65536 + j * 256 + k
dp = [0] * (256 * 256 * 256)
def calc(fix=None):
r = list(map(range, (len(w[0]), len(w[1]), len(w[2]))))
if fix is not None: r[fix] = range(len(w[fix]) - 1, len(w[fix]))
for i in r[0]:
for j in r[1]:
for k in r[2]:
dp[idx(i, j, k)] = min(nxt[w[0][i]][dp[idx(i - 1, j, k)]] if i else n + 1,
nxt[w[1][j]][dp[idx(i, j - 1, k)]] if j else n + 1,
nxt[w[2][k]][dp[idx(i, j, k - 1)]] if k else n + 1)
if i == j == k == 0: dp[idx(i, j, k)] = 0
out = []
for _ in range(q):
t, *r = input().split()
if t == '+':
i, c = int(r[0]) - 1, ord(r[1]) - 97
w[i].append(c)
calc(i)
else:
i = int(r[0]) - 1
w[i].pop()
req = dp[idx(len(w[0]) - 1, len(w[1]) - 1, len(w[2]) - 1)]
out.append('YES' if req <= n else 'NO')
print(*out, sep='\n') | train | APPS_structured |
Chef was bored staying at home in the lockdown. He wanted to go out for a change. Chef and Chefu are fond of eating Cakes,so they decided to go the Cake shop where cakes of all possible price are available .
They decided to purchase cakes of equal price and each of them will pay for their cakes. Chef only has coins of denomination $N$ whereas Chefu has that of denomination $M$.
So they want your help to find out the minimum amount to be spent in order to purchase the cakes.
-----Input:-----
- First line will contain $T$, number of testcases. Then the testcases follow.
- Each testcase contains of a single line of input, two integers $N, M$.
-----Output:-----
For each testcase, output in a single line answer the minimum amount to be spent in order to purchase the cake.
-----Constraints-----
- $1 \leq T \leq 1000$
- $2 \leq N,M \leq 10^7$
-----Sample Input:-----
1
2 3
-----Sample Output:-----
6 | def compute_gcd(x, y):
while(y):
x, y = y, x % y
return x
def cm(x, y):
lcm = (x*y)//compute_gcd(x,y)
return lcm
for _ in range(int(input())):
n,m=list(map(int,input().split()))
print(cm(n,m))
| def compute_gcd(x, y):
while(y):
x, y = y, x % y
return x
def cm(x, y):
lcm = (x*y)//compute_gcd(x,y)
return lcm
for _ in range(int(input())):
n,m=list(map(int,input().split()))
print(cm(n,m))
| train | APPS_structured |
There is a pizza with 3n slices of varying size, you and your friends will take slices of pizza as follows:
You will pick any pizza slice.
Your friend Alice will pick next slice in anti clockwise direction of your pick.
Your friend Bob will pick next slice in clockwise direction of your pick.
Repeat until there are no more slices of pizzas.
Sizes of Pizza slices is represented by circular array slices in clockwise direction.
Return the maximum possible sum of slice sizes which you can have.
Example 1:
Input: slices = [1,2,3,4,5,6]
Output: 10
Explanation: Pick pizza slice of size 4, Alice and Bob will pick slices with size 3 and 5 respectively. Then Pick slices with size 6, finally Alice and Bob will pick slice of size 2 and 1 respectively. Total = 4 + 6.
Example 2:
Input: slices = [8,9,8,6,1,1]
Output: 16
Output: Pick pizza slice of size 8 in each turn. If you pick slice with size 9 your partners will pick slices of size 8.
Example 3:
Input: slices = [4,1,2,5,8,3,1,9,7]
Output: 21
Example 4:
Input: slices = [3,1,2]
Output: 3
Constraints:
1 <= slices.length <= 500
slices.length % 3 == 0
1 <= slices[i] <= 1000 | class Solution:
def maxSizeSlices(self, slices: List[int]) -> int:
def helper(start, end):
dp = [[0] * n for _ in range(end-start+1)]
dp[0] = [slices[start]] * n
dp[1] = [max(slices[start], slices[start+1])] * n
for i in range(start+2, end+1):
dp[i-start][0] = max(slices[i], dp[i-start-1][0])
for j in range(1, n):
dp[i-start][j] = max(dp[i-start-1][j], slices[i] + dp[i-start-2][j-1])
return dp[-1][-1]
n = len(slices) // 3
return max(helper(0, len(slices) - 2), helper(1, len(slices) - 1)) | class Solution:
def maxSizeSlices(self, slices: List[int]) -> int:
def helper(start, end):
dp = [[0] * n for _ in range(end-start+1)]
dp[0] = [slices[start]] * n
dp[1] = [max(slices[start], slices[start+1])] * n
for i in range(start+2, end+1):
dp[i-start][0] = max(slices[i], dp[i-start-1][0])
for j in range(1, n):
dp[i-start][j] = max(dp[i-start-1][j], slices[i] + dp[i-start-2][j-1])
return dp[-1][-1]
n = len(slices) // 3
return max(helper(0, len(slices) - 2), helper(1, len(slices) - 1)) | train | APPS_structured |
Your country has an infinite number of lakes. Initially, all the lakes are empty, but when it rains over the nth lake, the nth lake becomes full of water. If it rains over a lake which is full of water, there will be a flood. Your goal is to avoid the flood in any lake.
Given an integer array rains where:
rains[i] > 0 means there will be rains over the rains[i] lake.
rains[i] == 0 means there are no rains this day and you can choose one lake this day and dry it.
Return an array ans where:
ans.length == rains.length
ans[i] == -1 if rains[i] > 0.
ans[i] is the lake you choose to dry in the ith day if rains[i] == 0.
If there are multiple valid answers return any of them. If it is impossible to avoid flood return an empty array.
Notice that if you chose to dry a full lake, it becomes empty, but if you chose to dry an empty lake, nothing changes. (see example 4)
Example 1:
Input: rains = [1,2,3,4]
Output: [-1,-1,-1,-1]
Explanation: After the first day full lakes are [1]
After the second day full lakes are [1,2]
After the third day full lakes are [1,2,3]
After the fourth day full lakes are [1,2,3,4]
There's no day to dry any lake and there is no flood in any lake.
Example 2:
Input: rains = [1,2,0,0,2,1]
Output: [-1,-1,2,1,-1,-1]
Explanation: After the first day full lakes are [1]
After the second day full lakes are [1,2]
After the third day, we dry lake 2. Full lakes are [1]
After the fourth day, we dry lake 1. There is no full lakes.
After the fifth day, full lakes are [2].
After the sixth day, full lakes are [1,2].
It is easy that this scenario is flood-free. [-1,-1,1,2,-1,-1] is another acceptable scenario.
Example 3:
Input: rains = [1,2,0,1,2]
Output: []
Explanation: After the second day, full lakes are [1,2]. We have to dry one lake in the third day.
After that, it will rain over lakes [1,2]. It's easy to prove that no matter which lake you choose to dry in the 3rd day, the other one will flood.
Example 4:
Input: rains = [69,0,0,0,69]
Output: [-1,69,1,1,-1]
Explanation: Any solution on one of the forms [-1,69,x,y,-1], [-1,x,69,y,-1] or [-1,x,y,69,-1] is acceptable where 1 <= x,y <= 10^9
Example 5:
Input: rains = [10,20,20]
Output: []
Explanation: It will rain over lake 20 two consecutive days. There is no chance to dry any lake.
Constraints:
1 <= rains.length <= 10^5
0 <= rains[i] <= 10^9 | class Solution:
def avoidFlood(self, rains: List[int]) -> List[int]:
n = len(rains)
res = [-1] * n
dry = []
rained = {}
for i, r in enumerate(rains):
if r:
if r not in rained:
rained[r] = i
else:
if not dry:
return []
else:
idx = bisect.bisect_left(dry, rained[r])
if idx == len(dry):
return []
res[dry[idx]] = r
dry.pop(idx)
rained[r] = i
else:
dry.append(i)
for i in dry:
res[i] = 1
return res | class Solution:
def avoidFlood(self, rains: List[int]) -> List[int]:
n = len(rains)
res = [-1] * n
dry = []
rained = {}
for i, r in enumerate(rains):
if r:
if r not in rained:
rained[r] = i
else:
if not dry:
return []
else:
idx = bisect.bisect_left(dry, rained[r])
if idx == len(dry):
return []
res[dry[idx]] = r
dry.pop(idx)
rained[r] = i
else:
dry.append(i)
for i in dry:
res[i] = 1
return res | train | APPS_structured |
You get a new job working for Eggman Movers. Your first task is to write a method that will allow the admin staff to enter a person’s name and return what that person's role is in the company.
You will be given an array of object literals holding the current employees of the company. You code must find the employee with the matching firstName and lastName and then return the role for that employee or if no employee is not found it should return "Does not work here!"
The array is preloaded and can be referenced using the variable `employees` (`$employees` in Ruby). It uses the following structure.
```python
employees = [ {'first_name': "Dipper", 'last_name': "Pines", 'role': "Boss"}, ...... ]
```
There are no duplicate names in the array and the name passed in will be a single string with a space between the first and last name i.e. Jane Doe or just a name. | employees = [{'first_name': 'Ollie', 'last_name': 'Hepburn', 'role': 'Boss'}, {'first_name': 'Morty', 'last_name': 'Smith', 'role': 'Truck Driver'}, {'first_name': 'Peter', 'last_name': 'Ross', 'role': 'Warehouse Manager'}, {'first_name': 'Cal', 'last_name': 'Neil', 'role': 'Sales Assistant'}, {'first_name': 'Jesse', 'last_name': 'Saunders', 'role': 'Admin'}, {'first_name': 'Anna', 'last_name': 'Jones', 'role': 'Sales Assistant'}, {'first_name': 'Carmel', 'last_name': 'Hamm', 'role': 'Admin'}, {'first_name': 'Tori', 'last_name': 'Sparks', 'role': 'Sales Manager'}, {'first_name': 'Peter', 'last_name': 'Jones', 'role': 'Warehouse Picker'}, {'first_name': 'Mort', 'last_name': 'Smith', 'role': 'Warehouse Picker'}, {'first_name': 'Anna', 'last_name': 'Bell', 'role': 'Admin'}, {'first_name': 'Jewel', 'last_name': 'Bell', 'role': 'Receptionist'}, {'first_name': 'Colin', 'last_name': 'Brown', 'role': 'Trainee'}]
def find_employees_role(name):
for i in employees:
if i.get("first_name") + " " + i.get("last_name") == name: return i["role"]
return "Does not work here!" | employees = [{'first_name': 'Ollie', 'last_name': 'Hepburn', 'role': 'Boss'}, {'first_name': 'Morty', 'last_name': 'Smith', 'role': 'Truck Driver'}, {'first_name': 'Peter', 'last_name': 'Ross', 'role': 'Warehouse Manager'}, {'first_name': 'Cal', 'last_name': 'Neil', 'role': 'Sales Assistant'}, {'first_name': 'Jesse', 'last_name': 'Saunders', 'role': 'Admin'}, {'first_name': 'Anna', 'last_name': 'Jones', 'role': 'Sales Assistant'}, {'first_name': 'Carmel', 'last_name': 'Hamm', 'role': 'Admin'}, {'first_name': 'Tori', 'last_name': 'Sparks', 'role': 'Sales Manager'}, {'first_name': 'Peter', 'last_name': 'Jones', 'role': 'Warehouse Picker'}, {'first_name': 'Mort', 'last_name': 'Smith', 'role': 'Warehouse Picker'}, {'first_name': 'Anna', 'last_name': 'Bell', 'role': 'Admin'}, {'first_name': 'Jewel', 'last_name': 'Bell', 'role': 'Receptionist'}, {'first_name': 'Colin', 'last_name': 'Brown', 'role': 'Trainee'}]
def find_employees_role(name):
for i in employees:
if i.get("first_name") + " " + i.get("last_name") == name: return i["role"]
return "Does not work here!" | train | APPS_structured |
In Russia regular bus tickets usually consist of 6 digits. The ticket is called lucky when the sum of the first three digits equals to the sum of the last three digits. Write a function to find out whether the ticket is lucky or not. Return true if so, otherwise return false. Consider that input is always a string. Watch examples below. | import re
def is_lucky(ticket):
return bool(re.match(r'\d{6}', ticket)) and sum(int(i) for i in ticket[:3]) == sum(int(i) for i in ticket[3:]) | import re
def is_lucky(ticket):
return bool(re.match(r'\d{6}', ticket)) and sum(int(i) for i in ticket[:3]) == sum(int(i) for i in ticket[3:]) | train | APPS_structured |
# Letterss of Natac
In a game I just made up that doesn’t have anything to do with any other game that you may or may not have played, you collect resources on each turn and then use those resources to build settlements, roads, and cities or buy a development. Other kata about this game can be found [here](https://www.codewars.com/collections/59e6938afc3c49005900011f).
## Task
This kata asks you to implement the function `build_or_buy(hand)` , which takes as input a `hand`, the resources you have (a string of letters representing the resources you have), and returns a list of the unique game objects you can build or buy given your hand.
There are five different resources, `'b'`, `'w'`, `'g'`, `'s'`, and `'o'`.
Game objects and the resources required to build or buy them are as follows:
1. `'road'`: `bw`
2. `'settlement'`: `bwsg`
3. `'city'`: `ooogg`
4. `'development'`: `osg`
## Examples
```python
build_or_buy("bwoo") => ['road']
build_or_buy("bwsg") => ['road', 'settlement'] or ['settlement', 'road']
build_or_buy("") => []
build_or_buy("ogogoogogo") => ['city']
```
## Notes:
1. Don't mutate the hand
2. The order of the returned list doesn't matter
3. You do not have to test for whether a hand is valid.
4. The list will be interpreted to mean 'you can build any of these objects,' not 'you can build all these objects in one play'. See example 2 above, even though there is only one `'b'` and one `'w'` in `hand`, both `Road()` and `Settlement()` are in the list.
5. A hand can be empty. In the event a hand is empty, you can't build or buy anything, so return an empty list, see example 3 above.
6. Hand are between 0 and 39 in length. | from collections import Counter
PRICES = {
'road': 'bw',
'settlement': 'bwsg',
'city': 'ooogg',
'development': 'osg'
}
def build_or_buy(hand):
return list(filter(lambda obj: not Counter(PRICES[obj]) - Counter(hand),
PRICES.keys())) | from collections import Counter
PRICES = {
'road': 'bw',
'settlement': 'bwsg',
'city': 'ooogg',
'development': 'osg'
}
def build_or_buy(hand):
return list(filter(lambda obj: not Counter(PRICES[obj]) - Counter(hand),
PRICES.keys())) | train | APPS_structured |
Your friend has invited you to a party, and tells you to meet them in the line to get in. The one problem is it's a masked party. Everyone in line is wearing a colored mask, including your friend. Find which people in line could be your friend.
Your friend has told you that he will be wearing a `RED` mask, and has **TWO** other friends with him, both wearing `BLUE` masks.
Input to the function will be an array of strings, each representing a colored mask. For example:
```python
line = ['blue','blue','red','red','blue','green']
```
The output of the function should be the number of people who could possibly be your friend.
```python
friend_find(['blue','blue','red','red','blue','green','chipmunk']) # return 1
``` | def friend_find(line):
N = len(line)
A = lambda i: line[i] == "red" and B(i)
B = lambda i: C(i) or D(i) or E(i)
C = lambda i: i < N-2 and line[i+1] == line[i+2] == "blue"
D = lambda i: 0 < i < N-1 and line[i-1] == line[i+1] == "blue"
E = lambda i: 1 < i and line[i-2] == line[i-1] == "blue"
return sum(map(A, range(N))) | def friend_find(line):
N = len(line)
A = lambda i: line[i] == "red" and B(i)
B = lambda i: C(i) or D(i) or E(i)
C = lambda i: i < N-2 and line[i+1] == line[i+2] == "blue"
D = lambda i: 0 < i < N-1 and line[i-1] == line[i+1] == "blue"
E = lambda i: 1 < i and line[i-2] == line[i-1] == "blue"
return sum(map(A, range(N))) | train | APPS_structured |
If Give an integer N . Write a program to obtain the sum of the first and last digits of this number.
-----Input-----
The first line contains an integer T, the total number of test cases. Then follow T lines, each line contains an integer N.
-----Output-----
For each test case, display the sum of first and last digits of N in a new line.
-----Constraints-----
- 1 ≤ T ≤ 1000
- 1 ≤ N ≤ 1000000
-----Example-----
Input
3
1234
124894
242323
Output
5
5
5 | # cook your dish here
for _ in range(int(input())):
s=str(input())
print(int(s[0])+int(s[-1])) | # cook your dish here
for _ in range(int(input())):
s=str(input())
print(int(s[0])+int(s[-1])) | train | APPS_structured |
Given any number of boolean flags function should return true if and only if one of them is true while others are false. If function is called without arguments it should return false.
```python
only_one() == False
only_one(True, False, False) == True
only_one(True, False, False, True) == False
only_one(False, False, False, False) == False
``` | def only_one(*bool):
sum = 0
for value in bool:
if value:
sum += 1
if sum == 1:
return True
else:
return False | def only_one(*bool):
sum = 0
for value in bool:
if value:
sum += 1
if sum == 1:
return True
else:
return False | train | APPS_structured |
Ms. E.T. came from planet Hex. She has 8 fingers in each hand which makes her count in hexadecimal way. When she meets you, she tells you that she came from 7E light years from the planet Earth. You see she means that it is 126 light years far away and she is telling you the numbers in hexadecimal. Now, you are in trouble to understand what those numbers really mean. Therefore, you have to convert the hexadecimal numbers to decimals.
Input:
First line of code contain T test cases.
every line of text case contain a Hex-value
Output:
Every line of output contain a decimal conversion of given nunmber
Sample Input:
3
A
1A23
2C2A
Sample Output:
10
6691
11306 | t=int(input())
for _ in range(t):
test_string =input()
res = int(test_string, 16)
print(str(res)) | t=int(input())
for _ in range(t):
test_string =input()
res = int(test_string, 16)
print(str(res)) | train | APPS_structured |
After completing some serious investigation, Watson and Holmes are now chilling themselves in the Shimla hills. Very soon Holmes became bored. Holmes lived entirely for his profession. We know he is a workaholic. So Holmes wants to stop his vacation and get back to work. But after a tiresome season, Watson is in no mood to return soon. So to keep Holmes engaged, he decided to give Holmes one math problem. And Holmes agreed to solve the problem and said as soon as he solves the problem, they should return back to work. Watson too agreed.
The problem was as follows. Watson knows Holmes’ favorite numbers are 6 and 5. So he decided to give Holmes N single digit numbers. Watson asked Holmes to form a new number with the given N numbers in such a way that the newly formed number should be completely divisible by 5 and 6. Watson told Holmes that he should also form the number from these digits in such a way that the formed number is maximum. He may or may not use all the given numbers. But he is not allowed to use leading zeros. Though he is allowed to leave out some of the numbers, he is not allowed to add any extra numbers, which means the maximum count of each digit in the newly formed number, is the same as the number of times that number is present in those given N digits.
-----Input-----
The first line of input contains one integers T denoting the number of test cases.
Each test case consists of one integer N, number of numbers.
Next line contains contains N single digit integers
-----Output-----
For each test case output a single number, where the above said conditions are satisfied. If it is not possible to create such a number with the given constraints print -1.If there exists a solution, the maximised number should be greater than or equal to 0.
-----Constraints-----
- 1 ≤ T ≤ 100
- 1 ≤ N ≤ 10000
- 0 ≤ Each digit ≤ 9
-----Subtasks-----
Subtask #1 : (90 points)
- 1 ≤ T ≤ 100
- 1 ≤ N ≤ 10000
Subtask 2 : (10 points)
- 1 ≤ T ≤ 10
- 1 ≤ N≤ 10
-----Example-----
Input:
2
12
3 1 2 3 2 0 2 2 2 0 2 3
11
3 9 9 6 4 3 6 4 9 6 0
Output:
33322222200
999666330 | def mul3(ip):
q0=[]
q1=[]
q2=[]
ip.sort()
sums=sum(ip)
for i in ip:
if (i % 3) == 0:
q0.insert(0,i)
if (i % 3) == 1:
q1.insert(0,i)
if (i % 3) == 2:
q2.insert(0,i)
if(sums%3==1):
if(len(q1)):
q1.pop()
elif(len(q2)>=2):
q2.pop()
q2.pop()
else:
return -1
elif(sums%3==2):
if(len(q2)):
q2.pop()
elif(len(q1)>=2):
q1.pop()
q1.pop()
else:
return -1
q0.extend(q1)
q0.extend(q2)
if(len(q0)<=0):
return -1
q0.sort()
q0.reverse()
return q0
t = int(input())
for z in range(t):
n = int(input())
a = list(map(int, input().split()))
if 0 not in a or mul3(a)==-1:
print(-1)
else:
out=''
temp = mul3(a)
for p in temp:
out+=str(p)
print(out) | def mul3(ip):
q0=[]
q1=[]
q2=[]
ip.sort()
sums=sum(ip)
for i in ip:
if (i % 3) == 0:
q0.insert(0,i)
if (i % 3) == 1:
q1.insert(0,i)
if (i % 3) == 2:
q2.insert(0,i)
if(sums%3==1):
if(len(q1)):
q1.pop()
elif(len(q2)>=2):
q2.pop()
q2.pop()
else:
return -1
elif(sums%3==2):
if(len(q2)):
q2.pop()
elif(len(q1)>=2):
q1.pop()
q1.pop()
else:
return -1
q0.extend(q1)
q0.extend(q2)
if(len(q0)<=0):
return -1
q0.sort()
q0.reverse()
return q0
t = int(input())
for z in range(t):
n = int(input())
a = list(map(int, input().split()))
if 0 not in a or mul3(a)==-1:
print(-1)
else:
out=''
temp = mul3(a)
for p in temp:
out+=str(p)
print(out) | train | APPS_structured |
Two players are playing a game. The game is played on a sequence of positive integer pairs. The players make their moves alternatively. During his move the player chooses a pair and decreases the larger integer in the pair by a positive multiple of the smaller integer in the pair in such a way that both integers in the pair remain positive. If two numbers in some pair become equal then the pair is removed from the sequence. The player who can not make any move loses (or in another words the player who encounters an empty sequence loses). Given the sequence of positive integer pairs determine whether the first player can win or not (assuming that both players are playing optimally).
-----Input-----
The first line of the input contains an integer T denoting the number of test cases. The description of T test cases follows.
Each test starts with an integer N denoting the number of pairs. Each of the next N lines contains a pair of positive integers.
-----Output-----
For each test case, output a single line containing "YES" if the first player can win and "NO" otherwise.
-----Constraints-----
- 1 ≤ T ≤ 100
- 1 ≤ N ≤ 100
- All other integers are between 1 to 108
- The integers in each pair will be different
-----Example-----
Input:
3
1
2 3
2
4 5
5 6
2
2 3
3 5
Output:
NO
NO
YES
-----Explanation-----
Example case 1. The first player don't have any choice other subtracting 2 from 3. So during the turn of the second player integer pair will be (2,1). The second player will win by subtracting 1 from 2.
Example case 2. If the first player choose to move (4,5) to (4,1) the second player will make it to (1,1). If the first player choose to move (5,6) to (5,1) the second player will make it to (1,1). So regardless of the move of the first player, the second will always win.
Example case 3. The first player will select pair (3,5) and make it to (3,2). Now both pairs are equal. So whatever the move of second player he will just mirror that move in another pair. This will ensure his win. | import sys
t = int(input())
def g(a,b):
if (a > b):
tmp = a
a = b
b = tmp
if (b == a):
return 0
if (b % a == 0):
return int(b/a)-1
r = g(b%a,a)
q = int(b/a)
if (r >= q):
return q-1
else:
return q
def mex(x):
n = len(list(x.keys()))
for i in range(n):
if (i not in x):
return i
return i
def g2(a,b):
if (a == b):
return 0
if (a > b):
tmp = a
a = b
b = tmp
if (b % a == 0):
return int(b/a)-1
q = int(b/a)
x = {}
r = b % a
for i in range(q):
x[g2(r+i*a,a)] = True
return mex(x)
#print(str(g(6,33))+" "+str(g2(6,33)))
while (t):
n = int(input())
x = 0
while (n):
line = input().split()
a = int(line[0])
b = int(line[1])
x ^= g(a,b)
n -= 1
if (x):
sys.stdout.write("YES\n")
else:
sys.stdout.write("NO\n")
#print(str(g(a,b)) + " " + str(g2(a,b)))
t -= 1 | import sys
t = int(input())
def g(a,b):
if (a > b):
tmp = a
a = b
b = tmp
if (b == a):
return 0
if (b % a == 0):
return int(b/a)-1
r = g(b%a,a)
q = int(b/a)
if (r >= q):
return q-1
else:
return q
def mex(x):
n = len(list(x.keys()))
for i in range(n):
if (i not in x):
return i
return i
def g2(a,b):
if (a == b):
return 0
if (a > b):
tmp = a
a = b
b = tmp
if (b % a == 0):
return int(b/a)-1
q = int(b/a)
x = {}
r = b % a
for i in range(q):
x[g2(r+i*a,a)] = True
return mex(x)
#print(str(g(6,33))+" "+str(g2(6,33)))
while (t):
n = int(input())
x = 0
while (n):
line = input().split()
a = int(line[0])
b = int(line[1])
x ^= g(a,b)
n -= 1
if (x):
sys.stdout.write("YES\n")
else:
sys.stdout.write("NO\n")
#print(str(g(a,b)) + " " + str(g2(a,b)))
t -= 1 | train | APPS_structured |
You are given a sequence a = \{a_1, ..., a_N\} with all zeros, and a sequence b = \{b_1, ..., b_N\} consisting of 0 and 1. The length of both is N.
You can perform Q kinds of operations. The i-th operation is as follows:
- Replace each of a_{l_i}, a_{l_i + 1}, ..., a_{r_i} with 1.
Minimize the hamming distance between a and b, that is, the number of i such that a_i \neq b_i, by performing some of the Q operations.
-----Constraints-----
- 1 \leq N \leq 200,000
- b consists of 0 and 1.
- 1 \leq Q \leq 200,000
- 1 \leq l_i \leq r_i \leq N
- If i \neq j, either l_i \neq l_j or r_i \neq r_j.
-----Input-----
Input is given from Standard Input in the following format:
N
b_1 b_2 ... b_N
Q
l_1 r_1
l_2 r_2
:
l_Q r_Q
-----Output-----
Print the minimum possible hamming distance.
-----Sample Input-----
3
1 0 1
1
1 3
-----Sample Output-----
1
If you choose to perform the operation, a will become \{1, 1, 1\}, for a hamming distance of 1. | import sys
input=sys.stdin.readline
n=int(input())
b=list(map(int,input().split()))
ope=[[] for i in range(n)]
Q=int(input())
for i in range(Q):
l,r=list(map(int,input().split()))
ope[r-1].append(l-1)
res=b.count(0)
Data=[(-1)**((b[i]==1)+1) for i in range(n)]
for i in range(1,n):
Data[i]+=Data[i-1]
Data=[0]+Data
for i in range(n):
ope[i].sort(reverse=True)
# N: 処理する区間の長さ
N=n+1
N0 = 2**(N-1).bit_length()
data = [None]*(2*N0)
INF = (-2**31, -2**31)
# 区間[l, r+1)の値をvに書き換える
# vは(t, value)という値にする (新しい値ほどtは大きくなる)
def update(l, r, v):
L = l + N0; R = r + N0
while L < R:
if R & 1:
R -= 1
if data[R-1]:
data[R-1] = max(v,data[R-1])
else:
data[R-1]=v
if L & 1:
if data[L-1]:
data[L-1] = max(v,data[L-1])
else:
data[L-1]=v
L += 1
L >>= 1; R >>= 1
# a_iの現在の値を取得
def _query(k):
k += N0-1
s = INF
while k >= 0:
if data[k]:
s = max(s, data[k])
k = (k - 1) // 2
return s
# これを呼び出す
def query(k):
return _query(k)[1]
for i in range(n+1):
update(i,i+1,(-Data[i],-Data[i]))
if ope[0]:
update(1,2,(0,0))
for i in range(1,n):
val=query(i)
update(i+1,i+2,(val+Data[i]-Data[i+1],val+Data[i]-Data[i+1]))
for l in ope[i]:
val=query(l)
update(l+1,i+2,(val,val))
print((n-(res+query(n)+Data[n])))
| import sys
input=sys.stdin.readline
n=int(input())
b=list(map(int,input().split()))
ope=[[] for i in range(n)]
Q=int(input())
for i in range(Q):
l,r=list(map(int,input().split()))
ope[r-1].append(l-1)
res=b.count(0)
Data=[(-1)**((b[i]==1)+1) for i in range(n)]
for i in range(1,n):
Data[i]+=Data[i-1]
Data=[0]+Data
for i in range(n):
ope[i].sort(reverse=True)
# N: 処理する区間の長さ
N=n+1
N0 = 2**(N-1).bit_length()
data = [None]*(2*N0)
INF = (-2**31, -2**31)
# 区間[l, r+1)の値をvに書き換える
# vは(t, value)という値にする (新しい値ほどtは大きくなる)
def update(l, r, v):
L = l + N0; R = r + N0
while L < R:
if R & 1:
R -= 1
if data[R-1]:
data[R-1] = max(v,data[R-1])
else:
data[R-1]=v
if L & 1:
if data[L-1]:
data[L-1] = max(v,data[L-1])
else:
data[L-1]=v
L += 1
L >>= 1; R >>= 1
# a_iの現在の値を取得
def _query(k):
k += N0-1
s = INF
while k >= 0:
if data[k]:
s = max(s, data[k])
k = (k - 1) // 2
return s
# これを呼び出す
def query(k):
return _query(k)[1]
for i in range(n+1):
update(i,i+1,(-Data[i],-Data[i]))
if ope[0]:
update(1,2,(0,0))
for i in range(1,n):
val=query(i)
update(i+1,i+2,(val+Data[i]-Data[i+1],val+Data[i]-Data[i+1]))
for l in ope[i]:
val=query(l)
update(l+1,i+2,(val,val))
print((n-(res+query(n)+Data[n])))
| train | APPS_structured |
Students went into a class to write a test and sat in some way. The teacher thought: "Probably they sat in this order to copy works of each other. I need to rearrange them in such a way that students that were neighbors are not neighbors in a new seating."
The class can be represented as a matrix with n rows and m columns with a student in each cell. Two students are neighbors if cells in which they sit have a common side.
Let's enumerate students from 1 to n·m in order of rows. So a student who initially sits in the cell in row i and column j has a number (i - 1)·m + j. You have to find a matrix with n rows and m columns in which all numbers from 1 to n·m appear exactly once and adjacent numbers in the original matrix are not adjacent in it, or determine that there is no such matrix.
-----Input-----
The only line contains two integers n and m (1 ≤ n, m ≤ 10^5; n·m ≤ 10^5) — the number of rows and the number of columns in the required matrix.
-----Output-----
If there is no such matrix, output "NO" (without quotes).
Otherwise in the first line output "YES" (without quotes), and in the next n lines output m integers which form the required matrix.
-----Examples-----
Input
2 4
Output
YES
5 4 7 2
3 6 1 8
Input
2 1
Output
NO
-----Note-----
In the first test case the matrix initially looks like this:
1 2 3 4
5 6 7 8
It's easy to see that there are no two students that are adjacent in both matrices.
In the second test case there are only two possible seatings and in both of them students with numbers 1 and 2 are neighbors. | n,m=map(int,input().split())
if n==1and m==1:print('YES\n1')
elif n==3and m==3:
print('YES')
print(6, 1, 8)
print(7,5,3)
print(2,9,4)
elif n<4and m<4:print('NO')
elif n==1 or m==1:
t=max(n,m)
a=[i for i in range(2,t+1,2)]
a+=[i for i in range(1,t+1,2)]
print('YES')
for i in a:print(i,end="");print([' ','\n'][m==1],end='')
else:
a=[]
for j in range(n):
a.append([int(i)+int(m*j) for i in range(1,m+1)])
if n<=m:
for j in range(1,m,2):
t=a[0][j]
for i in range(1,n):
a[i-1][j]=a[i][j]
a[n-1][j]=t
for i in range(1,n,2):
r,s=a[i][0],a[i][1]
for j in range(2,m):
a[i][j-2]=a[i][j]
a[i][m-2],a[i][m-1]=r,s
else:
for j in range(1,m,2):
r,s=a[0][j],a[1][j]
for i in range(2,n):
a[i-2][j]=a[i][j]
a[n-2][j], a[n-1][j] = r, s
for i in range(1,n,2):
t=a[i][0]
for j in range(1,m):
a[i][j-1]=a[i][j]
a[i][m-1]=t
print('YES')
for i in range(n):
print(*a[i]) | n,m=map(int,input().split())
if n==1and m==1:print('YES\n1')
elif n==3and m==3:
print('YES')
print(6, 1, 8)
print(7,5,3)
print(2,9,4)
elif n<4and m<4:print('NO')
elif n==1 or m==1:
t=max(n,m)
a=[i for i in range(2,t+1,2)]
a+=[i for i in range(1,t+1,2)]
print('YES')
for i in a:print(i,end="");print([' ','\n'][m==1],end='')
else:
a=[]
for j in range(n):
a.append([int(i)+int(m*j) for i in range(1,m+1)])
if n<=m:
for j in range(1,m,2):
t=a[0][j]
for i in range(1,n):
a[i-1][j]=a[i][j]
a[n-1][j]=t
for i in range(1,n,2):
r,s=a[i][0],a[i][1]
for j in range(2,m):
a[i][j-2]=a[i][j]
a[i][m-2],a[i][m-1]=r,s
else:
for j in range(1,m,2):
r,s=a[0][j],a[1][j]
for i in range(2,n):
a[i-2][j]=a[i][j]
a[n-2][j], a[n-1][j] = r, s
for i in range(1,n,2):
t=a[i][0]
for j in range(1,m):
a[i][j-1]=a[i][j]
a[i][m-1]=t
print('YES')
for i in range(n):
print(*a[i]) | train | APPS_structured |
After six days, professor GukiZ decided to give more candies to his students. Like last time, he has $N$ students, numbered $1$ through $N$. Let's denote the number of candies GukiZ gave to the $i$-th student by $p_i$. As GukiZ has a lot of students, he does not remember all the exact numbers of candies he gave to the students. He only remembers the following properties of the sequence $p$:
- The numbers of candies given to each of the first $K$ students ($p_1, p_2, \dots, p_K$) are known exactly.
- All elements of the sequence $p$ are distinct and positive.
- GukiZ didn't give more than $x$ candies to any student (the maximum value in the sequence $p$ is not greater than $x$).
- For each student $i$, there is at least one other student $j$ such that $|p_i - p_j| \le D$.
- The professor gave out the biggest possible total number of candies, i.e. $S = p_1 + p_2 + p_3 + \ldots + p_N$ is maximum possible.
GukiZ would like to know the total number of candies $S$ he had at the beginning. However, times change and after six days, the professor is really tired, so it is possible that there is no sequence $p$ which satisfies the constraints. Can you help GukiZ find the number of candies he gave out, or tell him that he must have made a mistake?
-----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 four space-separated integers $N$, $K$, $x$, $D$.
- The second line contains $K$ distinct space-separated integers $p_1, p_2, \dots, p_K$.
-----Output-----
For each test case, print a single line containing one integer — the number of candies GukiZ had, or $-1$ if there is no valid sequence $p$.
-----Constraints-----
- $1 \le T \le 50$
- $3 \le N \le 10^9$
- $1 \le K \le \mathrm{min}(N, 2 \cdot 10^4)$
- $1 \le x \le 2 \cdot 10^9$
- $1 \le D \le 10^9$
- $1 \le p_i \le x$ for each valid $i$
- All values $p_i$ from input are distinct
-----Subtasks-----
Subtask #1 (15 points): $1 \leq x, N, D \leq 15$
Subtask #2 (35 points): $1 \leq x, N, D \leq 10^5$
Subtask #3 (50 points): original constraints
-----Example Input-----
2
4 3 5 3
2 1 5
3 2 8 2
3 8
-----Example Output-----
12
-1
-----Explanation-----
Example case 1: There are four students. We know that the first student got $p_1 = 2$ candies, the second student got $p_2 = 1$ and the third got $p_3 = 5$ candies; we don't know the number of candies given to the last student. The maximum possible amount of candies given to some student is $x=5$. The best possible option is giving $p_4=4$ candies to the last student. Then, the fourth constraint (with $D=3$) is satisfied for all students. Only the pair of students $(2, 3)$ have numbers of candies that differ by more than $3$, but still, for each student, there are at least two other students with close enough numbers of candies.
Example case 2: GukiZ made some mistake in distribution and there is no valid sequence $p$. The answer is $-1$. | # https://www.codechef.com/LTIME63B/problems/GHMC
# Finally.... I properly understood what needs to be done.
def ctlt(arr, val):
# find number of values in sorted arr < val
if arr[0] >= val: return 0
lo = 0
hi = len(arr)
while hi-lo > 1:
md = (hi+lo)//2
if arr[md]<val:
lo = md
else:
hi = md
return hi
for _ in range(int(input())):
n,k,x,d = map(int, input().split())
z = input().strip().split()
if k > 0:
ps = list(map(int,z[:k]))
else:
ps = [x]
ps.sort()
if x<n or x<ps[-1] or n<k:
print(-1)
continue
valchecked = 0
fillval = 0
valsdone = False
isolbelow = True
lastp = ps[0]
while not valsdone and n>=k:
if n == k:
lo = x+d+1 # put out of range
else:
# find best maxfill (before val support)
lo = 1
hi = x+1
while hi-lo>1:
md = (hi+lo)//2
v = (x-md+1) + ctlt(ps,md)
if v<n:
hi = md
else:
lo = md
valsdone = True
checkto = ctlt(ps,lo)-1
if checkto >= valchecked:
# support all vals
for p in ps[valchecked+1:checkto+1]:
if lastp+d >= p:
isolbelow = False
elif isolbelow:
valsdone = False
fillval += lastp+d
n -= 1
isolbelow = (p > lastp + 2*d )
else:
isolbelow = True
lastp = p
valchecked = checkto
if valsdone and isolbelow:
# check gap to maxfill
if lastp + d >= lo:
isolbelow = False
else:
valsdone = False
fillval += lastp
ps[checkto] += d
lastp += d
isolbelow = False
n -= 1
if k > n:
print(-1)
elif k == n:
print(sum(ps) + fillval)
elif k == n-1 and lo > ps[-1]:
print(sum(ps) + fillval + min(x,ps[-1]+d))
else:
tot = (x+lo)*(x-lo+1)//2 + sum(ps[:ctlt(ps,lo)])
print(tot + fillval)
| # https://www.codechef.com/LTIME63B/problems/GHMC
# Finally.... I properly understood what needs to be done.
def ctlt(arr, val):
# find number of values in sorted arr < val
if arr[0] >= val: return 0
lo = 0
hi = len(arr)
while hi-lo > 1:
md = (hi+lo)//2
if arr[md]<val:
lo = md
else:
hi = md
return hi
for _ in range(int(input())):
n,k,x,d = map(int, input().split())
z = input().strip().split()
if k > 0:
ps = list(map(int,z[:k]))
else:
ps = [x]
ps.sort()
if x<n or x<ps[-1] or n<k:
print(-1)
continue
valchecked = 0
fillval = 0
valsdone = False
isolbelow = True
lastp = ps[0]
while not valsdone and n>=k:
if n == k:
lo = x+d+1 # put out of range
else:
# find best maxfill (before val support)
lo = 1
hi = x+1
while hi-lo>1:
md = (hi+lo)//2
v = (x-md+1) + ctlt(ps,md)
if v<n:
hi = md
else:
lo = md
valsdone = True
checkto = ctlt(ps,lo)-1
if checkto >= valchecked:
# support all vals
for p in ps[valchecked+1:checkto+1]:
if lastp+d >= p:
isolbelow = False
elif isolbelow:
valsdone = False
fillval += lastp+d
n -= 1
isolbelow = (p > lastp + 2*d )
else:
isolbelow = True
lastp = p
valchecked = checkto
if valsdone and isolbelow:
# check gap to maxfill
if lastp + d >= lo:
isolbelow = False
else:
valsdone = False
fillval += lastp
ps[checkto] += d
lastp += d
isolbelow = False
n -= 1
if k > n:
print(-1)
elif k == n:
print(sum(ps) + fillval)
elif k == n-1 and lo > ps[-1]:
print(sum(ps) + fillval + min(x,ps[-1]+d))
else:
tot = (x+lo)*(x-lo+1)//2 + sum(ps[:ctlt(ps,lo)])
print(tot + fillval)
| train | APPS_structured |
We define a harmonious array is an array where the difference between its maximum value and its minimum value is exactly 1.
Now, given an integer array, you need to find the length of its longest harmonious subsequence among all its possible subsequences.
Example 1:
Input: [1,3,2,2,5,2,3,7]
Output: 5
Explanation: The longest harmonious subsequence is [3,2,2,2,3].
Note:
The length of the input array will not exceed 20,000. | class Solution:
def findLHS(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
count = collections.Counter(nums)
ret = 0
for i in count:
if i+1 in count:
ret = max(ret, count[i]+count[i+1])
return ret
| class Solution:
def findLHS(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
count = collections.Counter(nums)
ret = 0
for i in count:
if i+1 in count:
ret = max(ret, count[i]+count[i+1])
return ret
| train | APPS_structured |
**An [isogram](https://en.wikipedia.org/wiki/Isogram)** (also known as a "nonpattern word") is a logological term for a word or phrase without a repeating letter. It is also used by some to mean a word or phrase in which each letter appears the same number of times, not necessarily just once.
You task is to write a method `isogram?` that takes a string argument and returns true if the string has the properties of being an isogram and false otherwise. Anything that is not a string is not an isogram (ints, nils, etc.)
**Properties:**
- must be a string
- cannot be nil or empty
- each letter appears the same number of times (not necessarily just once)
- letter case is not important (= case insensitive)
- non-letter characters (e.g. hyphens) should be ignored | is_isogram = lambda word: type(word) == str and bool(word) and len(set( __import__("collections").Counter( __import__("re").sub(r'[^a-z]', "", word.lower())).values() )) == 1 | is_isogram = lambda word: type(word) == str and bool(word) and len(set( __import__("collections").Counter( __import__("re").sub(r'[^a-z]', "", word.lower())).values() )) == 1 | train | APPS_structured |
There are N children standing in a line. Each child is assigned a rating value.
You are giving candies to these children subjected to the following requirements:
Each child must have at least one candy.
Children with a higher rating get more candies than their neighbors.
What is the minimum candies you must give?
Example 1:
Input: [1,0,2]
Output: 5
Explanation: You can allocate to the first, second and third child with 2, 1, 2 candies respectively.
Example 2:
Input: [1,2,2]
Output: 4
Explanation: You can allocate to the first, second and third child with 1, 2, 1 candies respectively.
The third child gets 1 candy because it satisfies the above two conditions. | class Solution:
def candy(self, ratings):
"""
:type ratings: List[int]
:rtype: int
"""
if not ratings: return 0
if len(ratings) == 1: return 1
l2r = [1 for _ in ratings]
r2l = [1 for _ in ratings]
for i in range(1, len(ratings)):
if ratings[i] > ratings[i - 1]:
l2r[i] = l2r[i - 1] + 1
for i in range(len(ratings) - 2, -1, -1):
if ratings[i] > ratings[i + 1]:
r2l[i] = r2l[i + 1] + 1
res = 0
for i in range(len(ratings)):
res += max(l2r[i], r2l[i])
return res | class Solution:
def candy(self, ratings):
"""
:type ratings: List[int]
:rtype: int
"""
if not ratings: return 0
if len(ratings) == 1: return 1
l2r = [1 for _ in ratings]
r2l = [1 for _ in ratings]
for i in range(1, len(ratings)):
if ratings[i] > ratings[i - 1]:
l2r[i] = l2r[i - 1] + 1
for i in range(len(ratings) - 2, -1, -1):
if ratings[i] > ratings[i + 1]:
r2l[i] = r2l[i + 1] + 1
res = 0
for i in range(len(ratings)):
res += max(l2r[i], r2l[i])
return res | train | APPS_structured |
There is no single treatment that works for every phobia, but some people cure it by being gradually exposed to the phobic situation or object. In this kata we will try curing arachnophobia by drawing primitive spiders.
Our spiders will have legs, body, eyes and a mouth. Here are some examples:
```
/\((OOwOO))/\
/╲(((0000w0000)))╱\
^(oWo)^
```
You will be given four values:
1) `leg size` where each value stands for its own leg type: `1 for "^ ^", 2 for "/\ /\", 3 for "/╲ ╱\", 4 for "╱╲ ╱╲"`
2) `body size` where each value stands for its own body type: `1 for "( )", 2 for "(( ))", 3 for "((( )))"`
3) `mouth` representing the spider's mouth
4) `eye` representing the spider's eye
**Note:** the eyes are symmetric, and their total amount is `2 to the power of body size`.
You will also be given only valid data. That's it for the instructions, you can start coding! |
L = {1:'^', 2:'/\\', 3:'/╲', 4:'╱╲'}
R = {1:'^', 2:'/\\', 3:'╱\\', 4:'╱╲'}
def draw_spider(leg, body, mouth, eye):
return L[leg] + '(' * body + eye * (2**body//2) + mouth + eye * (2**body//2) + ')' * body + R[leg] |
L = {1:'^', 2:'/\\', 3:'/╲', 4:'╱╲'}
R = {1:'^', 2:'/\\', 3:'╱\\', 4:'╱╲'}
def draw_spider(leg, body, mouth, eye):
return L[leg] + '(' * body + eye * (2**body//2) + mouth + eye * (2**body//2) + ')' * body + R[leg] | train | APPS_structured |
Your music player contains N different songs and she wants to listen to L (not necessarily different) songs during your trip. You create a playlist so that:
Every song is played at least once
A song can only be played again only if K other songs have been played
Return the number of possible playlists. As the answer can be very large, return it modulo 10^9 + 7.
Example 1:
Input: N = 3, L = 3, K = 1
Output: 6
Explanation: There are 6 possible playlists. [1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1].
Example 2:
Input: N = 2, L = 3, K = 0
Output: 6
Explanation: There are 6 possible playlists. [1, 1, 2], [1, 2, 1], [2, 1, 1], [2, 2, 1], [2, 1, 2], [1, 2, 2]
Example 3:
Input: N = 2, L = 3, K = 1
Output: 2
Explanation: There are 2 possible playlists. [1, 2, 1], [2, 1, 2]
Note:
0 <= K < N <= L <= 100 | class Solution:
def numMusicPlaylists(self, N: int, L: int, K: int) -> int:
memo = {}
def dp(i, j):
if i == 0:
return j == 0
if (i, j) in memo: return memo[i, j]
memo[i, j] = dp(i - 1, j - 1) * (N - j + 1) + dp(i - 1, j) * max(j - K, 0)
return memo[i, j]
return dp(L, N)%(10**9 + 7)
| class Solution:
def numMusicPlaylists(self, N: int, L: int, K: int) -> int:
memo = {}
def dp(i, j):
if i == 0:
return j == 0
if (i, j) in memo: return memo[i, j]
memo[i, j] = dp(i - 1, j - 1) * (N - j + 1) + dp(i - 1, j) * max(j - K, 0)
return memo[i, j]
return dp(L, N)%(10**9 + 7)
| train | APPS_structured |
You will be given a vector of strings. You must sort it alphabetically (case-sensitive, and based on the ASCII values of the chars) and then return the first value.
The returned value must be a string, and have `"***"` between each of its letters.
You should not remove or add elements from/to the array. | two_sort = lambda l:'***'.join(sorted(l)[0]) | two_sort = lambda l:'***'.join(sorted(l)[0]) | train | APPS_structured |
You are a skier (marked below by the `X`). You have made it to the Olympics! Well done.
```
\_\_\_X\_
\*\*\*\*\*\
\*\*\*\*\*\*\
\*\*\*\*\*\*\*\
\*\*\*\*\*\*\*\*\
\*\*\*\*\*\*\*\*\*\\.\_\_\_\_/
```
Your job in this kata is to calculate the maximum speed you will achieve during your downhill run. The speed is dictated by the height of the mountain. Each element of the array is a layer of the mountain as indicated by the diagram above (and further below). So for this example the mountain has a height of 5 (5 rows of stars). `Speed` is `mountain height * 1.5`.
The jump length is calculated by `(mountain height * speed * 9) / 10`. Jump length should be rounded to 2 decimal places.
You must return the length of the resulting jump as a string in the following format:
* when less than 10 m: `"X metres: He's crap!"`
* between 10 and 25 m: `"X metres: He's ok!"`
* between 25 and 50 m: `"X metres: He's flying!"`
* when more than 50 m: `"X metres: Gold!!"`
So in the example case above, the right answer would be `"33.75 metres: He's flying!"`
Sadly, it takes a lot of time to make arrays look like mountains, so the tests wont all look so nice. To give an example, the above mountain would look as follows in most cases:
```
[*****, ******, *******, ********, *********]
```
Not as much fun, eh?
*p.s. if you think "metre" is incorrect, please [read this](https://en.wikipedia.org/wiki/Metre#Spelling)* | def ski_jump(mountain):
k=0
l=0
m=0
for i in mountain:
i=mountain[k]
k+=1
l=k*1.5
m=(k*l*9)/10
if m<10:
m=("%.2f" % m)
m=str(m)
m=m +" metres: He's crap!"
return m
elif m>=10 and m<=25:
m=("%.2f"%m)
m=str(m)
m=m+" metres: He's ok!"
return m
elif m>=25 and m<=50:
m=("%.2f" % m)
m=str(m)
m=(m)+" metres: He's flying!"
return m
else:
m=("%.2f" % m)
m=str(m)
m=m+" metres: Gold!!"
return m
| def ski_jump(mountain):
k=0
l=0
m=0
for i in mountain:
i=mountain[k]
k+=1
l=k*1.5
m=(k*l*9)/10
if m<10:
m=("%.2f" % m)
m=str(m)
m=m +" metres: He's crap!"
return m
elif m>=10 and m<=25:
m=("%.2f"%m)
m=str(m)
m=m+" metres: He's ok!"
return m
elif m>=25 and m<=50:
m=("%.2f" % m)
m=str(m)
m=(m)+" metres: He's flying!"
return m
else:
m=("%.2f" % m)
m=str(m)
m=m+" metres: Gold!!"
return m
| train | APPS_structured |
Ever since you started work at the grocer, you have been faithfully logging down each item and its category that passes through. One day, your boss walks in and asks, "Why are we just randomly placing the items everywhere? It's too difficult to find anything in this place!" Now's your chance to improve the system, impress your boss, and get that raise!
The input is a comma-separated list with category as the prefix in the form `"fruit_banana"`. Your task is to group each item into the 4 categories `Fruit, Meat, Other, Vegetable` and output a string with a category on each line followed by a sorted comma-separated list of items.
For example, given:
```
"fruit_banana,vegetable_carrot,fruit_apple,canned_sardines,drink_juice,fruit_orange"
```
output:
```
"fruit:apple,banana,orange\nmeat:\nother:juice,sardines\nvegetable:carrot"
```
Assume that:
1. Only strings of the format `category_item` will be passed in
2. Strings will always be in lower case
3. Input will not be empty
4. Category and/or item will not be empty
5. There will be no duplicate items
6. All categories may not have items | def group_groceries(groceries):
categories = {"fruit": [], "meat": [], "other": [], "vegetable": []}
for entry in groceries.split(","):
category, item = entry.split("_")
categories[category if category in categories else "other"].append(item)
return "\n".join([f"{category}:{','.join(sorted(items))}" for category, items in categories.items()]) | def group_groceries(groceries):
categories = {"fruit": [], "meat": [], "other": [], "vegetable": []}
for entry in groceries.split(","):
category, item = entry.split("_")
categories[category if category in categories else "other"].append(item)
return "\n".join([f"{category}:{','.join(sorted(items))}" for category, items in categories.items()]) | train | APPS_structured |
You are standing near a very strange machine. If you put C cents in the machine, the remaining money in your purse will transform in an unusual way. If you have A dollars and B cents remaining in your purse after depositing the C cents, then after the transformation you will have B dollars and A cents. You can repeat this procedure as many times as you want unless you don't have enough money for the machine. If at any point C > B and A > 0, then the machine will allow you to break one of the A dollars into 100 cents so you can place C cents in the machine. The machine will not allow you to exchange a dollar for 100 cents if B >= C.
Of course, you want to do this to maximize your profit. For example if C=69 and you have 9 dollars and 77 cents then after you put 69 cents in the machine you will have 8 dollars and 9 cents (9.77 --> 9.08 --> 8.09). But I should warn you that you can't cheat. If you try to throw away 9 cents before the transformation (in order to obtain 99 dollars and 8 cents after), the machine will sense you are cheating and take away all of your money. You need to know how many times you should do this transformation in order to make a maximum profit. Since you are very busy man, you want to obtain the maximum possible profit in the minimum amount of time.
-----Input-----
The first line contains a single integer T <= 40, the number of test cases. T test cases follow. The only line of each test case contains three nonnegative integers A, B and C where A, B, C < 100. It means that you have A dollars and B cents in your purse and you need to put C cents in the machine to make the transformation.
-----Output-----
For each test case, output a single line containing the minimal number of times you should do this transformation in order to make a maximal profit. It is guaranteed that the answer is less than 10000.
-----Example-----
Input:
2
9 77 69
98 99 69
Output:
4
0
-----Explanation-----
In the first test we have the following sequence: 9.77, 8.09, 40.07, 38.39, 70.37, 68.69, 0.68. After last step we have not enough money for further transformations. The maximal profit will be after 4 transformations. | for _ in range(int(input())):
a, b, c = map(int, input().split())
ans, cur_max, cur, count = 0, [a, b], 0, 10000
while count > 0 and (b >= c or a > 0):
cur += 1
count -= 1
if b < c:
b += 100
a -= 1
b -= c
if cur_max < [b, a]:
ans = cur
cur_max = [b, a]
a, b = b, a
print(ans) | for _ in range(int(input())):
a, b, c = map(int, input().split())
ans, cur_max, cur, count = 0, [a, b], 0, 10000
while count > 0 and (b >= c or a > 0):
cur += 1
count -= 1
if b < c:
b += 100
a -= 1
b -= c
if cur_max < [b, a]:
ans = cur
cur_max = [b, a]
a, b = b, a
print(ans) | train | APPS_structured |
Take debugging to a whole new level:
Given a string, remove every *single* bug.
This means you must remove all instances of the word 'bug' from within a given string, *unless* the word is plural ('bugs').
For example, given 'obugobugobuoobugsoo', you should return 'ooobuoobugsoo'.
Another example: given 'obbugugo', you should return 'obugo'.
Note that all characters will be lowercase.
Happy squishing! | import re
def debug(string):
return re.sub("bug(?!s)", "", string) | import re
def debug(string):
return re.sub("bug(?!s)", "", string) | train | APPS_structured |
A Tic-Tac-Toe board is given as a string array board. Return True if and only if it is possible to reach this board position during the course of a valid tic-tac-toe game.
The board is a 3 x 3 array, and consists of characters " ", "X", and "O". The " " character represents an empty square.
Here are the rules of Tic-Tac-Toe:
Players take turns placing characters into empty squares (" ").
The first player always places "X" characters, while the second player always places "O" characters.
"X" and "O" characters are always placed into empty squares, never filled ones.
The game ends when there are 3 of the same (non-empty) character filling any row, column, or diagonal.
The game also ends if all squares are non-empty.
No more moves can be played if the game is over.
Example 1:
Input: board = ["O ", " ", " "]
Output: false
Explanation: The first player always plays "X".
Example 2:
Input: board = ["XOX", " X ", " "]
Output: false
Explanation: Players take turns making moves.
Example 3:
Input: board = ["XXX", " ", "OOO"]
Output: false
Example 4:
Input: board = ["XOX", "O O", "XOX"]
Output: true
Note:
board is a length-3 array of strings, where each string board[i] has length 3.
Each board[i][j] is a character in the set {" ", "X", "O"}. | class Solution:
def swimInWater(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
n = len(grid)
pq = [(grid[0][0], 0, 0)]
seen = set([(0, 0)])
res = 0
while True:
val, y, x = heapq.heappop(pq)
res = max(res, val)
if y == x == n - 1:
return res
for i, j in [(y + 1, x), (y - 1, x), (y, x + 1), (y, x - 1)]:
if 0 <= i < n and 0 <= j < n and (i, j) not in seen:
seen.add((i, j))
heapq.heappush(pq, (grid[i][j], i, j))
return 0
| class Solution:
def swimInWater(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
n = len(grid)
pq = [(grid[0][0], 0, 0)]
seen = set([(0, 0)])
res = 0
while True:
val, y, x = heapq.heappop(pq)
res = max(res, val)
if y == x == n - 1:
return res
for i, j in [(y + 1, x), (y - 1, x), (y, x + 1), (y, x - 1)]:
if 0 <= i < n and 0 <= j < n and (i, j) not in seen:
seen.add((i, j))
heapq.heappush(pq, (grid[i][j], i, j))
return 0
| train | APPS_structured |
Takaki Tono is a Computer Programmer in Tokyo. His boss at work shows him an online puzzle, which if solved would earn the solver a full expense paid trip to Los Angeles, California. Takaki really wants to solve this, as the love of his life, Akari, lives in Los Angeles and he hasn't met her since four years. Upon reading the puzzle he realizes that it is a query based problem. The problem is as follows :-
You are given a Tree T with N nodes numbered from 1 to N, with each node numbered z having a positive integer Az written on it. This integer denotes the value of the node. You have to process Q queries, of the following forms :-
1) C x y : Report the closest two values in the unique path from x to y i.e compute min(|Ap - Aq|) where p and q are two distinct nodes on the unique path from x to y.
2) F x y : Report the farthest two values in the unique path from x to y i.e. compute max(|Ap - Aq|) where p and q are two distinct nodes on the unique path from x to y.
It is also mentioned that x is not equal to y in any query and that no two nodes have the same value printed on them. Also, |x| denotes the absolute value of x.
Takaki is perplexed and requires your help to solve this task? Can you help him out?
-----Input-----
The first line of the input contains an integer N denoting the number of nodes in tree T.
The second line comprises N space separated integers denoting A, where the i-th integer denotes Ai.
The next N-1 lines each comprise two space separated integers u and v, denoting that node u and node v
are connected by an edge. It is guaranteed that the final graph will be a connected tree.
The next line contains a single integer Q, denoting number of queries.
The next Q lines comprise the queries. Each such line is of the format C x y or F x y.
-----Output-----
For each query, print the required output as mentioned above.
-----Constraints-----
- 2 ≤ N ≤ 35000
- 1 ≤ Ai ≤ 109
- 1 ≤ Q ≤ 35000
- 1 ≤ u, v ≤ N
- No two nodes have the same value printed on them.
- x is not equal to y in any query.
-----Subtasks-----
-----Subtasks-----Subtask #1 (15 points)
- N, Q ≤ 1000Subtask #2 (20 points)
- Only Type F queries are present.Subtask #3 (65 points)
- Original constraints
-----Example-----
Input:5
1 2 7 4 5
1 2
2 3
2 4
2 5
7
C 1 5
F 1 5
C 2 4
C 1 2
F 1 3
F 3 4
F 2 4
Output:1
4
2
1
6
5
2
-----Explanation-----
Given below is the tree corresponding to the sample input. Each node has two numbers written in it.
The first number represents the node index and the second number indicates node value. |
N = eval(input())
nodes = list(map(int, input().split(" ")))
edges = [set() for _ in range(N)]
for _ in range(N-1):
a, b = list(map(int, input().split(" ")))
edges[a-1].add(b-1)
edges[b-1].add(a-1)
path = [[] for _ in range(N)]
visited, tovisit = set(), [(0, 0)]
while tovisit:
p, v = tovisit.pop()
if v not in visited:
path[v] = path[p] + [v]
visited.add(v)
news = edges[v] - visited
tovisit.extend([(v, x) for x in news])
# print path
Q = eval(input())
for _ in range(Q):
q, a, b = input().split(" ")
a, b = int(a)-1, int(b)-1
i = 1
while i < min(len(path[a]), len(path[b])):
if path[a][i] != path[b][i]: break
i += 1
s = path[a][i-1:] + path[b][i:]
s = sorted([nodes[i] for i in s])
# print s
if q == "C":
d = s[-1] - s[0]
for i in range(len(s)-1):
d = min(d, s[i+1]-s[i])
print(d)
else:
print(s[-1] - s[0])
# print M[(s, l)] - m[(s, l)]
|
N = eval(input())
nodes = list(map(int, input().split(" ")))
edges = [set() for _ in range(N)]
for _ in range(N-1):
a, b = list(map(int, input().split(" ")))
edges[a-1].add(b-1)
edges[b-1].add(a-1)
path = [[] for _ in range(N)]
visited, tovisit = set(), [(0, 0)]
while tovisit:
p, v = tovisit.pop()
if v not in visited:
path[v] = path[p] + [v]
visited.add(v)
news = edges[v] - visited
tovisit.extend([(v, x) for x in news])
# print path
Q = eval(input())
for _ in range(Q):
q, a, b = input().split(" ")
a, b = int(a)-1, int(b)-1
i = 1
while i < min(len(path[a]), len(path[b])):
if path[a][i] != path[b][i]: break
i += 1
s = path[a][i-1:] + path[b][i:]
s = sorted([nodes[i] for i in s])
# print s
if q == "C":
d = s[-1] - s[0]
for i in range(len(s)-1):
d = min(d, s[i+1]-s[i])
print(d)
else:
print(s[-1] - s[0])
# print M[(s, l)] - m[(s, l)]
| train | APPS_structured |
Two tortoises named ***A*** and ***B*** must run a race. ***A*** starts with an average speed of ```720 feet per hour```.
Young ***B*** knows she runs faster than ***A***, and furthermore has not finished her cabbage.
When she starts, at last, she can see that ***A*** has a `70 feet lead` but ***B***'s speed is `850 feet per hour`.
How long will it take ***B*** to catch ***A***?
More generally:
given two speeds `v1` (***A***'s speed, integer > 0) and `v2` (***B***'s speed, integer > 0) and a lead `g` (integer > 0)
how long will it take ***B*** to catch ***A***?
The result will be an array ```[hour, min, sec]``` which is the time needed in hours, minutes and seconds (round down to the nearest second)
or a string in some languages.
If `v1 >= v2` then return `nil`, `nothing`, `null`, `None` or `{-1, -1, -1}` for C++, C, Go, Nim, `[]` for Kotlin or "-1 -1 -1".
## Examples:
(form of the result depends on the language)
```
race(720, 850, 70) => [0, 32, 18] or "0 32 18"
race(80, 91, 37) => [3, 21, 49] or "3 21 49"
```
** Note:
- See other examples in "Your test cases".
- In Fortran - as in any other language - the returned string is not permitted to contain any redundant trailing whitespace: you can use dynamically allocated character strings.
** Hints for people who don't know how to convert to hours, minutes, seconds:
- Tortoises don't care about fractions of seconds
- Think of calculation by hand using only integers (in your code use or simulate integer division)
- or Google: "convert decimal time to hours minutes seconds" | def race(v1, v2, g):
if v1 >= v2: return None
t = float(g)/(v2-v1)*3600
mn, s = divmod(t, 60)
h, mn = divmod(mn, 60)
return [int(h), int(mn), int(s)] | def race(v1, v2, g):
if v1 >= v2: return None
t = float(g)/(v2-v1)*3600
mn, s = divmod(t, 60)
h, mn = divmod(mn, 60)
return [int(h), int(mn), int(s)] | train | APPS_structured |
The Binomial Form of a polynomial has many uses, just as the standard form does. For comparison, if p(x) is in Binomial Form and q(x) is in standard form, we might write
p(x) := a0 \* xC0 + a1 \* xC1 + a2 \* xC2 + ... + aN \* xCN
q(x) := b0 + b1 \* x + b2 \* x^(2) + ... + bN \* x^(N)
Both forms have tricks for evaluating them, but tricks should not be necessary. The most important thing to keep in mind is that aCb can be defined for non-integer values of a; in particular,
```
aCb := a * (a-1) * (a-2) * ... * (a-b+1) / b! // for any value a and integer values b
:= a! / ((a-b)!b!) // for integer values a,b
```
The inputs to your function are an array which specifies a polynomial in Binomial Form, ordered by highest-degree-first, and also a number to evaluate the polynomial at. An example call might be
```python
value_at([1, 2, 7], 3)
```
and the return value would be 16, since 3C2 + 2 * 3C1 + 7 = 16. In more detail, this calculation looks like
```
1 * xC2 + 2 * xC1 + 7 * xC0 :: x = 3
3C2 + 2 * 3C1 + 7
3 * (3-1) / 2! + 2 * 3 / 1! + 7
3 + 6 + 7 = 16
```
More information can be found by reading about [Binomial Coefficients](https://en.wikipedia.org/wiki/Binomial_coefficient) or about [Finite Differences](https://en.wikipedia.org/wiki/Finite_difference).
Note that while a solution should be able to handle non-integer inputs and get a correct result, any solution should make use of rounding to two significant digits (as the official solution does) since high precision for non-integers is not the point here. | def value_at(poly_spec, x):
leng = len(poly_spec)
ans = 0
for i, e in enumerate(poly_spec):
temp = 1
for j in range(leng-i-1):
temp *= (x-j)/(j+1)
ans += e*temp
return round(ans, 2) | def value_at(poly_spec, x):
leng = len(poly_spec)
ans = 0
for i, e in enumerate(poly_spec):
temp = 1
for j in range(leng-i-1):
temp *= (x-j)/(j+1)
ans += e*temp
return round(ans, 2) | train | APPS_structured |
Write a function that takes an integer and returns an array `[A, B, C]`, where `A` is the number of multiples of 3 (but not 5) below the given integer, `B` is the number of multiples of 5 (but not 3) below the given integer and `C` is the number of multiples of 3 and 5 below the given integer.
For example, `solution(20)` should return `[5, 2, 1]`
~~~if:r
```r
# in R, returns a numeric vector
solution(20)
[1] 5 2 1
class(solution(20))
[1] "numeric"
```
~~~ | def solution(number):
number = number - 1
fizzbuzz = number // 15
fizz = number // 3 - fizzbuzz
buzz = number // 5 - fizzbuzz
return [fizz, buzz, fizzbuzz] | def solution(number):
number = number - 1
fizzbuzz = number // 15
fizz = number // 3 - fizzbuzz
buzz = number // 5 - fizzbuzz
return [fizz, buzz, fizzbuzz] | train | APPS_structured |
Consider the fraction, $a/b$, where $a$ and $b$ are positive integers. If $a < b$ and $GCD(a,b) = 1$, it is called a reduced proper fraction.
If we list the set of a reduced proper fraction for $d \leq 8$, (where $d$ is the denominator) in ascending order of size, we get:
$1/8$, $1/7$, $1/6$, $1/5$, $1/4$, $2/7$, $1/3$, $3/8$, $2/5$ , $3/7$, $1/2$, $4/7$, $3/5$, $5/8$, $2/3$, $5/7$, $3/4$, $4/5$, $5/6$, $6/7$, $7/8$
It can be seen that $2/5$ is the fraction immediately to the left of $3/7$.
By listing the set of reduced proper fractions for $d \leq N$ in ascending order of value, find the numerator and denominator of the fraction immediately to the left of $a/b$ when $a$ and $b$ are given.
-----Input:-----
- First line of input contains an integer $T$, number of test cases
- Next $T$ lines contain $a$ $b$ $N$ separated by space
-----Output:-----
Print the numerator and denominator separated by a space corresponding to each test case on a new line
-----Constraints-----
- $1 \leq T \leq 50$
- $1 \leq a < b \leq 10^9$
- $GCD(a,b) = 1$
- $b < N \leq 10^{15}$
-----Subtasks-----
- 10 points: $1 \leq N \leq 100$
- 30 points : $1 \leq N \leq 10^6$
- 60 points : $1 \leq N \leq 10^{15}$
-----Sample Input:-----
5
3 7 8
3 5 8
4 5 8
6 7 8
1 5 8
-----Sample Output:-----
2 5
4 7
3 4
5 6
1 6 | R1_HIGH, R1_LOW, R2_HIGH, R2_LOW = 0, 0, 0, 0
def cross_multiply(a, b, i):
nonlocal R1_HIGH
nonlocal R1_LOW
nonlocal R2_HIGH
nonlocal R2_LOW
if i == 1:
R1_HIGH = 6*a*b
R1_LOW = R1_HIGH // 2
elif i == 2:
R2_HIGH = 6*a*b
R2_LOW = R2_HIGH // 2
def isLess(a,b,c,d):
cross_multiply(a, d, 1)
cross_multiply(c, b, 2)
if (R1_HIGH < R2_HIGH):
return True
if (R1_HIGH > R2_HIGH):
return False
return (R1_LOW < R2_LOW)
def negb_frac(a,b,N):
leftN , leftD = 0, 1
rightN, rightD = 1, 1
while((leftD + rightD) <= N):
mediantN = leftN + rightN
mediantD = leftD + rightD
if isLess(mediantN, mediantD, a, b):
leftN = mediantN
leftD = mediantD
else:
rightN = mediantN
rightD = mediantD
if (rightN == a and rightD == b):
break
if ((leftD + rightD) <= N):
diff = N - (leftD + rightD)
repeat = 1 + diff // rightD
leftN += repeat * rightN
leftD += repeat * rightD
print(leftN, leftD)
def __starting_point():
T = int(input())
for _ in range(T):
a,b,N = list(map(int, input().split()))
negb_frac(a,b,N)
__starting_point() | R1_HIGH, R1_LOW, R2_HIGH, R2_LOW = 0, 0, 0, 0
def cross_multiply(a, b, i):
nonlocal R1_HIGH
nonlocal R1_LOW
nonlocal R2_HIGH
nonlocal R2_LOW
if i == 1:
R1_HIGH = 6*a*b
R1_LOW = R1_HIGH // 2
elif i == 2:
R2_HIGH = 6*a*b
R2_LOW = R2_HIGH // 2
def isLess(a,b,c,d):
cross_multiply(a, d, 1)
cross_multiply(c, b, 2)
if (R1_HIGH < R2_HIGH):
return True
if (R1_HIGH > R2_HIGH):
return False
return (R1_LOW < R2_LOW)
def negb_frac(a,b,N):
leftN , leftD = 0, 1
rightN, rightD = 1, 1
while((leftD + rightD) <= N):
mediantN = leftN + rightN
mediantD = leftD + rightD
if isLess(mediantN, mediantD, a, b):
leftN = mediantN
leftD = mediantD
else:
rightN = mediantN
rightD = mediantD
if (rightN == a and rightD == b):
break
if ((leftD + rightD) <= N):
diff = N - (leftD + rightD)
repeat = 1 + diff // rightD
leftN += repeat * rightN
leftD += repeat * rightD
print(leftN, leftD)
def __starting_point():
T = int(input())
for _ in range(T):
a,b,N = list(map(int, input().split()))
negb_frac(a,b,N)
__starting_point() | train | APPS_structured |
*Debug* function `getSumOfDigits` that takes positive integer to calculate sum of it's digits. Assume that argument is an integer.
### Example
```
123 => 6
223 => 7
1337 => 15
``` | def get_sum_of_digits(num):
digits = []
for i in str(num): digits.append(int(i))
return sum(digits) | def get_sum_of_digits(num):
digits = []
for i in str(num): digits.append(int(i))
return sum(digits) | train | APPS_structured |
Santa puts all the presents into the huge sack. In order to let his reindeers rest a bit, he only takes as many reindeers with him as he is required to do. The others may take a nap.
Two reindeers are always required for the sleigh and Santa himself. Additionally he needs 1 reindeer per 30 presents. As you know, Santa has 8 reindeers in total, so he can deliver up to 180 presents at once (2 reindeers for Santa and the sleigh + 6 reindeers with 30 presents each).
Complete the function `reindeers()`, which takes a number of presents and returns the minimum numbers of required reindeers. If the number of presents is too high, throw an error.
Examles:
```python
reindeer(0) # must return 2
reindeer(1) # must return 3
reindeer(30) # must return 3
reindeer(200) # must throw an error
``` | from math import ceil
# Why is this 6 kyu?
def reindeer(presents):
if presents > 180: raise Exception("Too many presents")
return 2 + ceil(presents/30) | from math import ceil
# Why is this 6 kyu?
def reindeer(presents):
if presents > 180: raise Exception("Too many presents")
return 2 + ceil(presents/30) | train | APPS_structured |
Assume you are creating a webshop and you would like to help the user in the search. You have products with brands, prices and name. You have the history of opened products (the most recently opened being the first item).
Your task is to create a list of brands ordered by popularity, if two brands have the same popularity level then choose the one which was opened last from the two and second the other one.
Product popularity is calculated from the history. If a product is more times in the history than it is more popular.
Your function will have one parameter which will be always an array/list of object.
example product:
{
name: "Phone",
price: 25,
brand: "Fake brand"
} | from collections import Counter
def sorted_brands(history):
cnt = Counter(item["brand"] for item in history)
return sorted(cnt, key=cnt.get, reverse=True) | from collections import Counter
def sorted_brands(history):
cnt = Counter(item["brand"] for item in history)
return sorted(cnt, key=cnt.get, reverse=True) | train | APPS_structured |
You are the Dungeon Master for a public DnD game at your local comic shop and recently you've had some trouble keeping your players' info neat and organized so you've decided to write a bit of code to help keep them sorted!
The goal of this code is to create an array of objects that stores a player's name and contact number from a given string.
The method should return an empty array if the argument passed is an empty string or `nil`/`None`/`null`.
## Examples
```ruby
player_manager("John Doe, 8167238327, Jane Doe, 8163723827") returns [{player: "John Doe", contact: 8167238327}, {player: "Jane Doe", contact: 8163723827}]
player_manager(nil) returns []
player_manager("") returns []
```
```python
player_manager("John Doe, 8167238327, Jane Doe, 8163723827") returns [{"player": "John Doe", "contact": 8167238327}, {"player": "Jane Doe", "contact": 8163723827}]
player_manager(None) returns []
player_manager("") returns []
```
```
playerManager("John Doe, 8167238327, Jane Doe, 8163723827") returns [{player: "John Doe", contact: 8167238327}, {player: "Jane Doe", contact: 8163723827}]
playerManager(null) returns []
playerManager("") returns []
```
Have at thee! | def player_manager(players):
return [{'player': a, 'contact': int(b)} for a, b in zip(*[iter(players.split(', '))] * 2)] if players else [] | def player_manager(players):
return [{'player': a, 'contact': int(b)} for a, b in zip(*[iter(players.split(', '))] * 2)] if players else [] | train | APPS_structured |
This kata is a continuation of [Part 1](http://www.codewars.com/kata/the-fibfusc-function-part-1). The `fibfusc` function is defined recursively as follows:
fibfusc(0) = (1, 0)
fibfusc(1) = (0, 1)
fibfusc(2n) = ((x + y)(x - y), y(2x + 3y)), where (x, y) = fibfusc(n)
fibfusc(2n + 1) = (-y(2x + 3y), (x + 2y)(x + 4y)), where (x, y) = fibfusc(n)
Your job is to produce the code for the `fibfusc` function. In this kata, your function will be tested with large values of n (up to 2000 bits), so you should be concerned about stack overflow and timeouts. Moreover, since the `fibfusc` function grows exponentially, your function should take an extra argument `num_digits` with a default value of `None`. When not `None`, `num_digits` takes a positive `int` value and the returned values shall be truncated to the last `num_digits` digits.
For example, let `n = 101`. With `num_digits` not set or set to `None`, `fibfusc` should return:
`(-280571172992510140037611932413038677189525L, 734544867157818093234908902110449296423351L)`. If `num_digits = 12`, the function should return `(-38677189525L, 449296423351L)`. Notice in particular, that for any value of `n` greater than 1, `x` is negative, and the truncated value of `x` should also be negative.
Hint 1: Use modulo `10 ** num_digits` arithmetic to keep all intermediary results small.
Hint 2: Consider using an iterative ["number climber"](http://www.codewars.com/kata/number-climber) to avoid stack overflows. | def fibfusc(n, num_digits=None):
if n==0: return (1,0)
x,y=0,1
trunc=1 if num_digits==None else 10**(num_digits)
nbin=bin(n)[3:]
for i in nbin:
x,y=((x+y)*(x-y),y*(2*x+3*y)) if i=='0' else (-y*(2*x + 3*y),(x + 2*y)*(x + 4*y))
if trunc > 1 : x,y=(-(-x % trunc),y % trunc)
return x,y | def fibfusc(n, num_digits=None):
if n==0: return (1,0)
x,y=0,1
trunc=1 if num_digits==None else 10**(num_digits)
nbin=bin(n)[3:]
for i in nbin:
x,y=((x+y)*(x-y),y*(2*x+3*y)) if i=='0' else (-y*(2*x + 3*y),(x + 2*y)*(x + 4*y))
if trunc > 1 : x,y=(-(-x % trunc),y % trunc)
return x,y | train | APPS_structured |
Xorgon is an extremely delicious treat formed by the sequence $S$ of binary integers $s_1, s_2,..,s_N$. A really interesting property found in a Xorgon is that the xor of all elements in any contiguous subsequence of length $K$ in $S$ will result in $1$.
Chef has been asked to prepare a Xorgon. However, he has at his disposal a binary sequence $X$ containing the binary integers $x_1, x_2, ...x_N$. To prepare a Xorgon, the chef may flip the value of as many binary digits in $X$ as required.(i.e. turn a $1$ to a $0$ and $0$ to a $1$). Unfortunately, flipping a digit takes a lot of time and the chef has to serve many orders. Can you help the chef calculate the minimum number of flips required to cook a Xorgon from the given $X$?
-----Input:-----
- The first line will contain two space-separated integers $N, K$.
- Next line contains N space-separated integers $x_1, x_2, ...,x_N$.
-----Output:-----
Output in a single line minimum number of flips required to turn $X$ into a Xorgon.
-----Constraints-----
- $1 \leq K \leq N \leq 3*10^6$
- $0 \leq x_i \leq 1$
-----Sample Input:-----
7 5
1 0 0 1 1 1 1
-----Sample Output:-----
1
-----EXPLANATION:-----
Flip the last bit from 1 to 0 to obtain a Xorgon. | # cook your dish here
from sys import stdin,stdout
a0=0
a1=1
n,k=stdin.readline().strip().split(' ')
n,k=int(n),int(k)
arr=list(map(int,stdin.readline().strip().split(' ')))
def solve(n,k,arr):
sol=[]
l=0;u=k;
while l!=u:
sol.append(arr[l:min(len(arr),u)])
l=min(l+k,len(arr))
u=min(u+k,len(arr))
tiwari=[]
for i in range(k):
titi=0
gao=0
for j in range(len(sol)):
if len(sol[j])>i:
if sol[j][i]==0:
titi+=1
else:
gao+=1
tiwari.append((titi,gao))
minflip=(-1,-1)
ans=0
ctr=0
for i in tiwari:
if i[0]<i[1]:
ans+=i[0]
ctr+=(1*a1+a0*a1)*a1
if i[1]<minflip[0] or minflip[0]==-1:
minflip=(i[1],i[0])
else:
ans+=i[1]
if i[0]<minflip[0] or minflip[0]==-1:
minflip=(i[0],i[1])
#print(ans,ctr)
#print(tiwari)
#print(minflip)
if ctr%2==0:
ans+=minflip[0]
ans-=minflip[1]
stdout.write(str(ans)+"\n")
solve(n,k,arr) | # cook your dish here
from sys import stdin,stdout
a0=0
a1=1
n,k=stdin.readline().strip().split(' ')
n,k=int(n),int(k)
arr=list(map(int,stdin.readline().strip().split(' ')))
def solve(n,k,arr):
sol=[]
l=0;u=k;
while l!=u:
sol.append(arr[l:min(len(arr),u)])
l=min(l+k,len(arr))
u=min(u+k,len(arr))
tiwari=[]
for i in range(k):
titi=0
gao=0
for j in range(len(sol)):
if len(sol[j])>i:
if sol[j][i]==0:
titi+=1
else:
gao+=1
tiwari.append((titi,gao))
minflip=(-1,-1)
ans=0
ctr=0
for i in tiwari:
if i[0]<i[1]:
ans+=i[0]
ctr+=(1*a1+a0*a1)*a1
if i[1]<minflip[0] or minflip[0]==-1:
minflip=(i[1],i[0])
else:
ans+=i[1]
if i[0]<minflip[0] or minflip[0]==-1:
minflip=(i[0],i[1])
#print(ans,ctr)
#print(tiwari)
#print(minflip)
if ctr%2==0:
ans+=minflip[0]
ans-=minflip[1]
stdout.write(str(ans)+"\n")
solve(n,k,arr) | train | APPS_structured |
You've came to visit your grandma and she straight away found you a job - her Christmas tree needs decorating!
She first shows you a tree with an identified number of branches, and then hands you a some baubles (or loads of them!).
You know your grandma is a very particular person and she would like the baubles to be distributed in the orderly manner. You decide the best course of action would be to put the same number of baubles on each of the branches (if possible) or add one more bauble to some of the branches - starting from the beginning of the tree.
In this kata you will return an array of baubles on each of the branches.
For example:
10 baubles, 2 branches: [5,5]
5 baubles, 7 branches: [1,1,1,1,1,0,0]
12 baubles, 5 branches: [3,3,2,2,2]
The numbers of branches and baubles will be always greater or equal to 0.
If there are 0 branches return: "Grandma, we will have to buy a Christmas tree first!".
Good luck - I think your granny may have some minced pies for you if you do a good job! | from itertools import cycle, islice
from collections import Counter
def baubles_on_tree(baubles, branches):
return [Counter(islice(cycle(range(branches)), baubles))[x] for x in range(branches)] or "Grandma, we will have to buy a Christmas tree first!" | from itertools import cycle, islice
from collections import Counter
def baubles_on_tree(baubles, branches):
return [Counter(islice(cycle(range(branches)), baubles))[x] for x in range(branches)] or "Grandma, we will have to buy a Christmas tree first!" | train | APPS_structured |
You are teaching a class of $N$ students. Today, during the morning prayer, all the students are standing in a line. You are given a string $s$ with length $N$; for each valid $i$, the $i$-th character of this string is 'b' if the $i$-th student in the line is a boy or 'g' if this student is a girl.
The awkwardness of this configuration of students is defined as the sum of pairwise distances between each boy and girl. The distance between the $i$-th and $j$-th student in the line is $|i - j|$. Formally, the awkwardness is ∑i=1N∑j=i+1sj≠siN(j−i).∑i=1N∑j=i+1sj≠siN(j−i).\sum\limits_{i=1}^N \, \sum\limits_{j=i+1\\ s_j \neq s_i}^N (j - i)\,.
As the teacher, it is your responsibility to reorder the students in such a way that the awkwardness of the resulting configuration is the smallest possible. You may reorder the students in the line in any way you want. Find the minimum awkwardness that can be achieved.
-----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 string $s$.
-----Output-----
For each test case, print a single line containing one integer - the minimum possible awkwardness.
-----Constraints-----
- $1 \le T \le 10^5$
- $1 \le |s| \le 10^5$
- each character of $s$ is either 'b' or 'g'
- the sum of $|s|$ over all test cases does not exceed $4 \cdot 10^6$
-----Example Input-----
3
gb
bgg
bbgg
-----Example Output-----
1
2
6
-----Explanation-----
Example case 1: The total awkwardness is $|1 - 0| = 1$, no matter how you arrange the students.
Example case 2: Initially, the awkwardness is $|1 - 0| + |2 - 0| = 1 + 2 = 3$. However, you can move the boy between the two girls, i.e. choose the configuration "gbg". Here, the awkwardness is $|1 - 0| + |2 - 1| = 1 + 1 = 2$. | # cook your dish here
try:
T = int(input())
for i in range (0,T):
s = input()
p, q = s.count("b"), s.count("g")
d = 0
c = q - p
r = c // 2
if len(s) == 0:
print(d)
else:
if p == q:
d = (q*(2*(q**2)+1))/3
elif p>q:
d = (q*(2*(q**2)+1))/3
c = p - q
r = c // 2
d = d + (q*r*(2*q + r))
elif q>p:
d = (p*(2*(p**2)+1))/3
d = d + (p*r*(2*p + r))
if r == c / 2:
print(int(d))
else:
if q<p:
d = d + q*r + q**2
else:
d = d + p*r + p**2
print(int(d))
except:
pass
| # cook your dish here
try:
T = int(input())
for i in range (0,T):
s = input()
p, q = s.count("b"), s.count("g")
d = 0
c = q - p
r = c // 2
if len(s) == 0:
print(d)
else:
if p == q:
d = (q*(2*(q**2)+1))/3
elif p>q:
d = (q*(2*(q**2)+1))/3
c = p - q
r = c // 2
d = d + (q*r*(2*q + r))
elif q>p:
d = (p*(2*(p**2)+1))/3
d = d + (p*r*(2*p + r))
if r == c / 2:
print(int(d))
else:
if q<p:
d = d + q*r + q**2
else:
d = d + p*r + p**2
print(int(d))
except:
pass
| train | APPS_structured |
Initially, there is a Robot at position (0, 0). Given a sequence of its moves, judge if this robot makes a circle, which means it moves back to the original place.
The move sequence is represented by a string. And each move is represent by a character. The valid robot moves are R (Right), L (Left), U (Up) and D (down). The output should be true or false representing whether the robot makes a circle.
Example 1:
Input: "UD"
Output: true
Example 2:
Input: "LL"
Output: false | class Solution:
def judgeCircle(self, moves):
"""
:type moves: str
:rtype: bool
"""
pos = [0,0]
for i in moves:
if i == 'U':
pos[0] = pos[0] + 1
elif i == 'D':
pos[0] = pos[0] - 1
elif i == 'L':
pos[1] = pos[1] - 1
elif i == 'R':
pos[1] = pos[1] + 1
return [0,0] == pos | class Solution:
def judgeCircle(self, moves):
"""
:type moves: str
:rtype: bool
"""
pos = [0,0]
for i in moves:
if i == 'U':
pos[0] = pos[0] + 1
elif i == 'D':
pos[0] = pos[0] - 1
elif i == 'L':
pos[1] = pos[1] - 1
elif i == 'R':
pos[1] = pos[1] + 1
return [0,0] == pos | train | APPS_structured |
Consider a sequence `u` where u is defined as follows:
1. The number `u(0) = 1` is the first one in `u`.
2. For each `x` in `u`, then `y = 2 * x + 1` and `z = 3 * x + 1` must be in `u` too.
3. There are no other numbers in `u`.
Ex:
`u = [1, 3, 4, 7, 9, 10, 13, 15, 19, 21, 22, 27, ...]`
1 gives 3 and 4, then 3 gives 7 and 10, 4 gives 9 and 13, then 7 gives 15 and 22 and so on...
## Task:
Given parameter `n` the function `dbl_linear` (or dblLinear...) returns the element `u(n)` of
the ordered (with <) sequence `u` (so, there are no duplicates).
## Example:
`dbl_linear(10) should return 22`
## Note:
Focus attention on efficiency | from collections import deque
def dbl_linear(n):
u, q2, q3 = 1, deque([]), deque([])
for _ in range(n):
q2.append(2 * u + 1)
q3.append(3 * u + 1)
u = min(q2[0], q3[0])
if u == q2[0]: q2.popleft()
if u == q3[0]: q3.popleft()
return u | from collections import deque
def dbl_linear(n):
u, q2, q3 = 1, deque([]), deque([])
for _ in range(n):
q2.append(2 * u + 1)
q3.append(3 * u + 1)
u = min(q2[0], q3[0])
if u == q2[0]: q2.popleft()
if u == q3[0]: q3.popleft()
return u | train | APPS_structured |
Today was a sad day. Having bought a new beard trimmer, I set it to the max setting and shaved away at my joyous beard. Stupidly, I hadnt checked just how long the max setting was, and now I look like Ive just started growing it!
Your task, given a beard represented as an arrayof arrays, is to trim the beard as follows:
['|', 'J', '|', '|'],
['|', '|', '|', 'J'],
['...', '...', '...', '...'];
To trim the beard use the following rules:
trim any curled hair --> replace 'J' with '|'
trim any hair from the chin (last array) --> replace '|' or 'J' with '...'
All sub arrays will be same length. Return the corrected array of arrays | def trim(beard):
return [[h.replace("J", "|") for h in b] for b in beard[:-1]] + [["..."]*len(beard[0])] | def trim(beard):
return [[h.replace("J", "|") for h in b] for b in beard[:-1]] + [["..."]*len(beard[0])] | train | APPS_structured |
Chef has a calculator which has two screens and two buttons. Initially, each screen shows the number zero. Pressing the first button increments the number on the first screen by 1, and each click of the first button consumes 1 unit of energy.
Pressing the second button increases the number on the second screen by the number which is currently appearing on the first screen. Each click of the second button consumes B units of energy.
Initially the calculator has N units of energy.
Now chef wonders what the maximum possible number is, that he gets on the second screen of the calculator, with the limited energy.
-----Input-----
The first line of the input contains an integer T denoting the number of test cases.
Each test case is described using a single line containing two integers, N and B.
-----Output-----
For each test case, output a single line containing the answer to this test case.
-----Constraints-----
- 1 ≤ T ≤ 10,000
- 1 ≤ N, B ≤ 1,000,000,000
-----Subtasks-----
- Subtask 1 (20 points): 1 ≤ N, B ≤ 1,000
- Subtask 2 (80 points): Original constraints
-----Example-----
Input:
3
10 2
8 5
6 1
Output:
12
3
9
-----Explanation-----
Example case 1. There are 10 units of energy available. Pressing second button takes 2 units of energy. Chef can achieve 12 on the second screen as follows.
- Press first button to get scores (1, 0). 9 units of energey is left.
- Press first button to get scores (2, 0). 8 units of energy remaining.
- Press first button to get scores (3, 0). 7 units of energy remaining.
- Press first button to get scores (4, 0). 6 units of energy remaining.
- Press second button to get scores (4, 4). 4 units of energy remaining.
- Press second button to get scores (4, 8). 2 units of energy remaining.
- Press second button to get scores (4, 12). 0 units of energy remaining. | # cook your dish here
for i in range(int(input())):
n,b=map(int,input().split())
ans=round(n/(2*b))*(n-b*round((n/(2*b))));
print(ans) | # cook your dish here
for i in range(int(input())):
n,b=map(int,input().split())
ans=round(n/(2*b))*(n-b*round((n/(2*b))));
print(ans) | train | APPS_structured |
We need you to implement a method of receiving commands over a network, processing the information and responding.
Our device will send a single packet to you containing data and an instruction which you must perform before returning your reply.
To keep things simple, we will be passing a single "packet" as a string.
Each "byte" contained in the packet is represented by 4 chars.
One packet is structured as below:
```
Header Instruction Data1 Data2 Footer
------ ------ ------ ------ ------
H1H1 0F12 0012 0008 F4F4
------ ------ ------ ------ ------
The string received in this case would be - "H1H10F1200120008F4F4"
Instruction: The calculation you should perform, always one of the below.
0F12 = Addition
B7A2 = Subtraction
C3D9 = Multiplication
FFFF = This instruction code should be used to identify your return value.
```
- The Header and Footer are unique identifiers which you must use to form your reply.
- Data1 and Data2 are the decimal representation of the data you should apply your instruction to. _i.e 0109 = 109._
- Your response must include the received header/footer, a "FFFF" instruction code, and the result of your calculation stored in Data1.
- Data2 should be zero'd out to "0000".
```
To give a complete example:
If you receive message "H1H10F1200120008F4F4".
The correct response would be "H1H1FFFF00200000F4F4"
```
In the event that your calculation produces a negative result, the value returned should be "0000", similarily if the value is above 9999 you should return "9999".
Goodluck, I look forward to reading your creative solutions! | import operator
funcs = {'0F12': operator.add, 'B7A2': operator.sub, 'C3D9': operator.mul}
def communication_module(packet):
instruction, one, two = packet[4:8], int(packet[8:12]), int(packet[12:16])
result = funcs[instruction](one, two)
if result > 9999:
result = 9999
elif result < 0:
result = 0
return '{}FFFF{:0>4}0000{}'.format(packet[:4], result, packet[16:]) | import operator
funcs = {'0F12': operator.add, 'B7A2': operator.sub, 'C3D9': operator.mul}
def communication_module(packet):
instruction, one, two = packet[4:8], int(packet[8:12]), int(packet[12:16])
result = funcs[instruction](one, two)
if result > 9999:
result = 9999
elif result < 0:
result = 0
return '{}FFFF{:0>4}0000{}'.format(packet[:4], result, packet[16:]) | train | APPS_structured |
## Overview
Resistors are electrical components marked with colorful stripes/bands to indicate both their resistance value in ohms and how tight a tolerance that value has. If you did my Resistor Color Codes kata, you wrote a function which took a string containing a resistor's band colors, and returned a string identifying the resistor's ohms and tolerance values.
Well, now you need that in reverse: The previous owner of your "Beyond-Ultimate Raspberry Pi Starter Kit" (as featured in my Fizz Buzz Cuckoo Clock kata) had emptied all the tiny labeled zip-lock bags of components into the box, so that for each resistor you need for a project, instead of looking for text on a label, you need to find one with the sequence of band colors that matches the ohms value you need.
## The resistor color codes
You can see this Wikipedia page for a colorful chart, but the basic resistor color codes are:
0: black, 1: brown, 2: red, 3: orange, 4: yellow, 5: green, 6: blue, 7: violet, 8: gray, 9: white
All resistors have at least three bands, with the first and second bands indicating the first two digits of the ohms value, and the third indicating the power of ten to multiply them by, for example a resistor with a value of 47 ohms, which equals 47 * 10^0 ohms, would have the three bands "yellow violet black".
Most resistors also have a fourth band indicating tolerance -- in an electronics kit like yours, the tolerance will always be 5%, which is indicated by a gold band. So in your kit, the 47-ohm resistor in the above paragraph would have the four bands "yellow violet black gold".
## Your mission
Your function will receive a string containing the ohms value you need, followed by a space and the word "ohms" (to avoid Codewars unicode headaches I'm just using the word instead of the ohms unicode symbol). The way an ohms value is formatted depends on the magnitude of the value:
* For resistors less than 1000 ohms, the ohms value is just formatted as the plain number. For example, with the 47-ohm resistor above, your function would receive the string `"47 ohms"`, and return the string `"yellow violet black gold".
* For resistors greater than or equal to 1000 ohms, but less than 1000000 ohms, the ohms value is divided by 1000, and has a lower-case "k" after it. For example, if your function received the string `"4.7k ohms"`, it would need to return the string `"yellow violet red gold"`.
* For resistors of 1000000 ohms or greater, the ohms value is divided by 1000000, and has an upper-case "M" after it. For example, if your function received the string `"1M ohms"`, it would need to return the string `"brown black green gold"`.
Test case resistor values will all be between 10 ohms and 990M ohms.
## More examples, featuring some common resistor values from your kit
```
"10 ohms" "brown black black gold"
"100 ohms" "brown black brown gold"
"220 ohms" "red red brown gold"
"330 ohms" "orange orange brown gold"
"470 ohms" "yellow violet brown gold"
"680 ohms" "blue gray brown gold"
"1k ohms" "brown black red gold"
"10k ohms" "brown black orange gold"
"22k ohms" "red red orange gold"
"47k ohms" "yellow violet orange gold"
"100k ohms" "brown black yellow gold"
"330k ohms" "orange orange yellow gold"
"2M ohms" "red black green gold"
```
Have fun! | import re
import math
REGEX_NUMBERS = r"\d+\.?\d*"
RESISTOR_COLORS = {0: 'black', 1: 'brown', 2: 'red', 3: 'orange', 4: 'yellow', 5: 'green', 6: 'blue', 7: 'violet', 8: 'gray', 9: 'white'}
MULTIPLIER = {'k': 1000, 'M': 1000000}
def encode_resistor_colors(ohms_string):
retrieved_val = re.findall(REGEX_NUMBERS, ohms_string.replace('ohms', ''))[0]
needs_trailing_zero = len(retrieved_val) == 1
retrieved_val = retrieved_val + '0' if needs_trailing_zero else retrieved_val
translation = ' '.join([RESISTOR_COLORS[int(digit)] for digit in retrieved_val if digit.isnumeric()][:2])
for key in MULTIPLIER:
retrieved_val = float(retrieved_val) * MULTIPLIER.get(key) if key in ohms_string else float(retrieved_val)
subtract = 2 if needs_trailing_zero else 1
return translation + ' '+(RESISTOR_COLORS[math.floor(math.log10(retrieved_val)) - subtract]) + ' gold' | import re
import math
REGEX_NUMBERS = r"\d+\.?\d*"
RESISTOR_COLORS = {0: 'black', 1: 'brown', 2: 'red', 3: 'orange', 4: 'yellow', 5: 'green', 6: 'blue', 7: 'violet', 8: 'gray', 9: 'white'}
MULTIPLIER = {'k': 1000, 'M': 1000000}
def encode_resistor_colors(ohms_string):
retrieved_val = re.findall(REGEX_NUMBERS, ohms_string.replace('ohms', ''))[0]
needs_trailing_zero = len(retrieved_val) == 1
retrieved_val = retrieved_val + '0' if needs_trailing_zero else retrieved_val
translation = ' '.join([RESISTOR_COLORS[int(digit)] for digit in retrieved_val if digit.isnumeric()][:2])
for key in MULTIPLIER:
retrieved_val = float(retrieved_val) * MULTIPLIER.get(key) if key in ohms_string else float(retrieved_val)
subtract = 2 if needs_trailing_zero else 1
return translation + ' '+(RESISTOR_COLORS[math.floor(math.log10(retrieved_val)) - subtract]) + ' gold' | train | APPS_structured |
This kata is part one of precise fractions series (see pt. 2: http://www.codewars.com/kata/precise-fractions-pt-2-conversion).
When dealing with fractional values, there's always a problem with the precision of arithmetical operations. So lets fix it!
Your task is to implement class ```Fraction``` that takes care of simple fraction arithmetics. Requirements:
* class must have two-parameter constructor `Fraction(numerator, denominator)`; passed values will be non-zero integers, and may be positive or negative.
* two conversion methods must be supported:
* `toDecimal()` returns decimal representation of fraction
* `toString()` returns string with fractional representation of stored value in format:
[ SIGN ] [ WHOLES ] [ NUMERATOR / DENOMINATOR ]
* **Note**: each part is returned only if it is available and non-zero, with the only possible space character going between WHOLES and fraction. Examples: '-1/2', '3', '-5 3/4'
* The fractional part must always be normalized (ie. the numerator and denominators must not have any common divisors).
* Four operations need to be implemented: `add`, `subtract`, `multiply` and `divide`. Each of them may take integers as well as another `Fraction` instance as an argument, and must return a new `Fraction` instance.
* Instances must be immutable, hence none of the operations may modify either of the objects it is called upon, nor the passed argument.
#### Python Notes
* If one integer is passed into the initialiser, then the fraction should be assumed to represent an integer not a fraction.
* You must implement the standard operator overrides `__add__`, `__sub__`, `__mul__`, `__div__`, in each case you should support `other` being an `int` or another instance of `Fraction`.
* Implement `__str__` and `to_decimal` in place of `toString` and `toDecimal` as described above. | from fractions import Fraction
def to_string(self):
n, d = self.numerator, self.denominator
s, w, n = "-" if n < 0 else "", *divmod(abs(n), d)
r = " ".join((str(w) if w else "", f"{n}/{d}" if n else "")).strip()
return f"{s}{r}"
Fraction.__str__ = to_string
Fraction.to_decimal = lambda self: self.numerator / self.denominator | from fractions import Fraction
def to_string(self):
n, d = self.numerator, self.denominator
s, w, n = "-" if n < 0 else "", *divmod(abs(n), d)
r = " ".join((str(w) if w else "", f"{n}/{d}" if n else "")).strip()
return f"{s}{r}"
Fraction.__str__ = to_string
Fraction.to_decimal = lambda self: self.numerator / self.denominator | train | APPS_structured |
## Sum Even Fibonacci Numbers
* Write a func named SumEvenFibonacci that takes a parameter of type int and returns a value of type int
* Generate all of the Fibonacci numbers starting with 1 and 2 and ending on the highest number before exceeding the parameter's value
#### Each new number in the Fibonacci sequence is generated by adding the previous two numbers - by starting with 1 and 2(the input could be smaller), the first 10 numbers will be:
```
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
```
* Sum all of the even numbers you generate and return that int
#### Example:
```
sumEvenFibonacci(8) // returns 10 by adding the even values 2 and 8
``` | def SumEvenFibonacci(limit):
a,b,s = 1,1,0
while a <= limit:
if not a%2: s += a
a,b = b, a+b
return s | def SumEvenFibonacci(limit):
a,b,s = 1,1,0
while a <= limit:
if not a%2: s += a
a,b = b, a+b
return s | train | APPS_structured |
In a forest, each rabbit has some color. Some subset of rabbits (possibly all of them) tell you how many other rabbits have the same color as them. Those answers are placed in an array.
Return the minimum number of rabbits that could be in the forest.
Examples:
Input: answers = [1, 1, 2]
Output: 5
Explanation:
The two rabbits that answered "1" could both be the same color, say red.
The rabbit than answered "2" can't be red or the answers would be inconsistent.
Say the rabbit that answered "2" was blue.
Then there should be 2 other blue rabbits in the forest that didn't answer into the array.
The smallest possible number of rabbits in the forest is therefore 5: 3 that answered plus 2 that didn't.
Input: answers = [10, 10, 10]
Output: 11
Input: answers = []
Output: 0
Note:
answers will have length at most 1000.
Each answers[i] will be an integer in the range [0, 999]. | from collections import Counter
class Poly():
def __init__(self,v):
self.c = Counter()
self.c[''] = 0
if isinstance(v,int):
self.c[''] = v
elif isinstance(v,str):
self.c[v] = 1
elif isinstance(v,Counter):
self.c = v
def __add__(self,other):
cn = Counter()
for el,c in self.c.items():
cn[el] += c
for el, c in other.c.items():
cn[el] += c
return Poly(cn)
def __sub__(self,other):
cn = Counter()
for el,c in self.c.items():
cn[el] += c
for el, c in other.c.items():
cn[el] -= c
return Poly(cn)
def __mul__(self,other):
cn = Counter()
for el1, v1 in self.c.items():
for el2, v2 in other.c.items():
#print(el1.split('*'))
sn = '*'.join(sorted(it for it in el1.split('*')+el2.split('*') if it != ''))
cn[sn] += v1*v2
return Poly(cn)
def toList(self):
vet = []
def comp(key):
el = key[0]
v = [it for it in el.split('*') if it != '']
return (-len(v),v)
for el,v in sorted(self.c.items(), key = comp):
#print(len(el),el,v)
if v == 0:
continue
vap = [str(v)]
vap += [it for it in el.split('*') if it != '']
#print(vap)
vet.append('*'.join(vap))
return vet
def __str__(self):
return str(self.c)
def rfind(vet,v):
for i in range(len(vet)-1,-1,-1):
if vet[i] == v:
return i
return -1
class Solution:
def basicCalculatorIV(self, expression, evalvars, evalints):
"""
:type expression: str
:type evalvars: List[str]
:type evalints: List[int]
:rtype: List[str]
"""
valToInt = dict(zip(evalvars,evalints))
self.i = 0
def parse():
parsed = []
while self.i < len(expression):
ch = expression[self.i]
if ch.isalpha():
s = ''
while self.i < len(expression) and expression[self.i].isalpha():
s += expression[self.i]
self.i += 1
parsed.append(s if s not in valToInt else valToInt[s])
elif ch.isdigit():
s = ''
while self.i < len(expression) and expression[self.i].isdigit():
s += expression[self.i]
self.i += 1
parsed.append(int(s))
elif ch in '+-*':
self.i += 1
parsed.append(ch)
elif ch == '(':
self.i += 1
parsed.append(parse())
elif ch == ')':
self.i += 1
return parsed
else:
self.i += 1
return parsed
parsed = parse()
def polyPlus(vet):
if '+' in vet:
i = vet.index('+')
#print(polyPlus(vet[:i])+polyPlus(vet[i+1:]))
return polyPlus(vet[:i])+polyPlus(vet[i+1:])
return polyMinus(vet)
def polyMinus(vet):
if '-' in vet:
i = rfind(vet,'-')
#print(polyMinus(vet[:1])-polyMinus(vet[2:]))
return polyMinus(vet[:i])-polyMinus(vet[i+1:])
return polyTimes(vet)
def polyTimes(vet):
if '*' in vet:
i = vet.index('*')
return polyTimes(vet[:i])*polyTimes(vet[i+1:])
return polyElement(vet)
def polyElement(vet):
if len(vet) == 0:
return Poly(None)
assert len(vet) == 1
el = vet[0]
if isinstance(el,list):
return polyPlus(el)
return Poly(el)
polyAns = polyPlus(parsed)
ans = polyAns.toList()
return ans
| from collections import Counter
class Poly():
def __init__(self,v):
self.c = Counter()
self.c[''] = 0
if isinstance(v,int):
self.c[''] = v
elif isinstance(v,str):
self.c[v] = 1
elif isinstance(v,Counter):
self.c = v
def __add__(self,other):
cn = Counter()
for el,c in self.c.items():
cn[el] += c
for el, c in other.c.items():
cn[el] += c
return Poly(cn)
def __sub__(self,other):
cn = Counter()
for el,c in self.c.items():
cn[el] += c
for el, c in other.c.items():
cn[el] -= c
return Poly(cn)
def __mul__(self,other):
cn = Counter()
for el1, v1 in self.c.items():
for el2, v2 in other.c.items():
#print(el1.split('*'))
sn = '*'.join(sorted(it for it in el1.split('*')+el2.split('*') if it != ''))
cn[sn] += v1*v2
return Poly(cn)
def toList(self):
vet = []
def comp(key):
el = key[0]
v = [it for it in el.split('*') if it != '']
return (-len(v),v)
for el,v in sorted(self.c.items(), key = comp):
#print(len(el),el,v)
if v == 0:
continue
vap = [str(v)]
vap += [it for it in el.split('*') if it != '']
#print(vap)
vet.append('*'.join(vap))
return vet
def __str__(self):
return str(self.c)
def rfind(vet,v):
for i in range(len(vet)-1,-1,-1):
if vet[i] == v:
return i
return -1
class Solution:
def basicCalculatorIV(self, expression, evalvars, evalints):
"""
:type expression: str
:type evalvars: List[str]
:type evalints: List[int]
:rtype: List[str]
"""
valToInt = dict(zip(evalvars,evalints))
self.i = 0
def parse():
parsed = []
while self.i < len(expression):
ch = expression[self.i]
if ch.isalpha():
s = ''
while self.i < len(expression) and expression[self.i].isalpha():
s += expression[self.i]
self.i += 1
parsed.append(s if s not in valToInt else valToInt[s])
elif ch.isdigit():
s = ''
while self.i < len(expression) and expression[self.i].isdigit():
s += expression[self.i]
self.i += 1
parsed.append(int(s))
elif ch in '+-*':
self.i += 1
parsed.append(ch)
elif ch == '(':
self.i += 1
parsed.append(parse())
elif ch == ')':
self.i += 1
return parsed
else:
self.i += 1
return parsed
parsed = parse()
def polyPlus(vet):
if '+' in vet:
i = vet.index('+')
#print(polyPlus(vet[:i])+polyPlus(vet[i+1:]))
return polyPlus(vet[:i])+polyPlus(vet[i+1:])
return polyMinus(vet)
def polyMinus(vet):
if '-' in vet:
i = rfind(vet,'-')
#print(polyMinus(vet[:1])-polyMinus(vet[2:]))
return polyMinus(vet[:i])-polyMinus(vet[i+1:])
return polyTimes(vet)
def polyTimes(vet):
if '*' in vet:
i = vet.index('*')
return polyTimes(vet[:i])*polyTimes(vet[i+1:])
return polyElement(vet)
def polyElement(vet):
if len(vet) == 0:
return Poly(None)
assert len(vet) == 1
el = vet[0]
if isinstance(el,list):
return polyPlus(el)
return Poly(el)
polyAns = polyPlus(parsed)
ans = polyAns.toList()
return ans
| train | APPS_structured |
Chef is solving mathematics problems. He is preparing for Engineering Entrance exam. He's stuck in a problem.
$f(n)=1^n*2^{n-1}*3^{n-2} * \ldots * n^{1} $
Help Chef to find the value of $f(n)$.Since this number could be very large, compute it modulo $1000000007$.
-----Input:-----
- First line will contain $T$, number of testcases. Then the testcases follow.
- Each testcase contains of a single line of input, $N$.
-----Output:-----
For each testcase, output in a single line the value of $f(n)$ mod $1000000007$.
-----Constraints-----
- $1 \leq T \leq 10^6$
- $1 \leq N \leq 10^6$
-----Subtasks-----
Subtask 1(24 points) :
- $1 \leq T \leq 5000$
- $1 \leq N \leq 5000$
Subtask 2(51 points) : original constraints
-----Sample Input:-----
1
3
-----Sample Output:-----
12 | #dt = {} for i in x: dt[i] = dt.get(i,0)+1
import sys;input = sys.stdin.readline
inp,ip = lambda :int(input()),lambda :[int(w) for w in input().split()]
M = 10**9+7
f = [1]*(1000001)
for i in range(2,1000001):
f[i] = (i*f[i-1])%M
for i in range(2,1000001):
f[i] = (f[i]*f[i-1])%M
for _ in range(inp()):
n = inp()
print(f[n]) | #dt = {} for i in x: dt[i] = dt.get(i,0)+1
import sys;input = sys.stdin.readline
inp,ip = lambda :int(input()),lambda :[int(w) for w in input().split()]
M = 10**9+7
f = [1]*(1000001)
for i in range(2,1000001):
f[i] = (i*f[i-1])%M
for i in range(2,1000001):
f[i] = (f[i]*f[i-1])%M
for _ in range(inp()):
n = inp()
print(f[n]) | train | APPS_structured |
# Remove Duplicates
You are to write a function called `unique` that takes an array of integers and returns the array with duplicates removed. It must return the values in the same order as first seen in the given array. Thus no sorting should be done, if 52 appears before 10 in the given array then it should also be that 52 appears before 10 in the returned array.
## Assumptions
* All values given are integers (they can be positive or negative).
* You are given an array but it may be empty.
* They array may have duplicates or it may not.
## Example
```python
print unique([1, 5, 2, 0, 2, -3, 1, 10])
[1, 5, 2, 0, -3, 10]
print unique([])
[]
print unique([5, 2, 1, 3])
[5, 2, 1, 3]
``` | def unique(integers):
ans = []
for x in integers:
if x not in ans:
ans.append(x)
return ans | def unique(integers):
ans = []
for x in integers:
if x not in ans:
ans.append(x)
return ans | train | APPS_structured |
You are given a sequence of a journey in London, UK. The sequence will contain bus **numbers** and TFL tube names as **strings** e.g.
```python
['Northern', 'Central', 243, 1, 'Victoria']
```
Journeys will always only contain a combination of tube names and bus numbers. Each tube journey costs `£2.40` and each bus journey costs `£1.50`. If there are `2` or more adjacent bus journeys, the bus fare is capped for sets of two adjacent buses and calculated as one bus fare for each set.
Your task is to calculate the total cost of the journey and return the cost `rounded to 2 decimal places` in the format (where x is a number): `£x.xx` | from itertools import groupby
def london_city_hacker(journey):
arr = list(map(type,journey))
s = 0
for k,g in groupby(arr):
g = len(list(g))
if k==str:
s += 2.4*g
else:
s += 1.5*(g//2+(1 if g%2 else 0) if g>1 else g)
return f'£{round(s,2):.2f}' | from itertools import groupby
def london_city_hacker(journey):
arr = list(map(type,journey))
s = 0
for k,g in groupby(arr):
g = len(list(g))
if k==str:
s += 2.4*g
else:
s += 1.5*(g//2+(1 if g%2 else 0) if g>1 else g)
return f'£{round(s,2):.2f}' | train | APPS_structured |
To give credit where credit is due: This problem was taken from the ACMICPC-Northwest Regional Programming Contest. Thank you problem writers.
You are helping an archaeologist decipher some runes. He knows that this ancient society used a Base 10 system, and that they never start a number with a leading zero. He's figured out most of the digits as well as a few operators, but he needs your help to figure out the rest.
The professor will give you a simple math expression, of the form
```
[number][op][number]=[number]
```
He has converted all of the runes he knows into digits. The only operators he knows are addition (`+`),subtraction(`-`), and multiplication (`*`), so those are the only ones that will appear. Each number will be in the range from -1000000 to 1000000, and will consist of only the digits 0-9, possibly a leading -, and maybe a few ?s. If there are ?s in an expression, they represent a digit rune that the professor doesn't know (never an operator, and never a leading -). All of the ?s in an expression will represent the same digit (0-9), and it won't be one of the other given digits in the expression. No number will begin with a 0 unless the number itself is 0, therefore 00 would not be a valid number.
Given an expression, figure out the value of the rune represented by the question mark. If more than one digit works, give the lowest one. If no digit works, well, that's bad news for the professor - it means that he's got some of his runes wrong. output -1 in that case.
Complete the method to solve the expression to find the value of the unknown rune. The method takes a string as a paramater repressenting the expression and will return an int value representing the unknown rune or -1 if no such rune exists.
~~~if:php
**Most of the time, the professor will be able to figure out most of the runes himself, but sometimes, there may be exactly 1 rune present in the expression that the professor cannot figure out (resulting in all question marks where the digits are in the expression) so be careful ;)**
~~~ | import re
def solve_runes(runes):
# 分解
m = re.match(r'(-?[0-9?]+)([-+*])(-?[0-9?]+)=(-?[0-9?]+)', runes)
nums = [m.group(1),m.group(3),m.group(4)]
op = m.group(2)
# 迭代尝试
for v in range(0,10):
# 同字校验
if str(v) in runes:
continue
testNums = [num.replace('?',str(v)) for num in nums]
# 0起始校验
for num in testNums:
if re.match(r"(^0|^(-0))[0-9]+",num):
break
else:
# 判等
if int(testNums[2]) == eval(testNums[0] + op + testNums[1]):
return v
return -1 | import re
def solve_runes(runes):
# 分解
m = re.match(r'(-?[0-9?]+)([-+*])(-?[0-9?]+)=(-?[0-9?]+)', runes)
nums = [m.group(1),m.group(3),m.group(4)]
op = m.group(2)
# 迭代尝试
for v in range(0,10):
# 同字校验
if str(v) in runes:
continue
testNums = [num.replace('?',str(v)) for num in nums]
# 0起始校验
for num in testNums:
if re.match(r"(^0|^(-0))[0-9]+",num):
break
else:
# 判等
if int(testNums[2]) == eval(testNums[0] + op + testNums[1]):
return v
return -1 | train | APPS_structured |
The chef was not happy with the binary number system, so he designed a new machine which is having 6 different states, i.e. in binary there is a total of 2 states as 0 and 1. Now, the chef is confused about how to correlate this machine to get an interaction with Integer numbers, when N(Integer number) is provided to the system, what will be the Nth number that system will return(in Integer form), help the chef to design this system.
-----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 given by the system.
-----Constraints-----
- $1 \leq T \leq 10^5$
- $1 \leq N \leq 10^5$
-----Sample Input:-----
2
3
5
-----Sample Output:-----
7
37
-----EXPLANATION:-----
Initial numbers for system = [1, 6, 7, 36, 37, 42, 43, 216, …..
For 1) 3rd Number for the system will be 7.
For 2) 5th Number for the system will be 37. | import sys
# cook your dish here
T=int(input())
system=[0,1]
new_multiplier=1
while(len(system)<110000):
new_multiplier*=6
new_list=list( int(x+new_multiplier) for x in system)
system+=new_list
for t in range(T):
N=int(input())
print(system[N])
| import sys
# cook your dish here
T=int(input())
system=[0,1]
new_multiplier=1
while(len(system)<110000):
new_multiplier*=6
new_list=list( int(x+new_multiplier) for x in system)
system+=new_list
for t in range(T):
N=int(input())
print(system[N])
| train | APPS_structured |
A category page displays a set number of products per page, with pagination at the bottom allowing the user to move from page to page.
Given that you know the page you are on, how many products are in the category in total, and how many products are on any given page, how would you output a simple string showing which products you are viewing..
examples
In a category of 30 products with 10 products per page, on page 1 you would see
'Showing 1 to 10 of 30 Products.'
In a category of 26 products with 10 products per page, on page 3 you would see
'Showing 21 to 26 of 26 Products.'
In a category of 8 products with 10 products per page, on page 1 you would see
'Showing 1 to 8 of 8 Products.' | def pagination_text(page_number, page_size, total_products):
return "Showing %d to %d of %d Products." % (
page_size * (page_number - 1) + 1,
min(total_products, page_size * page_number),
total_products)
| def pagination_text(page_number, page_size, total_products):
return "Showing %d to %d of %d Products." % (
page_size * (page_number - 1) + 1,
min(total_products, page_size * page_number),
total_products)
| train | APPS_structured |
Vietnamese and Bengali as well.
An $N$-bonacci sequence is an infinite sequence $F_1, F_2, \ldots$ such that for each integer $i > N$, $F_i$ is calculated as $f(F_{i-1}, F_{i-2}, \ldots, F_{i-N})$, where $f$ is some function. A XOR $N$-bonacci sequence is an $N$-bonacci sequence for which $f(F_{i-1}, F_{i-2}, \ldots, F_{i-N}) = F_{i-1} \oplus F_{i−2} \oplus \ldots \oplus F_{i−N}$, where $\oplus$ denotes the bitwise XOR operation.
Recently, Chef has found an interesting sequence $S_1, S_2, \ldots$, which is obtained from prefix XORs of a XOR $N$-bonacci sequence $F_1, F_2, \ldots$. Formally, for each positive integer $i$, $S_i = F_1 \oplus F_2 \oplus \ldots \oplus F_i$. You are given the first $N$ elements of the sequence $F$, which uniquely determine the entire sequence $S$.
You should answer $Q$ queries. In each query, you are given an index $k$ and you should calculate $S_k$. It is guaranteed that in each query, $S_k$ does not exceed $10^{50}$.
-----Input-----
- The first line of the input contains two space-separated integers $N$ and $Q$.
- The second line contains $N$ space-separated integers $F_1, F_2, \ldots, F_N$.
- The following $Q$ lines describe queries. Each of these lines contains a single integer $k$.
-----Output-----
For each query, print a single line containing one integer $S_k$.
-----Constraints-----
- $1 \le N, Q \le 10^5$
- $0 \le F_i \le 10^9$ for each $i$ such that $1 \le i \le N$
- $1 \le k \le 10^9$
-----Example Input-----
3 4
0 1 2
7
2
5
1000000000
-----Example Output-----
3
1
0
0 | n,q=list(map(int,input().split()))
arr=[int(n) for n in input().split()]
x=arr[0]
arr1=[]
arr1.append(x)
for i in range(1,n):
x=x^arr[i]
arr1.append(x)
arr1.append(0)
while(q):
q=q-1
x=int(input())
r=x%(n+1)
print(arr1[r-1])
| n,q=list(map(int,input().split()))
arr=[int(n) for n in input().split()]
x=arr[0]
arr1=[]
arr1.append(x)
for i in range(1,n):
x=x^arr[i]
arr1.append(x)
arr1.append(0)
while(q):
q=q-1
x=int(input())
r=x%(n+1)
print(arr1[r-1])
| train | APPS_structured |
A startup office has an ongoing problem with its bin. Due to low budgets, they don't hire cleaners. As a result, the staff are left to voluntarily empty the bin. It has emerged that a voluntary system is not working and the bin is often overflowing. One staff member has suggested creating a rota system based upon the staff seating plan.
Create a function `binRota` that accepts a 2D array of names. The function will return a single array containing staff names in the order that they should empty the bin.
Adding to the problem, the office has some temporary staff. This means that the seating plan changes every month. Both staff members' names and the number of rows of seats may change. Ensure that the function `binRota` works when tested with these changes.
**Notes:**
- All the rows will always be the same length as each other.
- There will be no empty spaces in the seating plan.
- There will be no empty arrays.
- Each row will be at least one seat long.
An example seating plan is as follows:
![](http://i.imgur.com/aka6lh0l.png)
Or as an array:
```
[ ["Stefan", "Raj", "Marie"],
["Alexa", "Amy", "Edward"],
["Liz", "Claire", "Juan"],
["Dee", "Luke", "Katie"] ]
```
The rota should start with Stefan and end with Dee, taking the left-right zigzag path as illustrated by the red line:
As an output you would expect in this case:
```
["Stefan", "Raj", "Marie", "Edward", "Amy", "Alexa", "Liz", "Claire", "Juan", "Katie", "Luke", "Dee"])
``` | def binRota(arr):
return [seat for row, seats in enumerate(arr) for seat in seats[::(-1)**row]]
| def binRota(arr):
return [seat for row, seats in enumerate(arr) for seat in seats[::(-1)**row]]
| train | APPS_structured |
Consider an array containing cats and dogs. Each dog can catch only one cat, but cannot catch a cat that is more than `n` elements away. Your task will be to return the maximum number of cats that can be caught.
For example:
```Haskell
solve(['D','C','C','D','C'], 2) = 2, because the dog at index 0 (D0) catches C1 and D3 catches C4.
solve(['C','C','D','D','C','D'], 2) = 3, because D2 catches C0, D3 catches C1 and D5 catches C4.
solve(['C','C','D','D','C','D'], 1) = 2, because D2 catches C1, D3 catches C4. C0 cannot be caught because n == 1.
solve(['D','C','D','D','C'], 1) = 2, too many dogs, so all cats get caught!
```
Do not modify the input array.
More examples in the test cases. Good luck! | def solve(arr,n):
c,l = 0,len(arr)
for i in range(l):
if arr[i] == 'C':
a = max(0,i-n)
b = min(l-1,i+n)
for j in range(a,b+1):
if arr[j] == 'D':
arr[j] = 'd'
c += 1
break
return c | def solve(arr,n):
c,l = 0,len(arr)
for i in range(l):
if arr[i] == 'C':
a = max(0,i-n)
b = min(l-1,i+n)
for j in range(a,b+1):
if arr[j] == 'D':
arr[j] = 'd'
c += 1
break
return c | train | APPS_structured |
Assume `"#"` is like a backspace in string. This means that string `"a#bc#d"` actually is `"bd"`
Your task is to process a string with `"#"` symbols.
## Examples
```
"abc#d##c" ==> "ac"
"abc##d######" ==> ""
"#######" ==> ""
"" ==> ""
``` | import re
def clean_string(s):
return clean_string(re.sub('[^#]{1}#', '', s).lstrip('#')) if '#' in s else s
| import re
def clean_string(s):
return clean_string(re.sub('[^#]{1}#', '', s).lstrip('#')) if '#' in s else s
| train | APPS_structured |
Chef works in a similar way to a travelling salesman ― he always travels to new cities in order to sell his delicious dishes.
Today, Chef is planning to visit $N$ cities (numbered $1$ through $N$). There is a direct way to travel between each pair of cities. Each city has a specific temperature; let's denote the temperature in the $i$-th city by $C_i$. Chef has a fixed temperature tolerance $D$ with the following meaning: for each pair of cities $a$ and $b$, he may travel from city $a$ directly to city $b$ only if $|C_a-C_b| \le D$, otherwise he would catch a heavy flu because of the sudden change in temperature.
Chef starts from city $1$. Is he able to visit all $N$ cities in such a way that each city is visited exactly once?
Notes:
- Chef is not able to travel through a city without visiting it.
- City $1$ is visited at the beginning.
- It is not necessary to be able to travel directly to city $1$ from the last city Chef visits.
-----Input-----
- The first line of the input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows.
- The first line of each test case contains two space-separated integers $N$ and $D$.
- The second line contains $N$ space-separated integers $C_1, C_2, \ldots, C_N$.
-----Output-----
For each test case, print a single line containing the string "YES" (without quotes) if Chef can visit all cities or "NO" (without quotes) if he cannot.
-----Constraints-----
- $1 \le T \le 1,000$
- $2 \le N \le 10^5$
- $0 \le D \le 10^9$
- $0 \le C_i \le 10^9$ for each valid $i$
- the sum of $N$ over all test cases does not exceed $10^6$
-----Subtasks-----
Subtask #1 (20 points):
- $N \le 1,000$
- the sum of $N$ over all test cases does not exceed $10,000$
Subtask #2 (80 points): original constraints
-----Example Input-----
2
5 3
3 2 1 4 5
5 4
10 1 3 2 9
-----Example Output-----
YES
NO | def left(a, pos):
if pos == 0 or pos == len(a) - 1:
return True
for i in range(pos + 1, len(a)):
if a[i] - a[i - 2] > d:
return False
return True
def right(a ,pos):
for i in range(pos - 1, -1, -1):
if a[i + 2] - a[i] > d:
return False
return True
for _ in range(int(input())):
n, d = map(int, input().split())
a = list(map(int,input().split()))
startVal = a[0]
a.sort()
f = 1
startPos = 0
for i, e in enumerate(a[1: ]):
if e - a[i] > d:
f = 0
break
if e == startVal:
startPos = i + 1
if f and (left(a, startPos) or right(a, startPos)):
print("YES")
else:
print("NO") | def left(a, pos):
if pos == 0 or pos == len(a) - 1:
return True
for i in range(pos + 1, len(a)):
if a[i] - a[i - 2] > d:
return False
return True
def right(a ,pos):
for i in range(pos - 1, -1, -1):
if a[i + 2] - a[i] > d:
return False
return True
for _ in range(int(input())):
n, d = map(int, input().split())
a = list(map(int,input().split()))
startVal = a[0]
a.sort()
f = 1
startPos = 0
for i, e in enumerate(a[1: ]):
if e - a[i] > d:
f = 0
break
if e == startVal:
startPos = i + 1
if f and (left(a, startPos) or right(a, startPos)):
print("YES")
else:
print("NO") | train | APPS_structured |
Complete the method so that it formats the words into a single comma separated value. The last word should be separated by the word 'and' instead of a comma. The method takes in an array of strings and returns a single formatted string. Empty string values should be ignored. Empty arrays or null/nil values being passed into the method should result in an empty string being returned.
```Python
format_words(['ninja', 'samurai', 'ronin']) # should return "ninja, samurai and ronin"
format_words(['ninja', '', 'ronin']) # should return "ninja and ronin"
format_words([]) # should return ""
```
```Haskell
formatWords ["ninja", "samurai", "ronin"] -- should return "ninja, samurai and ronin"
formatWords ["ninja", "", "ronin"] -- should return "ninja and ronin"
formatWords [] -- should return ""
``` | def format_words(words):
words = [w for w in words if w] if words else ''
if not words:
return ''
return f'{", ".join(words[:-1])} and {words[-1]}' if len(words) !=1 else words[-1] | def format_words(words):
words = [w for w in words if w] if words else ''
if not words:
return ''
return f'{", ".join(words[:-1])} and {words[-1]}' if len(words) !=1 else words[-1] | train | APPS_structured |
Sort the given strings in alphabetical order, case **insensitive**. For example:
```
["Hello", "there", "I'm", "fine"] --> ["fine", "Hello", "I'm", "there"]
["C", "d", "a", "B"]) --> ["a", "B", "C", "d"]
``` | sortme=lambda w:sorted(w,key=lambda x:x.lower()) | sortme=lambda w:sorted(w,key=lambda x:x.lower()) | train | APPS_structured |
You have to write a function that describe Leo:
```python
def leo(oscar):
pass
```
if oscar was (integer) 88, you have to return "Leo finally won the oscar! Leo is happy".
if oscar was 86, you have to return "Not even for Wolf of wallstreet?!"
if it was not 88 or 86 (and below 88) you should return "When will you give Leo an Oscar?"
if it was over 88 you should return "Leo got one already!" | def leo(oscar):
return "Not even for Wolf of wallstreet?!" if oscar==86 else "When will you give Leo an Oscar?" if oscar<88 else "Leo finally won the oscar! Leo is happy" if oscar == 88 else "Leo got one already!" | def leo(oscar):
return "Not even for Wolf of wallstreet?!" if oscar==86 else "When will you give Leo an Oscar?" if oscar<88 else "Leo finally won the oscar! Leo is happy" if oscar == 88 else "Leo got one already!" | train | APPS_structured |
You are given array of integers, your task will be to count all pairs in that array and return their count.
**Notes:**
* Array can be empty or contain only one value; in this case return `0`
* If there are more pairs of a certain number, count each pair only once. E.g.: for `[0, 0, 0, 0]` the return value is `2` (= 2 pairs of `0`s)
* Random tests: maximum array length is 1000, range of values in array is between 0 and 1000
## Examples
```
[1, 2, 5, 6, 5, 2] --> 2
```
...because there are 2 pairs: `2` and `5`
```
[1, 2, 2, 20, 6, 20, 2, 6, 2] --> 4
```
...because there are 4 pairs: `2`, `20`, `6` and `2` (again) | def duplicates(arr):
return sum((arr.count(n) // 2 for n in set(arr))) | def duplicates(arr):
return sum((arr.count(n) // 2 for n in set(arr))) | train | APPS_structured |
The Gray code (see wikipedia for more details) is a well-known concept.
One of its important properties is that every two adjacent numbers have exactly one different digit in their binary representation.
In this problem, we will give you n non-negative integers in a sequence A[1..n] (0<=A[i]<2^64), such that every two adjacent integers have exactly one different digit in their binary representation, similar to the Gray code.
Your task is to check whether there exist 4 numbers A[i1], A[i2], A[i3], A[i4] (1 <= i1 < i2 < i3 < i4 <= n) out of the given n numbers such that A[i1] xor A[i2] xor A[i3] xor A[i4] = 0. Here xor is a bitwise operation which is same as ^ in C, C++, Java and xor in Pascal.
-----Input-----
First line contains one integer n (4<=n<=100000).
Second line contains n space seperated non-negative integers denoting the sequence A.
-----Output-----
Output “Yes” (quotes exclusive) if there exist four distinct indices i1, i2, i3, i4 such that A[i1] xor A[i2] xor A[i3] xor A[i4] = 0. Otherwise, output "No" (quotes exclusive) please.
-----Example-----
Input:
5
1 0 2 3 7
Output:
Yes | n = int(input())
s = input()
s = s.split()
d = {}
flag = "No"
two,four = 0,0
for i in s:
if i in d:
d[i] += 1;
if d[i] == 2:
two += 1
elif d[i] == 4:
four += 1
else:
d[i] = 1;
if two>1 or four>0:
flag = "Yes"
else:
for i in range(n-1):
ex = int(s[i]) ^ int(s[i+1])
if ex in d:
d[ex].append(i)
if d[ex][-1] - d[ex][0] > 1:
flag = "Yes"
break;
else:
d[ex] = [i]
print(flag)
| n = int(input())
s = input()
s = s.split()
d = {}
flag = "No"
two,four = 0,0
for i in s:
if i in d:
d[i] += 1;
if d[i] == 2:
two += 1
elif d[i] == 4:
four += 1
else:
d[i] = 1;
if two>1 or four>0:
flag = "Yes"
else:
for i in range(n-1):
ex = int(s[i]) ^ int(s[i+1])
if ex in d:
d[ex].append(i)
if d[ex][-1] - d[ex][0] > 1:
flag = "Yes"
break;
else:
d[ex] = [i]
print(flag)
| train | APPS_structured |
Given a set of numbers, return the additive inverse of each. Each positive becomes negatives, and the negatives become positives.
~~~if-not:racket
```
invert([1,2,3,4,5]) == [-1,-2,-3,-4,-5]
invert([1,-2,3,-4,5]) == [-1,2,-3,4,-5]
invert([]) == []
```
~~~
```if:javascript,python,ruby,php,elixir,dart
You can assume that all values are integers. Do not mutate the input array/list.
```
```if:c
### Notes:
- All values are greater than `INT_MIN`
- The input should be modified, not returned.
```
~~~if:racket
```racket
(invert '(1 2 3 4 5)) ; '(-1 -2 -3 -4 -5)
(invert '(1 -2 3 -4 5)) ; '(-1 2 -3 4 -5)
(invert '()) ; '()
```
~~~ | def invert(lst):
lstCopy = lst[:]
for i in range(len(lst)):
lstCopy[i]*=-1
return lstCopy | def invert(lst):
lstCopy = lst[:]
for i in range(len(lst)):
lstCopy[i]*=-1
return lstCopy | train | APPS_structured |
Mr. Wire Less is not that good at implementing circuit in a breadboard. In his Digital Logic Design course, he has to implement several boolean functions using the breadboard. In a breadboard, inputs are given through the switches and outputs are taken through the LEDs. Each input switch can be either in ground state or in high state. So, if he wishes to implement a boolean function, f(x1, x2, .., xn) that takes n boolean values as input and returns m boolean values as output, he will use n switches and m LEDs.
Mr. Wire Less can quickly assemble the necessary ICs and wires, but the key problem is testing. While testing he has to check with all possible input combination, to make sure whether the output of LED corresponds to the expected output or not. This is taking too long for him, as most of the switches are jammed and difficult to toggle.
Mr. Wire Less is asking for help to minimize his time of testing. So, your task is to minimize the total number of switch-toggle throughout the testing.
For example, if Mr. Wire Less has to test a function f(x0, x1) of two variables, he may choose this switching-sequence for testing 00, 11, 10, 01. In this case, the total number of switch-toggle will be 2+1+2 = 5. But if he tests in this sequence 00, 10, 11, 01 total number of toggle will be 1+1+1 = 3.
Given n, you have to output the minimum number of toggle needed for complete testing. Though it seems impractical, he wants you to solve the problem for a very large value of n. But, then the toggle value can be quite big. So, he is completely okay with the toggle value modulo 8589934592 (233).
-----Input-----
The first line of the input contains a positive integer T(T ≤ 105), denoting the number of test-case. Each of the following T lines contains a single non-negative integer n(n ≤ 1020).
-----Output-----
For every test-case, output a single containing test-case number and the minimum number of switch-toggle modulo 8589934592 (233).
-----Sample-----
Input
2
1
2
Output
Case 1: 1
Case 2: 3 | # cook your dish here
'''#include <bits/stdc++.h>
#include <math.h>
using namespace std;
main(){
long long a=pow(2,1000000000000000000,8589934592);
printf("%lld",a);
}'''
a=int(input())
for i in range(a):
b=int(input())
aa=pow(2,b,8589934592)
print("Case",str(i+1)+":",(aa-1)%(8589934592)) | # cook your dish here
'''#include <bits/stdc++.h>
#include <math.h>
using namespace std;
main(){
long long a=pow(2,1000000000000000000,8589934592);
printf("%lld",a);
}'''
a=int(input())
for i in range(a):
b=int(input())
aa=pow(2,b,8589934592)
print("Case",str(i+1)+":",(aa-1)%(8589934592)) | train | APPS_structured |
Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.
(i.e., [0,0,1,2,2,5,6] might become [2,5,6,0,0,1,2]).
You are given a target value to search. If found in the array return true, otherwise return false.
Example 1:
Input: nums = [2,5,6,0,0,1,2], target = 0
Output: true
Example 2:
Input: nums = [2,5,6,0,0,1,2], target = 3
Output: false
Follow up:
This is a follow up problem to Search in Rotated Sorted Array, where nums may contain duplicates.
Would this affect the run-time complexity? How and why? | class Solution:
res = False
def searchR(self, nums, target, start, end):
if(start > end or self.res == True):
return self.res
else:
mid = int((start + end) / 2)
print("Mid index: %d, Mid val: %d, Target: %d" % (mid, nums[mid], target))
if(nums[mid] == target):
self.res = True
elif(nums[start] <= nums[mid]):
if(nums[mid] == nums[end]):
self.searchR(nums, target, start, mid - 1)
self.searchR(nums, target, mid+1, end)
elif (target >= nums[start] and target <= nums[mid]):
self.searchR(nums, target, start, mid - 1)
else:
self.searchR(nums, target, mid+1, end)
else:
print("Here")
if (target >= nums[mid] and target <= nums[end]):
self.searchR(nums, target, mid + 1, end)
else:
self.searchR(nums, target, start, mid - 1)
return self.res
def search(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: bool
"""
res = self.searchR(nums, target, 0, (len(nums) - 1))
return res | class Solution:
res = False
def searchR(self, nums, target, start, end):
if(start > end or self.res == True):
return self.res
else:
mid = int((start + end) / 2)
print("Mid index: %d, Mid val: %d, Target: %d" % (mid, nums[mid], target))
if(nums[mid] == target):
self.res = True
elif(nums[start] <= nums[mid]):
if(nums[mid] == nums[end]):
self.searchR(nums, target, start, mid - 1)
self.searchR(nums, target, mid+1, end)
elif (target >= nums[start] and target <= nums[mid]):
self.searchR(nums, target, start, mid - 1)
else:
self.searchR(nums, target, mid+1, end)
else:
print("Here")
if (target >= nums[mid] and target <= nums[end]):
self.searchR(nums, target, mid + 1, end)
else:
self.searchR(nums, target, start, mid - 1)
return self.res
def search(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: bool
"""
res = self.searchR(nums, target, 0, (len(nums) - 1))
return res | train | APPS_structured |
Passer ratings are the generally accepted standard for evaluating NFL quarterbacks.
I knew a rating of 100 is pretty good, but never knew what makes up the rating.
So out of curiosity I took a look at the wikipedia page and had an idea or my first kata: https://en.wikipedia.org/wiki/Passer_rating
## Formula
There are four parts to the NFL formula:
```python
A = ((Completions / Attempts) - .3) * 5
B = ((Yards / Attempts) - 3) * .25
C = (Touchdowns / Attempt) * 20
D = 2.375 - ((Interceptions / Attempts) * 25)
```
However, if the result of any calculation is greater than `2.375`, it is set to `2.375`. If the result is a negative number, it is set to zero.
Finally the passer rating is: `((A + B + C + D) / 6) * 100`
Return the rating rounded to the nearest tenth.
## Example
Last year Tom Brady had 432 attempts, 3554 yards, 291 completions, 28 touchdowns, and 2 interceptions.
His passer rating was 112.2
Happy coding! | def passer_rating(attempts, yards, completions, touchdowns, interceptions):
a = (completions / attempts - .3) * 5
b = (yards / attempts - 3) * .25
c = (touchdowns / attempts) * 20
d = 2.375 - (interceptions / attempts * 25)
a, b, c, d = (max(0, min(x, 2.375)) for x in (a, b, c, d))
return round((a + b + c + d) / 6 * 100, 1) | def passer_rating(attempts, yards, completions, touchdowns, interceptions):
a = (completions / attempts - .3) * 5
b = (yards / attempts - 3) * .25
c = (touchdowns / attempts) * 20
d = 2.375 - (interceptions / attempts * 25)
a, b, c, d = (max(0, min(x, 2.375)) for x in (a, b, c, d))
return round((a + b + c + d) / 6 * 100, 1) | train | APPS_structured |
Given a string s of lower and upper case English letters.
A good string is a string which doesn't have two adjacent characters s[i] and s[i + 1] where:
0 <= i <= s.length - 2
s[i] is a lower-case letter and s[i + 1] is the same letter but in upper-case or vice-versa.
To make the string good, you can choose two adjacent characters that make the string bad and remove them. You can keep doing this until the string becomes good.
Return the string after making it good. The answer is guaranteed to be unique under the given constraints.
Notice that an empty string is also good.
Example 1:
Input: s = "leEeetcode"
Output: "leetcode"
Explanation: In the first step, either you choose i = 1 or i = 2, both will result "leEeetcode" to be reduced to "leetcode".
Example 2:
Input: s = "abBAcC"
Output: ""
Explanation: We have many possible scenarios, and all lead to the same answer. For example:
"abBAcC" --> "aAcC" --> "cC" --> ""
"abBAcC" --> "abBA" --> "aA" --> ""
Example 3:
Input: s = "s"
Output: "s"
Constraints:
1 <= s.length <= 100
s contains only lower and upper case English letters. | class Solution:
def makeGood(self, s: str) -> str:
if len(s) == 1:
return s
for i in range(len(s) - 2, -1, -1):
if s[i].lower() == s[i+1].lower() and s[i] != s[i+1]:
s = s[:i] + s[i+2:]
return self.makeGood(s)
return s | class Solution:
def makeGood(self, s: str) -> str:
if len(s) == 1:
return s
for i in range(len(s) - 2, -1, -1):
if s[i].lower() == s[i+1].lower() and s[i] != s[i+1]:
s = s[:i] + s[i+2:]
return self.makeGood(s)
return s | train | APPS_structured |
Given a string and an array of integers representing indices, capitalize all letters at the given indices.
For example:
* `capitalize("abcdef",[1,2,5]) = "aBCdeF"`
* `capitalize("abcdef",[1,2,5,100]) = "aBCdeF"`. There is no index 100.
The input will be a lowercase string with no spaces and an array of digits.
Good luck!
Be sure to also try:
[Alternate capitalization](https://www.codewars.com/kata/59cfc000aeb2844d16000075)
[String array revisal](https://www.codewars.com/kata/59f08f89a5e129c543000069) | def capitalize(s, ind):
sy = list(s)
for i in ind:
try:
sy[i] = sy[i].upper()
except IndexError:
print("Index out of range")
return "".join(sy) | def capitalize(s, ind):
sy = list(s)
for i in ind:
try:
sy[i] = sy[i].upper()
except IndexError:
print("Index out of range")
return "".join(sy) | train | APPS_structured |
A string is called a happy prefix if is a non-empty prefix which is also a suffix (excluding itself).
Given a string s. Return the longest happy prefix of s .
Return an empty string if no such prefix exists.
Example 1:
Input: s = "level"
Output: "l"
Explanation: s contains 4 prefix excluding itself ("l", "le", "lev", "leve"), and suffix ("l", "el", "vel", "evel"). The largest prefix which is also suffix is given by "l".
Example 2:
Input: s = "ababab"
Output: "abab"
Explanation: "abab" is the largest prefix which is also suffix. They can overlap in the original string.
Example 3:
Input: s = "leetcodeleet"
Output: "leet"
Example 4:
Input: s = "a"
Output: ""
Constraints:
1 <= s.length <= 10^5
s contains only lowercase English letters. | class Solution:
def longestPrefix(self, s: str) -> str:
def build(p):
m = len(p)
nxt = [0,0]
j = 0
for i in range(1,m):
while j > 0 and s[i] != s[j]:
j = nxt[j]
if s[i] == s[j]:
j += 1
nxt.append(j)
return nxt
nxt = build(s)
return s[:nxt[-1]] | class Solution:
def longestPrefix(self, s: str) -> str:
def build(p):
m = len(p)
nxt = [0,0]
j = 0
for i in range(1,m):
while j > 0 and s[i] != s[j]:
j = nxt[j]
if s[i] == s[j]:
j += 1
nxt.append(j)
return nxt
nxt = build(s)
return s[:nxt[-1]] | train | APPS_structured |
Vasya and Petya are playing a simple game. Vasya thought of number x between 1 and n, and Petya tries to guess the number.
Petya can ask questions like: "Is the unknown number divisible by number y?".
The game is played by the following rules: first Petya asks all the questions that interest him (also, he can ask no questions), and then Vasya responds to each question with a 'yes' or a 'no'. After receiving all the answers Petya should determine the number that Vasya thought of.
Unfortunately, Petya is not familiar with the number theory. Help him find the minimum number of questions he should ask to make a guaranteed guess of Vasya's number, and the numbers y_{i}, he should ask the questions about.
-----Input-----
A single line contains number n (1 ≤ n ≤ 10^3).
-----Output-----
Print the length of the sequence of questions k (0 ≤ k ≤ n), followed by k numbers — the questions y_{i} (1 ≤ y_{i} ≤ n).
If there are several correct sequences of questions of the minimum length, you are allowed to print any of them.
-----Examples-----
Input
4
Output
3
2 4 3
Input
6
Output
4
2 4 3 5
-----Note-----
The sequence from the answer to the first sample test is actually correct.
If the unknown number is not divisible by one of the sequence numbers, it is equal to 1.
If the unknown number is divisible by 4, it is 4.
If the unknown number is divisible by 3, then the unknown number is 3.
Otherwise, it is equal to 2. Therefore, the sequence of questions allows you to guess the unknown number. It can be shown that there is no correct sequence of questions of length 2 or shorter. | def main():
n = int(input()) + 1
a, res = [True] * n, []
for p in range(2, n):
if a[p]:
pp = 1
while pp * p < n:
pp *= p
res.append(pp)
a[p:n:p] = [False] * ((n - 1) // p)
print(len(res))
print(*res)
def __starting_point():
main()
__starting_point() | def main():
n = int(input()) + 1
a, res = [True] * n, []
for p in range(2, n):
if a[p]:
pp = 1
while pp * p < n:
pp *= p
res.append(pp)
a[p:n:p] = [False] * ((n - 1) // p)
print(len(res))
print(*res)
def __starting_point():
main()
__starting_point() | train | APPS_structured |
### Problem Context
The [Fibonacci](http://en.wikipedia.org/wiki/Fibonacci_number) sequence is traditionally used to explain tree recursion.
```python
def fibonacci(n):
if n in [0, 1]:
return n
return fibonacci(n - 1) + fibonacci(n - 2)
```
This algorithm serves welll its educative purpose but it's [tremendously inefficient](http://mitpress.mit.edu/sicp/full-text/book/book-Z-H-11.html#%_sec_1.2.2), not only because of recursion, but because we invoke the fibonacci function twice, and the right branch of recursion (i.e. `fibonacci(n-2)`) recalculates all the Fibonacci numbers already calculated by the left branch (i.e. `fibonacci(n-1)`).
This algorithm is so inefficient that the time to calculate any Fibonacci number over 50 is simply too much. You may go for a cup of coffee or go take a nap while you wait for the answer. But if you try it here in Code Wars you will most likely get a code timeout before any answers.
For this particular Kata we want to **implement the memoization solution**. This will be cool because it will let us *keep using the tree recursion* algorithm while still keeping it sufficiently optimized to get an answer very rapidly.
The trick of the memoized version is that we will keep a cache data structure (most likely an associative array) where we will store the Fibonacci numbers as we calculate them. When a Fibonacci number is calculated, we first look it up in the cache, if it's not there, we calculate it and put it in the cache, otherwise we returned the cached number.
Refactor the function into a recursive Fibonacci function that using a memoized data structure avoids the deficiencies of tree recursion Can you make it so the memoization cache is private to this function? | from functools import lru_cache
@lru_cache()
def fibonacci(n):
if n in [0, 1]:
return n
return fibonacci(n - 1) + fibonacci(n - 2) | from functools import lru_cache
@lru_cache()
def fibonacci(n):
if n in [0, 1]:
return n
return fibonacci(n - 1) + fibonacci(n - 2) | train | APPS_structured |