input
stringlengths 50
13.9k
| output_program
stringlengths 5
655k
| output_answer
stringlengths 5
655k
| split
stringclasses 1
value | dataset
stringclasses 1
value |
---|---|---|---|---|
A great flood has hit the land, and just as in Biblical times we need to get the animals to the ark in pairs. We are only interested in getting one pair of each animal, and not interested in any animals where there are less than 2....they need to mate to repopulate the planet after all!
You will be given a list of animals, which you need to check to see which animals there are at least two of, and then return a dictionary containing the name of the animal along with the fact that there are 2 of them to bring onto the ark.
---
```python
>>> two_by_two(['goat', 'goat', 'rabbit', 'rabbit', 'rabbit', 'duck', 'horse', 'horse', 'swan'])
{'goat': 2, 'horse': 2, 'rabbit': 2}
# If the list of animals is empty, return False as there are no animals to bring onto the ark and we are all doomed!!!
>>> two_by_two([])
False
# If there are no pairs of animals, return an empty dictionary
>>> two_by_two(['goat'])
{}
``` | from collections import Counter
def two_by_two(a):
return {x: 2 for x, y in Counter(a).items() if y > 1} if a else 0 | from collections import Counter
def two_by_two(a):
return {x: 2 for x, y in Counter(a).items() if y > 1} if a else 0 | train | APPS_structured |
Chef is very fond of horses. He enjoys watching them race. As expected, he has a stable full of horses. He, along with his friends, goes to his stable during the weekends to watch a few of these horses race. Chef wants his friends to enjoy the race and so he wants the race to be close. This can happen only if the horses are comparable on their skill i.e. the difference in their skills is less.
There are N horses in the stable. The skill of the horse i is represented by an integer S[i]. The Chef needs to pick 2 horses for the race such that the difference in their skills is minimum. This way, he would be able to host a very interesting race. Your task is to help him do this and report the minimum difference that is possible between 2 horses in the race.
-----Input:-----
First line of the input file contains a single integer T, the number of test cases.
Every test case starts with a line containing the integer N.
The next line contains N space separated integers where the i-th integer is S[i].
-----Output:-----
For each test case, output a single line containing the minimum difference that is possible.
-----Constraints:-----
1 ≤ T ≤ 10
2 ≤ N ≤ 5000
1 ≤ S[i] ≤ 1000000000
-----Example:-----Input:
1
5
4 9 1 32 13
Output:
3
Explanation: The minimum difference can be achieved if we pick horses with skills 1 and 4 for the race. | #!/bin/python
t = eval(input())
while t > 0:
t-=1
n = eval(input())
str = input()
inp = str.split()
inp = list(map(int,inp))
inp.sort()
smallest = abs(inp[0] - inp[1])
for i in range(1,n-1):
temp = abs(inp[i] - inp[i+1])
if temp < smallest:
smallest = temp
print(smallest) | #!/bin/python
t = eval(input())
while t > 0:
t-=1
n = eval(input())
str = input()
inp = str.split()
inp = list(map(int,inp))
inp.sort()
smallest = abs(inp[0] - inp[1])
for i in range(1,n-1):
temp = abs(inp[i] - inp[i+1])
if temp < smallest:
smallest = temp
print(smallest) | train | APPS_structured |
There are n cities numbered from 0 to n-1. Given the array edges where edges[i] = [fromi, toi, weighti] represents a bidirectional and weighted edge between cities fromi and toi, and given the integer distanceThreshold.
Return the city with the smallest number of cities that are reachable through some path and whose distance is at most distanceThreshold, If there are multiple such cities, return the city with the greatest number.
Notice that the distance of a path connecting cities i and j is equal to the sum of the edges' weights along that path.
Example 1:
Input: n = 4, edges = [[0,1,3],[1,2,1],[1,3,4],[2,3,1]], distanceThreshold = 4
Output: 3
Explanation: The figure above describes the graph.
The neighboring cities at a distanceThreshold = 4 for each city are:
City 0 -> [City 1, City 2]
City 1 -> [City 0, City 2, City 3]
City 2 -> [City 0, City 1, City 3]
City 3 -> [City 1, City 2]
Cities 0 and 3 have 2 neighboring cities at a distanceThreshold = 4, but we have to return city 3 since it has the greatest number.
Example 2:
Input: n = 5, edges = [[0,1,2],[0,4,8],[1,2,3],[1,4,2],[2,3,1],[3,4,1]], distanceThreshold = 2
Output: 0
Explanation: The figure above describes the graph.
The neighboring cities at a distanceThreshold = 2 for each city are:
City 0 -> [City 1]
City 1 -> [City 0, City 4]
City 2 -> [City 3, City 4]
City 3 -> [City 2, City 4]
City 4 -> [City 1, City 2, City 3]
The city 0 has 1 neighboring city at a distanceThreshold = 2.
Constraints:
2 <= n <= 100
1 <= edges.length <= n * (n - 1) / 2
edges[i].length == 3
0 <= fromi < toi < n
1 <= weighti, distanceThreshold <= 10^4
All pairs (fromi, toi) are distinct. | def buildGraph(n, edges):
graph = [[float('inf')]*n for _ in range(n)]
for e in edges:
graph[e[0]][e[1]] = e[2]
graph[e[1]][e[0]] = e[2]
'''
Floyed-Warshall algorithm won't work if diagonal values are not set to
0 when self loop distance is not given
'''
for i in range(n):
graph[i][i] = 0
return graph
def floyedWarshalAllPairDist(graph):
n = len(graph)
for i in range(n):
for j in range(n):
for k in range(n):
graph[j][k] = min(graph[j][k], graph[j][i]+graph[i][k])
'''
Algorithm:
1) Measure all pair distance using Floyed Warshal algorithm
2) Find the city with minimum connected cities with atmost threshold distance
'''
class Solution:
def findTheCity(self, n: int, edges: List[List[int]], distanceThreshold: int) -> int:
'''
graph = buildGraph(n, edges)
floyedWarshalAllPairDist(graph)
min_city = 0
min_count = float('inf')
for i in range(n):
count = sum([1 if x<=distanceThreshold else 0 for x in graph[i]])
if count <= min_count:
min_count = count
min_city = i
return min_city
'''
g = [[float('inf')]*n for _ in range(n)]
for u,v,w in edges:
g[u][v] = w
g[v][u] = w
for i in range(n):
for u in range(n):
for v in range(n):
if u==v:
g[u][v]=0
else:
g[u][v] = min(g[u][v], g[u][i]+g[i][v])
city, count = -1,float('inf')
for i in range(n):
tmp = sum(1 for x in g[i] if x<=distanceThreshold)
if tmp<=count:
city = i
count = tmp
return city
| def buildGraph(n, edges):
graph = [[float('inf')]*n for _ in range(n)]
for e in edges:
graph[e[0]][e[1]] = e[2]
graph[e[1]][e[0]] = e[2]
'''
Floyed-Warshall algorithm won't work if diagonal values are not set to
0 when self loop distance is not given
'''
for i in range(n):
graph[i][i] = 0
return graph
def floyedWarshalAllPairDist(graph):
n = len(graph)
for i in range(n):
for j in range(n):
for k in range(n):
graph[j][k] = min(graph[j][k], graph[j][i]+graph[i][k])
'''
Algorithm:
1) Measure all pair distance using Floyed Warshal algorithm
2) Find the city with minimum connected cities with atmost threshold distance
'''
class Solution:
def findTheCity(self, n: int, edges: List[List[int]], distanceThreshold: int) -> int:
'''
graph = buildGraph(n, edges)
floyedWarshalAllPairDist(graph)
min_city = 0
min_count = float('inf')
for i in range(n):
count = sum([1 if x<=distanceThreshold else 0 for x in graph[i]])
if count <= min_count:
min_count = count
min_city = i
return min_city
'''
g = [[float('inf')]*n for _ in range(n)]
for u,v,w in edges:
g[u][v] = w
g[v][u] = w
for i in range(n):
for u in range(n):
for v in range(n):
if u==v:
g[u][v]=0
else:
g[u][v] = min(g[u][v], g[u][i]+g[i][v])
city, count = -1,float('inf')
for i in range(n):
tmp = sum(1 for x in g[i] if x<=distanceThreshold)
if tmp<=count:
city = i
count = tmp
return city
| train | APPS_structured |
# Task
In the city, a bus named Fibonacci runs on the road every day.
There are `n` stations on the route. The Bus runs from station1 to stationn.
At the departure station(station1), `k` passengers get on the bus.
At the second station(station2), a certain number of passengers get on and the same number get off. There are still `k` passengers on the bus.
From station3 to stationn-1, the number of boarding and alighting passengers follows the following rule:
- At stationi, the number of people getting on is the sum of the number of people getting on at the two previous stations(stationi-1 and stationi-2)
- The number of people getting off is equal to the number of people getting on at the previous station(stationi-1).
At stationn, all the passengers get off the bus.
Now, The numbers we know are: `k` passengers get on the bus at station1, `n` stations in total, `m` passengers get off the bus at stationn.
We want to know: How many passengers on the bus when the bus runs out stationx.
# Input
- `k`: The number of passengers get on the bus at station1.
- `1 <= k <= 100`
- `n`: The total number of stations(1-based).
- `6 <= n <= 30`
- `m`: The number of passengers get off the bus at stationn.
- `1 <= m <= 10^10`
- `x`: Stationx(1-based). The station we need to calculate.
- `3 <= m <= n-1`
- All inputs are valid integers.
# Output
An integer. The number of passengers on the bus when the bus runs out stationx. | def fibLikeGen():
a,b = (1,0), (0,1) # a: station i-1, b: station i
while 1:
yield a,b
a,b = b, tuple(x+y for x,y in zip(a,b))
gen = fibLikeGen()
SUM_AT = [(), (1,0), (1,0)] # (k,l)
def getCoefs(n):
while len(SUM_AT) <= n:
a,b = next(gen)
SUM_AT.append(tuple(x+y for x,y in zip(a,SUM_AT[-1])))
return SUM_AT[n]
def calc(k,n,m,x):
a,b = getCoefs(n-1)
l = (m-a*k) // b
a,b = getCoefs(x)
return a*k + b*l | def fibLikeGen():
a,b = (1,0), (0,1) # a: station i-1, b: station i
while 1:
yield a,b
a,b = b, tuple(x+y for x,y in zip(a,b))
gen = fibLikeGen()
SUM_AT = [(), (1,0), (1,0)] # (k,l)
def getCoefs(n):
while len(SUM_AT) <= n:
a,b = next(gen)
SUM_AT.append(tuple(x+y for x,y in zip(a,SUM_AT[-1])))
return SUM_AT[n]
def calc(k,n,m,x):
a,b = getCoefs(n-1)
l = (m-a*k) // b
a,b = getCoefs(x)
return a*k + b*l | train | APPS_structured |
The ZCO scholarship contest offers scholarships to first time ZCO participants. You are participating in it for the first time. So you want to know the number of participants who'll get the scholarship.
You know that the maximum number of scholarships offered is $R$ and there are a total of $N$ participants numbered from $1$ to $N$. Out of these, you know the set of people (denoted by $X$) who you know, had participated in previous year ZCOs and hence, they shall not get the scholarship.
Further, as the world isn't free from plagiarism, so is the case with the scholarship contest. And from your secret sources, you also know the set of people (denoted by set $Y$) who were involved in plagiarism and therefore aren't eligible for scholarship either.
Find out the number of participants who shall get the scholarship.
PS: Don't ask how so many scholarships are being offered when you see the constraints on $R$. You never questioned it when in mathematics classes, some person bought $80$ watermelons twice just to compare them and save $₹1$.
-----Input:-----
- The first line will contain a single integer, $T$, the number of testcases. Then the testcases follow.
- The first line of each test case contains four integers; $N$, $R$, $|X|$ and $|Y|$ denoting the number of participants, maximum number of scholarships offered, number of old participants, and the number of participants involved in plagiarism, respectively.
- The second line of each test case contains $|X|$ space separated integers $x_1, x_2 \ldots x_{|X|}$ denoting the indices of people who participated in previous years. If $X$ is empty, this line is skipped and no empty line is in the input.
- The third line of each test case contains $|Y|$ space separated integers $y_1, y_2 \ldots y_{|Y|}$ denoting the indices of people who are involved in plagiarism. If $Y$ is empty, this line is skipped and no empty line is in input.
-----Output:-----
For each testcase, print a single integer in a new line, denoting the number of participants who shall get the scholarship.
-----Constraints-----
- $1 \leq T \leq 1000$
- $1 \leq N \leq 10^{15}$
- $0 \leq R \leq 10^{15}$
- $0 \leq |X|, |Y| \leq min(N, 2*10^5)$
- $1 \leq x_i, y_i \leq N$
- All $x_i$ are distinct
- All $y_i$ are distinct
- Sum of $|X|$ over all test cases does not exceed $5*10^5$
- Sum of $|Y|$ over all test cases does not exceed $5*10^5$
-----Subtasks-----
- 20 points : $1 \leq N \leq 10^3$, and the sum of $N$ over all test cases does not exceed $3*10^3$
- 30 points : $1 \leq N \leq 2*10^5$, and the sum of $N$ over all test cases does not exceed $5*10^5$
- 50 points: Original constraints
-----Sample Input:-----
3
5 3 0 1
4
10 2 4 6
3 1 7 6
4 3 1 5 9 7
10 4 4 6
3 1 7 6
4 3 1 5 9 7
-----Sample Output:-----
3
2
3
-----EXPLANATION:-----
- In the first testcase, only participant $4$ is involved in plagiarism, and thus not eligible for the scholarship. No user has participated in previous years, and so no empty line is there in the sample. All participants except participant $4$ are eligible for the scholarship, but only three of them get it because $R = 3$.
- Both second and third testcases are the same, except for $R$. In both samples, only participants $2$, $8$ and $10$ are eligible for scholarships.
- In the second testcase, since the maximum number of scholarships is $2$, only $2$ participants get scholarships.
- In the third testcase, all three eligible participants get scholarships. | for _ in range(int(input())):
n, r, x, y = [int(x) for x in input().split()]
repeat = []
plagis = []
if x > 0:repeat = [int(x) for x in input().split()]
if y > 0:plagis = [int(x) for x in input().split()]
invalid = set(repeat).union(set(plagis))
print(min(r, n - len(invalid))) | for _ in range(int(input())):
n, r, x, y = [int(x) for x in input().split()]
repeat = []
plagis = []
if x > 0:repeat = [int(x) for x in input().split()]
if y > 0:plagis = [int(x) for x in input().split()]
invalid = set(repeat).union(set(plagis))
print(min(r, n - len(invalid))) | train | APPS_structured |
Given a string s, a k duplicate removal consists of choosing k adjacent and equal letters from s and removing them causing the left and the right side of the deleted substring to concatenate together.
We repeatedly make k duplicate removals on s until we no longer can.
Return the final string after all such duplicate removals have been made.
It is guaranteed that the answer is unique.
Example 1:
Input: s = "abcd", k = 2
Output: "abcd"
Explanation: There's nothing to delete.
Example 2:
Input: s = "deeedbbcccbdaa", k = 3
Output: "aa"
Explanation:
First delete "eee" and "ccc", get "ddbbbdaa"
Then delete "bbb", get "dddaa"
Finally delete "ddd", get "aa"
Example 3:
Input: s = "pbbcggttciiippooaais", k = 2
Output: "ps"
Constraints:
1 <= s.length <= 10^5
2 <= k <= 10^4
s only contains lower case English letters. | class Solution:
def removeDuplicates(self, s: str, k: int) -> str:
if not s or k == 0:
return s
stack = [['#', 0]]
for c in s:
if stack[-1][0] == c:
stack[-1][1] += 1
if stack[-1][1] == k:
stack.pop()
else:
stack.append([c, 1])
return ''.join(c*k for c, k in stack)
| class Solution:
def removeDuplicates(self, s: str, k: int) -> str:
if not s or k == 0:
return s
stack = [['#', 0]]
for c in s:
if stack[-1][0] == c:
stack[-1][1] += 1
if stack[-1][1] == k:
stack.pop()
else:
stack.append([c, 1])
return ''.join(c*k for c, k in stack)
| train | APPS_structured |
We all know the impressive story of Robin Hood. Robin Hood uses his archery skills and his wits to steal the money from rich, and return it to the poor.
There are n citizens in Kekoland, each person has c_{i} coins. Each day, Robin Hood will take exactly 1 coin from the richest person in the city and he will give it to the poorest person (poorest person right after taking richest's 1 coin). In case the choice is not unique, he will select one among them at random. Sadly, Robin Hood is old and want to retire in k days. He decided to spend these last days with helping poor people.
After taking his money are taken by Robin Hood richest person may become poorest person as well, and it might even happen that Robin Hood will give his money back. For example if all people have same number of coins, then next day they will have same number of coins too.
Your task is to find the difference between richest and poorest persons wealth after k days. Note that the choosing at random among richest and poorest doesn't affect the answer.
-----Input-----
The first line of the input contains two integers n and k (1 ≤ n ≤ 500 000, 0 ≤ k ≤ 10^9) — the number of citizens in Kekoland and the number of days left till Robin Hood's retirement.
The second line contains n integers, the i-th of them is c_{i} (1 ≤ c_{i} ≤ 10^9) — initial wealth of the i-th person.
-----Output-----
Print a single line containing the difference between richest and poorest peoples wealth.
-----Examples-----
Input
4 1
1 1 4 2
Output
2
Input
3 1
2 2 2
Output
0
-----Note-----
Lets look at how wealth changes through day in the first sample. [1, 1, 4, 2] [2, 1, 3, 2] or [1, 2, 3, 2]
So the answer is 3 - 1 = 2
In second sample wealth will remain the same for each person. | import sys
inp = sys.stdin.read().splitlines()
n,k = list(map(int,inp[0].split()))
lst = list(map(int,inp[1].split()))
lst.sort()
total = sum(lst)
lower = int(total/n)
nupper = total%n
if nupper == 0:
upper = lower;
else:
upper = lower+1;
nlower = n - nupper;
i = 0;
while i<n and lst[i]<lower:
i+=1
low1st = i;
i = n-1;
while i>=0 and lst[i]>upper:
i-=1
uplast = i;
lowerfill = low1st*lower - sum(lst[:low1st])
upperfill = sum(lst[uplast+1:]) - (n-uplast-1)*upper
totalsteps = (lowerfill+upperfill)/2
'''
print("nlower = %d"%nlower)
print("nupper = %d"%nupper)
print("lower = %d"%lower)
print("upper = %d"%upper)
print("lowerfill = %d"%lowerfill)
print("upperfill = %d"%upperfill)
print("totalsteps = %f"%totalsteps)
'''
def filllower():
kk = k
cur = lst[0]
i = 0
while (kk>0):
while (lst[i]==cur):
i+=1
#print("i=%d,lst[i]=%d"%(i,lst[i]))
diff = lst[i] - lst[i-1]
kk -= i*diff
#print("lower kk = %d",kk)
if kk == 0:
cur = lst[i]
break
elif kk<0:
cur = lst[i]-int(-kk/i)-1
#print("-kk/i = %d",int(-kk/i))
if (-kk%i) ==0:
cur += 1
break
cur = lst[i]
#print("min = ",cur)
return cur
def fillupper():
kk = k
i = n-1
cur = lst[i]
while (kk>0):
while (lst[i]==cur):
i-=1
#print("i=%d,lst[i]=%d"%(i,lst[i]))
diff = lst[i+1] - lst[i]
kk -= (n-i-1)*diff
#print("upper kk = ",kk)
if kk == 0:
cur = lst[i-1]
break
elif kk<0:
cur = lst[i]+int(-kk/(n-i-1))
if (-kk%(n-i-1)!=0):
cur += 1;
break
cur = lst[i]
#print("max = ",cur)
return cur
if totalsteps>=k:
print(fillupper()-filllower())
else:
print(upper-lower)
'''
def sortmax():
v = lst[-1]
i = n-2
while(i>=0):
if lst[i]<=v:
lst[-1]=lst[i+1]
lst[i+1]=v
return
i-=1
lst[-1]=lst[0]
lst[0]=v
def sortmin():
v = lst[0]
i = 1
while(i<n):
if lst[i]>=v:
lst[0]=lst[i-1]
lst[i-1]=v
return
i+=1
lst[0]=lst[-1]
lst[-1]=v
lst.sort()
while k:
lst[-1]-=1
sortmax()
#print(lst)
lst[0]+=1
sortmin()
if (lst[-1]-lst[0])<=1:
break
#print(lst)
k-=1
print(lst[-1]-lst[0])
'''
# Made By Mostafa_Khaled
| import sys
inp = sys.stdin.read().splitlines()
n,k = list(map(int,inp[0].split()))
lst = list(map(int,inp[1].split()))
lst.sort()
total = sum(lst)
lower = int(total/n)
nupper = total%n
if nupper == 0:
upper = lower;
else:
upper = lower+1;
nlower = n - nupper;
i = 0;
while i<n and lst[i]<lower:
i+=1
low1st = i;
i = n-1;
while i>=0 and lst[i]>upper:
i-=1
uplast = i;
lowerfill = low1st*lower - sum(lst[:low1st])
upperfill = sum(lst[uplast+1:]) - (n-uplast-1)*upper
totalsteps = (lowerfill+upperfill)/2
'''
print("nlower = %d"%nlower)
print("nupper = %d"%nupper)
print("lower = %d"%lower)
print("upper = %d"%upper)
print("lowerfill = %d"%lowerfill)
print("upperfill = %d"%upperfill)
print("totalsteps = %f"%totalsteps)
'''
def filllower():
kk = k
cur = lst[0]
i = 0
while (kk>0):
while (lst[i]==cur):
i+=1
#print("i=%d,lst[i]=%d"%(i,lst[i]))
diff = lst[i] - lst[i-1]
kk -= i*diff
#print("lower kk = %d",kk)
if kk == 0:
cur = lst[i]
break
elif kk<0:
cur = lst[i]-int(-kk/i)-1
#print("-kk/i = %d",int(-kk/i))
if (-kk%i) ==0:
cur += 1
break
cur = lst[i]
#print("min = ",cur)
return cur
def fillupper():
kk = k
i = n-1
cur = lst[i]
while (kk>0):
while (lst[i]==cur):
i-=1
#print("i=%d,lst[i]=%d"%(i,lst[i]))
diff = lst[i+1] - lst[i]
kk -= (n-i-1)*diff
#print("upper kk = ",kk)
if kk == 0:
cur = lst[i-1]
break
elif kk<0:
cur = lst[i]+int(-kk/(n-i-1))
if (-kk%(n-i-1)!=0):
cur += 1;
break
cur = lst[i]
#print("max = ",cur)
return cur
if totalsteps>=k:
print(fillupper()-filllower())
else:
print(upper-lower)
'''
def sortmax():
v = lst[-1]
i = n-2
while(i>=0):
if lst[i]<=v:
lst[-1]=lst[i+1]
lst[i+1]=v
return
i-=1
lst[-1]=lst[0]
lst[0]=v
def sortmin():
v = lst[0]
i = 1
while(i<n):
if lst[i]>=v:
lst[0]=lst[i-1]
lst[i-1]=v
return
i+=1
lst[0]=lst[-1]
lst[-1]=v
lst.sort()
while k:
lst[-1]-=1
sortmax()
#print(lst)
lst[0]+=1
sortmin()
if (lst[-1]-lst[0])<=1:
break
#print(lst)
k-=1
print(lst[-1]-lst[0])
'''
# Made By Mostafa_Khaled
| train | APPS_structured |
JavaScript provides a built-in parseInt method.
It can be used like this:
- `parseInt("10")` returns `10`
- `parseInt("10 apples")` also returns `10`
We would like it to return `"NaN"` (as a string) for the second case because the input string is not a valid number.
You are asked to write a `myParseInt` method with the following rules:
- It should make the conversion if the given string only contains a single integer value (and possibly spaces - including tabs, line feeds... - at both ends)
- For all other strings (including the ones representing float values), it should return NaN
- It should assume that all numbers are not signed and written in base 10 | def my_parse_int(string):
try:
return int(string)
except ValueError:
return 'NaN'
| def my_parse_int(string):
try:
return int(string)
except ValueError:
return 'NaN'
| train | APPS_structured |
In some countries of former Soviet Union there was a belief about lucky tickets. A transport ticket of any sort was believed to posess luck if sum of digits on the left half of its number was equal to the sum of digits on the right half. Here are examples of such numbers:
```
003111 # 3 = 1 + 1 + 1
813372 # 8 + 1 + 3 = 3 + 7 + 2
17935 # 1 + 7 = 3 + 5 // if the length is odd, you should ignore the middle number when adding the halves.
56328116 # 5 + 6 + 3 + 2 = 8 + 1 + 1 + 6
```
Such tickets were either eaten after being used or collected for bragging rights.
Your task is to write a funtion ```luck_check(str)```, which returns ```true/True``` if argument is string decimal representation of a lucky ticket number, or ```false/False``` for all other numbers. It should throw errors for empty strings or strings which don't represent a decimal number. | def luck_check(string):
e0, b1 = len(string) // 2, (len(string) + 1) // 2
return sum(map(int, string[:e0])) == sum(map(int, string[b1:])) | def luck_check(string):
e0, b1 = len(string) // 2, (len(string) + 1) // 2
return sum(map(int, string[:e0])) == sum(map(int, string[b1:])) | train | APPS_structured |
An area named Renus, is divided into $(N \times M)$ cells. According to archaeological survey the area contains huge amount of treasure. Some cells out of $(N \times M)$ cells contain treasure. But problem is, you can't go to every cell as some of the cells are blocked.
For every $a_{ij}$ cell($1 \leq i \leq N$,$1 \leq j \leq M$), your task is to find the distance of the nearest cell having treasure.
Note:
- You can only traverse up, down, left and right from a given cell.
- Diagonal movements are not allowed.
- Cells having treasure can't be blocked, only empty cells ( cells without treasure) can be blocked.
-----Input Format:------
- First line contains $T$, the number of test cases.
- Second line contains two space-separated integers $N\ and\ M$.
- Third line contains a single integer $X$ denoting number of cells having treasures, followed by $X$ lines containing two space-separated integers $x_i$ and $y_i$ denoting position of row and column of $i^{th}$ treasure, for every $1\leq i \leq X$
- The next line contains a single integer $Y$ denoting the number of cells that are blocked, and it is followed by subsequent $Y$ lines containing two space-separated integers $u_i$ and $v_i$ denoting position of row and column of blocked cells , for every $1\leq i \leq Y$
-----Constraints:------
- $1\le T \le 100$
- $1 \le N, M \le 200$
- $1 \le X < N*M$
- $0 \le Y <(N*M) - X$
- $1 \le x_i,u_j \le N, for\ every\ 1 \le i \le X\ and\ 1 \le j \le Y$
- $1 \le y_i,v_j \le M, for\ every\ 1 \le i \le X\ and\ 1 \le j \le Y$
-----Output Format:------
For each test case print a $N \times M$ matrix where each cell consists of distance of nearest treasure. Cells that are blocked will show "$X$" (without quotes). Also cells that doesn't have access to any treasure will show "$-1$" (without quotes).
Note: Co-ordinate of top left cell is $(1,1)$.
-----Sample Input-----
1
3 3
2
1 1
1 3
2
2 1
2 2
-----Sample Output-----
0 1 0
X X 1
4 3 2
-----Explanation:-----
- Coordinates (1,1) and (1,3) shows "0" because they contain treasure and nearest distance is 0.
- Coordinates (2,1) and (2,2) shows "X" as they are blocked.
- Rest shows distance of nearest cell having treasure. | t=int(input())
for _ in range(t):
n,m=[int(x) for x in input().split()]
mat=[]
ans=[]
for i in range(n+2):
l=[]
p=[]
for j in range(m+2):
l.append(0)
p.append(1000000000)
mat.append(l)
ans.append(p)
y=int(input())
for i in range(y):
a,b=[int(x) for x in input().split()]
mat[a][b]=1
ans[a][b]=0
y=int(input())
for i in range(y):
a,b=[int(x) for x in input().split()]
mat[a][b]=1000000000
ans[a][b]=1000000000
for i in range(1,n+1):
for j in range(1,m+1):
if mat[i][j]==1 or mat[i][j]==1000000000:
continue
else:
ans[i][j]=min(ans[i][j],ans[i][j-1]+1,ans[i-1][j]+1)
for i in range(n,0,-1):
for j in range(m,0,-1):
if mat[i][j] == 1 or mat[i][j] == 1000000000:
continue
else:
ans[i][j]=min(ans[i][j],ans[i+1][j]+1,ans[i][j+1]+1)
for i in range(1,n+1):
for j in range(m, 0, -1):
if mat[i][j] == 1 or mat[i][j] == 1000000000:
continue
else:
ans[i][j] = min(ans[i][j], ans[i - 1][j] + 1, ans[i][j + 1] + 1)
for i in range(n, 0, -1):
for j in range(1,m+1):
if mat[i][j] == 1 or mat[i][j] == 1000000000:
continue
else:
ans[i][j] = min(ans[i][j], ans[i + 1][j] + 1, ans[i][j - 1] + 1)
for i in range(1,n+1):
for j in range(1,m+1):
if mat[i][j]==1 or mat[i][j]==1000000000:
continue
else:
ans[i][j]=min(ans[i][j],ans[i][j-1]+1,ans[i-1][j]+1)
for i in range(n,0,-1):
for j in range(m,0,-1):
if mat[i][j] == 1 or mat[i][j] == 1000000000:
continue
else:
ans[i][j]=min(ans[i][j],ans[i+1][j]+1,ans[i][j+1]+1)
for i in range(1,n+1):
for j in range(m, 0, -1):
if mat[i][j] == 1 or mat[i][j] == 1000000000:
continue
else:
ans[i][j] = min(ans[i][j], ans[i - 1][j] + 1, ans[i][j + 1] + 1)
for i in range(n, 0, -1):
for j in range(1,m+1):
if mat[i][j] == 1 or mat[i][j] == 1000000000:
continue
else:
ans[i][j] = min(ans[i][j], ans[i + 1][j] + 1, ans[i][j - 1] + 1)
for i in range(1,n+1):
for j in range(1,m+1):
if mat[i][j]==1000000000:
print('X',end=" ")
elif ans[i][j]>=1000000000:
print('-1',end=" ")
else:
print(ans[i][j],end=" ")
print() | t=int(input())
for _ in range(t):
n,m=[int(x) for x in input().split()]
mat=[]
ans=[]
for i in range(n+2):
l=[]
p=[]
for j in range(m+2):
l.append(0)
p.append(1000000000)
mat.append(l)
ans.append(p)
y=int(input())
for i in range(y):
a,b=[int(x) for x in input().split()]
mat[a][b]=1
ans[a][b]=0
y=int(input())
for i in range(y):
a,b=[int(x) for x in input().split()]
mat[a][b]=1000000000
ans[a][b]=1000000000
for i in range(1,n+1):
for j in range(1,m+1):
if mat[i][j]==1 or mat[i][j]==1000000000:
continue
else:
ans[i][j]=min(ans[i][j],ans[i][j-1]+1,ans[i-1][j]+1)
for i in range(n,0,-1):
for j in range(m,0,-1):
if mat[i][j] == 1 or mat[i][j] == 1000000000:
continue
else:
ans[i][j]=min(ans[i][j],ans[i+1][j]+1,ans[i][j+1]+1)
for i in range(1,n+1):
for j in range(m, 0, -1):
if mat[i][j] == 1 or mat[i][j] == 1000000000:
continue
else:
ans[i][j] = min(ans[i][j], ans[i - 1][j] + 1, ans[i][j + 1] + 1)
for i in range(n, 0, -1):
for j in range(1,m+1):
if mat[i][j] == 1 or mat[i][j] == 1000000000:
continue
else:
ans[i][j] = min(ans[i][j], ans[i + 1][j] + 1, ans[i][j - 1] + 1)
for i in range(1,n+1):
for j in range(1,m+1):
if mat[i][j]==1 or mat[i][j]==1000000000:
continue
else:
ans[i][j]=min(ans[i][j],ans[i][j-1]+1,ans[i-1][j]+1)
for i in range(n,0,-1):
for j in range(m,0,-1):
if mat[i][j] == 1 or mat[i][j] == 1000000000:
continue
else:
ans[i][j]=min(ans[i][j],ans[i+1][j]+1,ans[i][j+1]+1)
for i in range(1,n+1):
for j in range(m, 0, -1):
if mat[i][j] == 1 or mat[i][j] == 1000000000:
continue
else:
ans[i][j] = min(ans[i][j], ans[i - 1][j] + 1, ans[i][j + 1] + 1)
for i in range(n, 0, -1):
for j in range(1,m+1):
if mat[i][j] == 1 or mat[i][j] == 1000000000:
continue
else:
ans[i][j] = min(ans[i][j], ans[i + 1][j] + 1, ans[i][j - 1] + 1)
for i in range(1,n+1):
for j in range(1,m+1):
if mat[i][j]==1000000000:
print('X',end=" ")
elif ans[i][j]>=1000000000:
print('-1',end=" ")
else:
print(ans[i][j],end=" ")
print() | train | APPS_structured |
Some new cashiers started to work at your restaurant.
They are good at taking orders, but they don't know how to capitalize words, or use a space bar!
All the orders they create look something like this:
`"milkshakepizzachickenfriescokeburgerpizzasandwichmilkshakepizza"`
The kitchen staff are threatening to quit, because of how difficult it is to read the orders.
Their preference is to get the orders as a nice clean string with spaces and capitals like so:
`"Burger Fries Chicken Pizza Pizza Pizza Sandwich Milkshake Milkshake Coke"`
The kitchen staff expect the items to be in the same order as they appear in the menu.
The menu items are fairly simple, there is no overlap in the names of the items:
```
1. Burger
2. Fries
3. Chicken
4. Pizza
5. Sandwich
6. Onionrings
7. Milkshake
8. Coke
``` | import re
MENU = {v:i for i,v in enumerate("Burger Fries Chicken Pizza Sandwich Onionrings Milkshake Coke".split())}
REG_CMD = re.compile('|'.join(MENU), flags=re.I)
def get_order(order):
return ' '.join(sorted( map(str.title, REG_CMD.findall(order)),
key=MENU.get )) | import re
MENU = {v:i for i,v in enumerate("Burger Fries Chicken Pizza Sandwich Onionrings Milkshake Coke".split())}
REG_CMD = re.compile('|'.join(MENU), flags=re.I)
def get_order(order):
return ' '.join(sorted( map(str.title, REG_CMD.findall(order)),
key=MENU.get )) | train | APPS_structured |
HELP! Jason can't find his textbook! It is two days before the test date, and Jason's textbooks are all out of order! Help him sort a list (ArrayList in java) full of textbooks by subject, so he can study before the test.
The sorting should **NOT** be case sensitive | def sorter(*textbooks):
for textbook in textbooks:
print(textbook.sort(key=str.lower))
return textbook | def sorter(*textbooks):
for textbook in textbooks:
print(textbook.sort(key=str.lower))
return textbook | train | APPS_structured |
**DESCRIPTION:**
Your strict math teacher is teaching you about right triangles, and the Pythagorean Theorem --> a^2 + b^2 = c^2 whereas a and b are the legs of the right triangle and c is the hypotenuse of the right triangle. On the test however, the question asks: What are the possible integer lengths for the other side of the triangle, but since you never learned anything about that in class, you realize she meant What are the possible integer lengths for the other side of the right triangle. Because you want to address the fact that she asked the wrong question and the fact that you're smart at math, you've decided to answer all the possible values for the third side EXCLUDING the possibilities for a right triangle in increasing order.
**EXAMPLES:**
```
side_len(1, 1) --> [1]
side_len(3, 4) --> [2, 3, 4, 6]
side_len(4, 6) --> [3, 4, 5, 6, 7, 8, 9]
```
**RETURN:**
Return your answer as a list of all the possible third side lengths of the triangle without the right triangles in increasing order.
By the way, after finishing this kata, please try some of my other katas: [Here](https://www.codewars.com/collections/tonylicodings-authored-katas)
NOTE:
When given side_len(x, y), y will always be greater than or equal to x. Also, if a right triangle's legs are passed in, exclude the hypotenuse. If a right triangle's leg and hypotenuse are passed in, exclude the other leg. | def side_len(x, y):
return [a for a in range(y - x + 1, x + y) if a * a + x * x != y * y and x * x + y * y != a * a] | def side_len(x, y):
return [a for a in range(y - x + 1, x + y) if a * a + x * x != y * y and x * x + y * y != a * a] | train | APPS_structured |
Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining.
The above elevation map is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped. Thanks Marcos for contributing this image!
Example:
Input: [0,1,0,2,1,0,1,3,2,1,2,1]
Output: 6 | class Solution:
def trap(self, barHeights):
if barHeights == []:
return 0
numberOfBars = len(barHeights)
leftMaxima = [0 for counter in range(numberOfBars)]
rightMaxima = [0 for counter in range(numberOfBars)]
leftMaxima[0] = barHeights[0]
for counter in range(1, numberOfBars):
leftMaxima[counter] = max(leftMaxima[counter-1], barHeights[counter])
rightMaxima[numberOfBars-1] = barHeights[numberOfBars-1]
for counter in range(numberOfBars-2, -1, -1):
rightMaxima[counter] = max(rightMaxima[counter+1], barHeights[counter])
waterTrapped = 0
for counter in range(0, numberOfBars):
waterTrapped += (min(leftMaxima[counter], rightMaxima[counter]) - barHeights[counter])
return waterTrapped
| class Solution:
def trap(self, barHeights):
if barHeights == []:
return 0
numberOfBars = len(barHeights)
leftMaxima = [0 for counter in range(numberOfBars)]
rightMaxima = [0 for counter in range(numberOfBars)]
leftMaxima[0] = barHeights[0]
for counter in range(1, numberOfBars):
leftMaxima[counter] = max(leftMaxima[counter-1], barHeights[counter])
rightMaxima[numberOfBars-1] = barHeights[numberOfBars-1]
for counter in range(numberOfBars-2, -1, -1):
rightMaxima[counter] = max(rightMaxima[counter+1], barHeights[counter])
waterTrapped = 0
for counter in range(0, numberOfBars):
waterTrapped += (min(leftMaxima[counter], rightMaxima[counter]) - barHeights[counter])
return waterTrapped
| train | APPS_structured |
Lira is now very keen on compiler development. :)
She knows that one of the most important components of a compiler, is its parser.
A parser is, in simple terms, a software component that processes text, and checks it's semantic correctness, or, if you prefer, if the text is properly built.
As an example, in declaring and initializing an integer, in C/C++, you can't do something like:
int = x ;4
as the semantics of such statement is incorrect, as we all know that the datatype must precede an identifier and only afterwards should come the equal sign and the initialization value, so, the corrected statement should be:
int x = 4;
Today, Lira is concerned with an abstract instruction which is composed of the characters "<" and ">" , which she will use on the design of her language, L++ :D.
She is using it as an abstraction for generating XML code Tags in an easier fashion and she understood that, for an expression to be valid, a "<" symbol must always have a corresponding ">" character somewhere (not necessary immediately) after it. Moreover, each ">" symbol should correspond to exactly one "<" symbol.
So, for instance, the instructions:
<<>>
<>
<><>
are all valid. While:
>>
><><
are not.
Given some expressions which represent some instructions to be analyzed by Lira's compiler, you should tell the length of the longest prefix of each of these expressions that is valid, or 0 if there's no such a prefix.
-----Input-----
Input will consist of an integer T denoting the number of test cases to follow.
Then, T strings follow, each on a single line, representing a possible expression in L++.
-----Output-----
For each expression you should output the length of the longest prefix that is valid or 0 if there's no such a prefix.
-----Constraints-----
- 1 ≤ T ≤ 500
- 1 ≤ The length of a single expression ≤ 106
- The total size all the input expressions is no more than 5*106
-----Example-----
Input:
3
<<>>
><
<>>>
Output:
4
0
2 | tc=int(input())
for q in range(tc):
arr=input()
stack=[]
maxx=0
counter=0
for i in arr:
counter+=1
if(i=='<'):
stack.append(i)
elif(i=='>' and len(stack)):
stack.pop()
if(not stack):
maxx=counter
else:
break
print(maxx) | tc=int(input())
for q in range(tc):
arr=input()
stack=[]
maxx=0
counter=0
for i in arr:
counter+=1
if(i=='<'):
stack.append(i)
elif(i=='>' and len(stack)):
stack.pop()
if(not stack):
maxx=counter
else:
break
print(maxx) | train | APPS_structured |
This program tests the life of an
evaporator containing a gas.
We know the content of the evaporator (content in ml),
the percentage of foam or gas lost every day (evap_per_day)
and the threshold (threshold) in percentage beyond which
the evaporator is no longer useful.
All numbers are strictly positive.
The program reports the nth day (as an integer)
on which the evaporator will be out of use.
**Note** : Content is in fact not necessary in the body of the function "evaporator", you can use it or not use it, as you wish. Some people might prefer to reason with content, some other with percentages only. It's up to you but you must keep it as a parameter because the tests have it as an argument. | from math import *
def evaporator(content, evap_per_day, threshold):
return ceil(log(threshold/100, 1-evap_per_day/100)) | from math import *
def evaporator(content, evap_per_day, threshold):
return ceil(log(threshold/100, 1-evap_per_day/100)) | train | APPS_structured |
Complete the method which accepts an array of integers, and returns one of the following:
* `"yes, ascending"` - if the numbers in the array are sorted in an ascending order
* `"yes, descending"` - if the numbers in the array are sorted in a descending order
* `"no"` - otherwise
You can assume the array will always be valid, and there will always be one correct answer. | def is_sorted_and_how(arr):
arr_up = arr[0]
arr_down = arr[0]
check = 1
for x in range(len(arr)):
if arr[x] > arr_up:
arr_up = arr[x]
check += 1
if check == len(arr):
return 'yes, ascending'
check = 1
for x in range(len(arr)):
if arr[x] < arr_down:
arr_down = arr[x]
check += 1
if check == len(arr):
return 'yes, descending'
else:
return 'no'
| def is_sorted_and_how(arr):
arr_up = arr[0]
arr_down = arr[0]
check = 1
for x in range(len(arr)):
if arr[x] > arr_up:
arr_up = arr[x]
check += 1
if check == len(arr):
return 'yes, ascending'
check = 1
for x in range(len(arr)):
if arr[x] < arr_down:
arr_down = arr[x]
check += 1
if check == len(arr):
return 'yes, descending'
else:
return 'no'
| train | APPS_structured |
There's a tree and every one of its nodes has a cost associated with it. Some of these nodes are labelled special nodes. You are supposed to answer a few queries on this tree. In each query, a source and destination node (SNODE$SNODE$ and DNODE$DNODE$) is given along with a value W$W$. For a walk between SNODE$SNODE$ and DNODE$DNODE$ to be valid you have to choose a special node and call it the pivot P$P$. Now the path will be SNODE$SNODE$ ->P$ P$ -> DNODE$DNODE$. For any valid path, there is a path value (PV$PV$) attached to it. It is defined as follows:
Select a subset of nodes(can be empty) in the path from SNODE$SNODE$ to P$P$ (both inclusive) such that sum of their costs (CTOT1$CTOT_{1}$) doesn't exceed W$W$.
Select a subset of nodes(can be empty) in the path from P$P$ to DNODE$DNODE$ (both inclusive) such that sum of their costs (CTOT2$CTOT_{2}$) doesn't exceed W$W$.
Now define PV=CTOT1+CTOT2$PV = CTOT_{1} + CTOT_{2}$ such that the absolute difference x=|CTOT1−CTOT2|$x = |CTOT_{1} - CTOT_{2}|$ is as low as possible. If there are multiple pairs of subsets that give the same minimum absolute difference, the pair of subsets which maximize PV$PV$ should be chosen.
For each query, output the path value PV$PV$ minimizing x$x$ as defined above.
Note that the sum of costs of an empty subset is zero.
-----Input-----
- First line contains three integers N$N$ - number of vertices in the tree, NSP$NSP$ - number of special nodes in the tree and Q$Q$ - number of queries to answer.
- Second line contains N−1$N-1$ integers. If the i$i$th integer is Vi$V_i$ then there is an undirected edge between i+1$i + 1$ and Vi$V_i$ (i$i$ starts from 1$1$ and goes till N−1$N-1$).
- Third line contains N$N$ integers, the i$i$th integer represents cost of the i$i$th vertex.
- Fourth line contains NSP$NSP$ integers - these represent which nodes are the special nodes.
- Following Q$Q$ lines contains three integers each - SNODE$SNODE$, DNODE$DNODE$ and W$W$ for each query.
-----Output-----
For each query output a single line containing a single integer - the path value PV$PV$ between SNODE$SNODE$ and DNODE$DNODE$.
-----Constraints:-----
- 1≤$1 \leq $ Number of nodes ≤1000$ \leq 1000 $
- 0≤W≤1000$ 0 \leq W \leq 1000 $
- 1≤$ 1 \leq $ Number of special nodes ≤10$ \leq 10 $
- 0≤$ 0 \leq $ Cost of each node ≤1000$ \leq 1000 $
- 1≤$ 1 \leq $ Number of queries ≤1000$ \leq 1000 $
-----Sample Input-----
7 1 5
1 1 2 2 3 3
3 5 4 2 7 9 1
1
2 3 100
1 1 100
2 1 100
4 5 100
4 7 100
-----Sample Output:-----
6
6
6
20
16
-----Explanation:-----
Consider query 4$4$. The only path is 4−>2−>1−>2−>5$4->2->1->2->5$. The two sets defined for this path are {3,2,5${3,2,5}$} and {3,5,7${3,5,7}$}. Pick subsets {3,2,5${3,2,5}$} and {3,7${3,7}$} from each set which minimizes PV$PV$. Note that node 2$2$ can repeat as it is in different paths (both to and from the pivot). | # cook your dish here
# cook your dish here
import numpy as np
n, s, q = [int(j) for j in input().split()]
edges = [int(j)-1 for j in input().split()]
costs = [int(j) for j in input().split()]
special = [int(j)-1 for j in input().split()]
queries = [[0] * 3 for _ in range(q)]
for i in range(q):
queries[i] = [int(j)-1 for j in input().split()]
edge_set = [[] for _ in range(n)]
for i in range(n-1):
edge_set[i+1].append(edges[i])
edge_set[edges[i]].append(i+1)
stored = np.zeros((s,n,1001),dtype=bool)
visited = [[] for _ in range(s)]
for i in range(s):
s_vertex = special[i]
s_cost = costs[s_vertex]
s_visited = visited[i]
s_visited.append(s_vertex)
s_stored = stored[i]
s_stored[s_vertex][0] = True
s_stored[s_vertex][s_cost] = True
for edge in edge_set[s_vertex]:
s_visited.append(edge)
s_stored[edge] = np.array(s_stored[s_vertex])
for j in range(1,n):
vertex = s_visited[j]
cost = costs[vertex]
s_stored[vertex][cost:1001] = np.logical_or(s_stored[vertex][0:1001-cost],s_stored[vertex][cost:1001])
for edge in edge_set[vertex]:
if edge not in s_visited:
s_visited.append(edge)
s_stored[edge] = np.array(s_stored[vertex])
for i in range(q):
first, second, max_cost = queries[i]
bool_array = np.zeros(max_cost+2,dtype=bool)
for j in range(s):
bool_array = np.logical_or(bool_array,np.logical_and(stored[j][first][:max_cost+2],stored[j][second][:max_cost+2]))
for j in range(max_cost+1,-1,-1):
if bool_array[j]:
print(2 * j)
break | # cook your dish here
# cook your dish here
import numpy as np
n, s, q = [int(j) for j in input().split()]
edges = [int(j)-1 for j in input().split()]
costs = [int(j) for j in input().split()]
special = [int(j)-1 for j in input().split()]
queries = [[0] * 3 for _ in range(q)]
for i in range(q):
queries[i] = [int(j)-1 for j in input().split()]
edge_set = [[] for _ in range(n)]
for i in range(n-1):
edge_set[i+1].append(edges[i])
edge_set[edges[i]].append(i+1)
stored = np.zeros((s,n,1001),dtype=bool)
visited = [[] for _ in range(s)]
for i in range(s):
s_vertex = special[i]
s_cost = costs[s_vertex]
s_visited = visited[i]
s_visited.append(s_vertex)
s_stored = stored[i]
s_stored[s_vertex][0] = True
s_stored[s_vertex][s_cost] = True
for edge in edge_set[s_vertex]:
s_visited.append(edge)
s_stored[edge] = np.array(s_stored[s_vertex])
for j in range(1,n):
vertex = s_visited[j]
cost = costs[vertex]
s_stored[vertex][cost:1001] = np.logical_or(s_stored[vertex][0:1001-cost],s_stored[vertex][cost:1001])
for edge in edge_set[vertex]:
if edge not in s_visited:
s_visited.append(edge)
s_stored[edge] = np.array(s_stored[vertex])
for i in range(q):
first, second, max_cost = queries[i]
bool_array = np.zeros(max_cost+2,dtype=bool)
for j in range(s):
bool_array = np.logical_or(bool_array,np.logical_and(stored[j][first][:max_cost+2],stored[j][second][:max_cost+2]))
for j in range(max_cost+1,-1,-1):
if bool_array[j]:
print(2 * j)
break | train | APPS_structured |
It's the fourth quater of the Super Bowl and your team is down by 4 points. You're 10 yards away from the endzone, if your team doesn't score a touchdown in the next four plays you lose. On a previous play, you were injured and rushed to the hospital. Your hospital room has no internet, tv, or radio and you don't know the results of the game. You look at your phone and see that on your way to the hospital a text message came in from one of your teamates. It contains an array of the last 4 plays in chronological order. In each play element of the array you will receive the yardage of the play and the type of the play. Have your function let you know if you won or not.
# What you know:
* Gaining greater than 10 yds from where you started is a touchdown and you win.
* Yardage of each play will always be a positive number greater than 0.
* There are only four types of plays: "run", "pass", "sack", "turnover".
* Type of plays that will gain yardage are: "run", "pass".
* Type of plays that will lose yardage are: "sack".
* Type of plays that will automatically lose the game are: "turnover".
* When a game ending play occurs the remaining (plays) arrays will be empty.
* If you win return true, if you lose return false.
# Examples:
[[8, "pass"],[5, "sack"],[3, "sack"],[5, "run"]]
`false`
[[12, "pass"],[],[],[]])
`true`
[[2, "run"],[5, "pass"],[3, "sack"],[8, "pass"]]
`true`
[[5, "pass"],[6, "turnover"],[],[]]
`false`
Good Luck! | def did_we_win(plays):
plays = [p for p in plays if p]
return all(p != 'turnover' for y,p in plays) and sum(-y if p == 'sack' else y for y,p in plays) > 10 | def did_we_win(plays):
plays = [p for p in plays if p]
return all(p != 'turnover' for y,p in plays) and sum(-y if p == 'sack' else y for y,p in plays) > 10 | train | APPS_structured |
Tavak and Seyyed are good friends. Seyyed is very funny and he told Tavak to solve the following problem instead of longest-path.
You are given l and r. For all integers from l to r, inclusive, we wrote down all of their integer divisors except 1. Find the integer that we wrote down the maximum number of times.
Solve the problem to show that it's not a NP problem.
-----Input-----
The first line contains two integers l and r (2 ≤ l ≤ r ≤ 10^9).
-----Output-----
Print single integer, the integer that appears maximum number of times in the divisors.
If there are multiple answers, print any of them.
-----Examples-----
Input
19 29
Output
2
Input
3 6
Output
3
-----Note-----
Definition of a divisor: https://www.mathsisfun.com/definitions/divisor-of-an-integer-.html
The first example: from 19 to 29 these numbers are divisible by 2: {20, 22, 24, 26, 28}.
The second example: from 3 to 6 these numbers are divisible by 3: {3, 6}. | def __starting_point():
l, r = list(map(int, input().split()))
if l == r:
print(l)
else:
print(2)
__starting_point() | def __starting_point():
l, r = list(map(int, input().split()))
if l == r:
print(l)
else:
print(2)
__starting_point() | train | APPS_structured |
Your task is to return the number of visible dots on a die after it has been rolled(that means the total count of dots that would not be touching the table when rolled)
6, 8, 10, 12, 20 sided dice are the possible inputs for "numOfSides"
topNum is equal to the number that is on top, or the number that was rolled.
for this exercise, all opposite faces add up to be 1 more than the total amount of sides
Example: 6 sided die would have 6 opposite 1, 4 opposite 3, and so on.
for this exercise, the 10 sided die starts at 1 and ends on 10.
Note: topNum will never be greater than numOfSides | totalAmountVisible = lambda t,n: sum(range(1,n+1))-(n+1-t) | totalAmountVisible = lambda t,n: sum(range(1,n+1))-(n+1-t) | train | APPS_structured |
Levko loves array a_1, a_2, ... , a_{n}, consisting of integers, very much. That is why Levko is playing with array a, performing all sorts of operations with it. Each operation Levko performs is of one of two types:
Increase all elements from l_{i} to r_{i} by d_{i}. In other words, perform assignments a_{j} = a_{j} + d_{i} for all j that meet the inequation l_{i} ≤ j ≤ r_{i}. Find the maximum of elements from l_{i} to r_{i}. That is, calculate the value $m_{i} = \operatorname{max}_{j = l_{i}}^{r_{i}} a_{j}$.
Sadly, Levko has recently lost his array. Fortunately, Levko has records of all operations he has performed on array a. Help Levko, given the operation records, find at least one suitable array. The results of all operations for the given array must coincide with the record results. Levko clearly remembers that all numbers in his array didn't exceed 10^9 in their absolute value, so he asks you to find such an array.
-----Input-----
The first line contains two integers n and m (1 ≤ n, m ≤ 5000) — the size of the array and the number of operations in Levko's records, correspondingly.
Next m lines describe the operations, the i-th line describes the i-th operation. The first integer in the i-th line is integer t_{i} (1 ≤ t_{i} ≤ 2) that describes the operation type. If t_{i} = 1, then it is followed by three integers l_{i}, r_{i} and d_{i} (1 ≤ l_{i} ≤ r_{i} ≤ n, - 10^4 ≤ d_{i} ≤ 10^4) — the description of the operation of the first type. If t_{i} = 2, then it is followed by three integers l_{i}, r_{i} and m_{i} (1 ≤ l_{i} ≤ r_{i} ≤ n, - 5·10^7 ≤ m_{i} ≤ 5·10^7) — the description of the operation of the second type.
The operations are given in the order Levko performed them on his array.
-----Output-----
In the first line print "YES" (without the quotes), if the solution exists and "NO" (without the quotes) otherwise.
If the solution exists, then on the second line print n integers a_1, a_2, ... , a_{n} (|a_{i}| ≤ 10^9) — the recovered array.
-----Examples-----
Input
4 5
1 2 3 1
2 1 2 8
2 3 4 7
1 1 3 3
2 3 4 8
Output
YES
4 7 4 7
Input
4 5
1 2 3 1
2 1 2 8
2 3 4 7
1 1 3 3
2 3 4 13
Output
NO | n, m = map(int, input().split())
a = [10**9 for _ in range(n)]
extra = [0 for _ in range(n)]
query = list()
for _ in range(m):
t, l, r, x = map(int, input().split())
l -= 1
r -= 1
query.append((t, l, r, x))
if t == 1:
for j in range(l, r + 1):
extra[j] += x
else:
for j in range(l, r + 1):
a[j] = min(a[j], x - extra[j])
extra = a.copy()
for t, l, r, x in query:
if t == 1:
for j in range(l, r + 1):
a[j] += x
else:
val = -10**9
for j in range(l, r + 1):
val = max(val, a[j])
if not val == x:
print('NO')
return
print('YES')
for x in extra:
print(x, end=' ')
| n, m = map(int, input().split())
a = [10**9 for _ in range(n)]
extra = [0 for _ in range(n)]
query = list()
for _ in range(m):
t, l, r, x = map(int, input().split())
l -= 1
r -= 1
query.append((t, l, r, x))
if t == 1:
for j in range(l, r + 1):
extra[j] += x
else:
for j in range(l, r + 1):
a[j] = min(a[j], x - extra[j])
extra = a.copy()
for t, l, r, x in query:
if t == 1:
for j in range(l, r + 1):
a[j] += x
else:
val = -10**9
for j in range(l, r + 1):
val = max(val, a[j])
if not val == x:
print('NO')
return
print('YES')
for x in extra:
print(x, end=' ')
| train | APPS_structured |
# Introduction
A grille cipher was a technique for encrypting a plaintext by writing it onto a sheet of paper through a pierced sheet (of paper or cardboard or similar). The earliest known description is due to the polymath Girolamo Cardano in 1550. His proposal was for a rectangular stencil allowing single letters, syllables, or words to be written, then later read, through its various apertures. The written fragments of the plaintext could be further disguised by filling the gaps between the fragments with anodyne words or letters. This variant is also an example of steganography, as are many of the grille ciphers.
Wikipedia Link
![Tangiers1](https://upload.wikimedia.org/wikipedia/commons/8/8a/Tangiers1.png)
![Tangiers2](https://upload.wikimedia.org/wikipedia/commons/b/b9/Tangiers2.png)
# Task
Write a function that accepts two inputs: `message` and `code` and returns hidden message decrypted from `message` using the `code`.
The `code` is a nonnegative integer and it decrypts in binary the `message`. | from itertools import compress
def grille(message, code):
l = len(message)
code = list(map(int, bin(code)[2:].zfill(l)))
return ''.join(list(compress(message, [code, code[l:]][l <len(code)] )))
| from itertools import compress
def grille(message, code):
l = len(message)
code = list(map(int, bin(code)[2:].zfill(l)))
return ''.join(list(compress(message, [code, code[l:]][l <len(code)] )))
| train | APPS_structured |
Greg has an array a = a_1, a_2, ..., a_{n} and m operations. Each operation looks as: l_{i}, r_{i}, d_{i}, (1 ≤ l_{i} ≤ r_{i} ≤ n). To apply operation i to the array means to increase all array elements with numbers l_{i}, l_{i} + 1, ..., r_{i} by value d_{i}.
Greg wrote down k queries on a piece of paper. Each query has the following form: x_{i}, y_{i}, (1 ≤ x_{i} ≤ y_{i} ≤ m). That means that one should apply operations with numbers x_{i}, x_{i} + 1, ..., y_{i} to the array.
Now Greg is wondering, what the array a will be after all the queries are executed. Help Greg.
-----Input-----
The first line contains integers n, m, k (1 ≤ n, m, k ≤ 10^5). The second line contains n integers: a_1, a_2, ..., a_{n} (0 ≤ a_{i} ≤ 10^5) — the initial array.
Next m lines contain operations, the operation number i is written as three integers: l_{i}, r_{i}, d_{i}, (1 ≤ l_{i} ≤ r_{i} ≤ n), (0 ≤ d_{i} ≤ 10^5).
Next k lines contain the queries, the query number i is written as two integers: x_{i}, y_{i}, (1 ≤ x_{i} ≤ y_{i} ≤ m).
The numbers in the lines are separated by single spaces.
-----Output-----
On a single line print n integers a_1, a_2, ..., a_{n} — the array after executing all the queries. Separate the printed numbers by spaces.
Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams of the %I64d specifier.
-----Examples-----
Input
3 3 3
1 2 3
1 2 1
1 3 2
2 3 4
1 2
1 3
2 3
Output
9 18 17
Input
1 1 1
1
1 1 1
1 1
Output
2
Input
4 3 6
1 2 3 4
1 2 1
2 3 2
3 4 4
1 2
1 3
2 3
1 2
1 3
2 3
Output
5 18 31 20 | from sys import stdin, stdout
rd = lambda: list(map(int, stdin.readline().split()))
n, m, k = rd()
a = rd()
b = [rd() for _ in range(m)]
x = [0]*(m+1)
y = [0]*(n+1)
for _ in range(k):
l, r = rd()
x[l-1] += 1
x[r ] -= 1
s = 0
for i in range(m):
l, r, d = b[i]
s += x[i]
y[l-1] += s*d
y[r ] -= s*d
s = 0
for i in range(n):
s += y[i]
a[i] += s
print(' '.join(map(str, a))) | from sys import stdin, stdout
rd = lambda: list(map(int, stdin.readline().split()))
n, m, k = rd()
a = rd()
b = [rd() for _ in range(m)]
x = [0]*(m+1)
y = [0]*(n+1)
for _ in range(k):
l, r = rd()
x[l-1] += 1
x[r ] -= 1
s = 0
for i in range(m):
l, r, d = b[i]
s += x[i]
y[l-1] += s*d
y[r ] -= s*d
s = 0
for i in range(n):
s += y[i]
a[i] += s
print(' '.join(map(str, a))) | train | APPS_structured |
There is a tree with N vertices numbered 1 to N.
The i-th edge in this tree connects Vertex a_i and Vertex b_i, and the color and length of that edge are c_i and d_i, respectively.
Here the color of each edge is represented by an integer between 1 and N-1 (inclusive). The same integer corresponds to the same color, and different integers correspond to different colors.
Answer the following Q queries:
- Query j (1 \leq j \leq Q): assuming that the length of every edge whose color is x_j is changed to y_j, find the distance between Vertex u_j and Vertex v_j. (The changes of the lengths of edges do not affect the subsequent queries.)
-----Constraints-----
- 2 \leq N \leq 10^5
- 1 \leq Q \leq 10^5
- 1 \leq a_i, b_i \leq N
- 1 \leq c_i \leq N-1
- 1 \leq d_i \leq 10^4
- 1 \leq x_j \leq N-1
- 1 \leq y_j \leq 10^4
- 1 \leq u_j < v_j \leq N
- The given graph is a tree.
- All values in input are integers.
-----Input-----
Input is given from Standard Input in the following format:
N Q
a_1 b_1 c_1 d_1
:
a_{N-1} b_{N-1} c_{N-1} d_{N-1}
x_1 y_1 u_1 v_1
:
x_Q y_Q u_Q v_Q
-----Output-----
Print Q lines. The j-th line (1 \leq j \leq Q) should contain the answer to Query j.
-----Sample Input-----
5 3
1 2 1 10
1 3 2 20
2 4 4 30
5 2 1 40
1 100 1 4
1 100 1 5
3 1000 3 4
-----Sample Output-----
130
200
60
The graph in this input is as follows:
Here the edges of Color 1 are shown as solid red lines, the edge of Color 2 is shown as a bold green line, and the edge of Color 4 is shown as a blue dashed line.
- Query 1: Assuming that the length of every edge whose color is 1 is changed to 100, the distance between Vertex 1 and Vertex 4 is 100 + 30 = 130.
- Query 2: Assuming that the length of every edge whose color is 1 is changed to 100, the distance between Vertex 1 and Vertex 5 is 100 + 100 = 200.
- Query 3: Assuming that the length of every edge whose color is 3 is changed to 1000 (there is no such edge), the distance between Vertex 3 and Vertex 4 is 20 + 10 + 30 = 60. Note that the edges of Color 1 now have their original lengths. | import sys
input = sys.stdin.readline
sys.setrecursionlimit(10**5)
N, Q = map(int, input().split())
path = [[] for _ in range(N)]
for _ in range(N-1) :
a, b, c, d = (int(i) for i in input().split())
path[a-1].append((b-1, c-1, d))
path[b-1].append((a-1, c-1, d))
# doublingに必要なKを求める
for K in range(18) :
if 2 ** K >= N :
break
# dfs
parent = [[-1] * N for _ in range(K)]
rank = [-1 for _ in range(N)]
rank[0] = 0
queue = [0]
while queue :
cur = queue.pop()
for nex, _, _ in path[cur] :
if rank[nex] < 0 :
queue.append(nex)
parent[0][nex] = cur
rank[nex] = rank[cur] + 1
# doubling
for i in range(1, K) :
for j in range(N) :
if parent[i-1][j] > 0 :
parent[i][j] = parent[i-1][parent[i-1][j]]
# lca
def lca(a, b) :
if rank[a] > rank[b] :
a, b = b, a
diff = rank[b] - rank[a]
i = 0
while diff > 0 :
if diff & 1 :
b = parent[i][b]
diff >>= 1
i += 1
if a == b :
return a
for i in range(K-1, -1, -1) :
if parent[i][a] != parent[i][b] :
a = parent[i][a]
b = parent[i][b]
return parent[0][a]
# Queryの先読み
schedule = [[] for _ in range(N)]
for i in range(Q) :
x, y, u, v = map(int, input().split())
x, u, v = x-1, u-1, v-1
l = lca(u, v)
schedule[u].append((i, 1, x, y))
schedule[v].append((i, 1, x, y))
schedule[l].append((i, -2, x, y))
ret = [0] * Q
C = [0] * (N-1)
D = [0] * (N-1)
def dfs(cur, pre, tot) :
for i, t, c, d in schedule[cur] :
ret[i] += t * (tot - D[c] + C[c] * d)
for nex, c, d in path[cur] :
if nex == pre :
continue
C[c] += 1
D[c] += d
dfs(nex, cur, tot + d)
C[c] -= 1
D[c] -= d
dfs(0, -1, 0)
for i in range(Q) :
print(ret[i]) | import sys
input = sys.stdin.readline
sys.setrecursionlimit(10**5)
N, Q = map(int, input().split())
path = [[] for _ in range(N)]
for _ in range(N-1) :
a, b, c, d = (int(i) for i in input().split())
path[a-1].append((b-1, c-1, d))
path[b-1].append((a-1, c-1, d))
# doublingに必要なKを求める
for K in range(18) :
if 2 ** K >= N :
break
# dfs
parent = [[-1] * N for _ in range(K)]
rank = [-1 for _ in range(N)]
rank[0] = 0
queue = [0]
while queue :
cur = queue.pop()
for nex, _, _ in path[cur] :
if rank[nex] < 0 :
queue.append(nex)
parent[0][nex] = cur
rank[nex] = rank[cur] + 1
# doubling
for i in range(1, K) :
for j in range(N) :
if parent[i-1][j] > 0 :
parent[i][j] = parent[i-1][parent[i-1][j]]
# lca
def lca(a, b) :
if rank[a] > rank[b] :
a, b = b, a
diff = rank[b] - rank[a]
i = 0
while diff > 0 :
if diff & 1 :
b = parent[i][b]
diff >>= 1
i += 1
if a == b :
return a
for i in range(K-1, -1, -1) :
if parent[i][a] != parent[i][b] :
a = parent[i][a]
b = parent[i][b]
return parent[0][a]
# Queryの先読み
schedule = [[] for _ in range(N)]
for i in range(Q) :
x, y, u, v = map(int, input().split())
x, u, v = x-1, u-1, v-1
l = lca(u, v)
schedule[u].append((i, 1, x, y))
schedule[v].append((i, 1, x, y))
schedule[l].append((i, -2, x, y))
ret = [0] * Q
C = [0] * (N-1)
D = [0] * (N-1)
def dfs(cur, pre, tot) :
for i, t, c, d in schedule[cur] :
ret[i] += t * (tot - D[c] + C[c] * d)
for nex, c, d in path[cur] :
if nex == pre :
continue
C[c] += 1
D[c] += d
dfs(nex, cur, tot + d)
C[c] -= 1
D[c] -= d
dfs(0, -1, 0)
for i in range(Q) :
print(ret[i]) | train | APPS_structured |
Let's assume we need "clean" strings. Clean means a string should only contain letters `a-z`, `A-Z` and spaces. We assume that there are no double spaces or line breaks.
Write a function that takes a string and returns a string without the unnecessary characters.
### Examples
```python
remove_chars('.tree1') ==> 'tree'
remove_chars("that's a pie$ce o_f p#ie!") ==> 'thats a piece of pie'
remove_chars('john.dope@dopington.com') ==> 'johndopedopingtoncom'
remove_chars('my_list = ["a","b","c"]') ==> 'mylist abc'
remove_chars('1 + 1 = 2') ==> ' ' (string with 4 spaces)
remove_chars("0123456789(.)+,|[]{}=@/~;^$'<>?-!*&:#%_") ==> '' (empty string)
``` | def remove_chars(s):
letters = "abcdefghijklmnopqrstuvwxyz "
return "".join([i for i in s if i in letters or i in letters.upper()]) | def remove_chars(s):
letters = "abcdefghijklmnopqrstuvwxyz "
return "".join([i for i in s if i in letters or i in letters.upper()]) | train | APPS_structured |
All strings in Chefland are beautiful because they are binary strings (a binary string contains only characters '0' and '1'). The beauty of a binary string $S$ is defined as the number of pairs $(i, j)$ ($1 \le i \le j \le |S|$) such that the substring $S_i, S_{i+1}, \ldots, S_j$ is special.
For a binary string $U$, let's denote the number of occurrences of the characters '1' and '0' in $U$ by $cnt_1$ and $cnt_0$ respectively; then, $U$ is special if $cnt_0 = cnt_1 \cdot cnt_1$.
Today, Chef's friend Araspa is celebrating her birthday. Chef wants to give Araspa the most beautiful binary string he can find. Currently, he is checking out binary strings in a shop, but he needs your help to calculate their beauties. Tell Chef the beauty of each binary string he gives you.
-----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 beauty of the string $S$.
-----Constraints-----
- $1 \le T \le 10$
- $1 \le |S| \le 10^5$
- each character of $S$ is '0' or '1'
-----Example Input-----
2
010001
10
-----Example Output-----
4
1
-----Explanation-----
Example case 1: The special substrings correspond to $(i, j) = (1, 2), (1, 6), (2, 3), (5, 6)$. | cnt1_max = 315
arr_size = [None]*cnt1_max
for i in range(1, cnt1_max+1):
arr_size[i-1] = (i*(i+1), i)
#print(arr_size)
t = int(input())
for _t in range(t):
s = input().strip()
n = len(s)
tot1 = [0]*(n+1)
for i in range(1, n+1):
if s[i-1] == '1':
tot1[i] = tot1[i-1] + 1
else:
tot1[i] = tot1[i-1]
#print(tot1)
beauty = 0
for size, cnt in arr_size:
i = 0
limit = n - size
while i < limit+1:
cnt1 = tot1[i+size] - tot1[i]
#print(i,i+size,cnt1,cnt)
if cnt1 == cnt:
beauty += 1
i+=1
else:
i += abs(cnt1-cnt)
print(beauty) | cnt1_max = 315
arr_size = [None]*cnt1_max
for i in range(1, cnt1_max+1):
arr_size[i-1] = (i*(i+1), i)
#print(arr_size)
t = int(input())
for _t in range(t):
s = input().strip()
n = len(s)
tot1 = [0]*(n+1)
for i in range(1, n+1):
if s[i-1] == '1':
tot1[i] = tot1[i-1] + 1
else:
tot1[i] = tot1[i-1]
#print(tot1)
beauty = 0
for size, cnt in arr_size:
i = 0
limit = n - size
while i < limit+1:
cnt1 = tot1[i+size] - tot1[i]
#print(i,i+size,cnt1,cnt)
if cnt1 == cnt:
beauty += 1
i+=1
else:
i += abs(cnt1-cnt)
print(beauty) | train | APPS_structured |
Little X has n distinct integers: p_1, p_2, ..., p_{n}. He wants to divide all of them into two sets A and B. The following two conditions must be satisfied: If number x belongs to set A, then number a - x must also belong to set A. If number x belongs to set B, then number b - x must also belong to set B.
Help Little X divide the numbers into two sets or determine that it's impossible.
-----Input-----
The first line contains three space-separated integers n, a, b (1 ≤ n ≤ 10^5; 1 ≤ a, b ≤ 10^9). The next line contains n space-separated distinct integers p_1, p_2, ..., p_{n} (1 ≤ p_{i} ≤ 10^9).
-----Output-----
If there is a way to divide the numbers into two sets, then print "YES" in the first line. Then print n integers: b_1, b_2, ..., b_{n} (b_{i} equals either 0, or 1), describing the division. If b_{i} equals to 0, then p_{i} belongs to set A, otherwise it belongs to set B.
If it's impossible, print "NO" (without the quotes).
-----Examples-----
Input
4 5 9
2 3 4 5
Output
YES
0 0 1 1
Input
3 3 4
1 2 4
Output
NO
-----Note-----
It's OK if all the numbers are in the same set, and the other one is empty. | class DisjointSet:
def __init__(self, n):
self._fa = list(range(n))
def union(self, x, y):
x = self.get_father(x)
y = self.get_father(y)
self._fa[x] = y
return y
def get_father(self, x):
y = self._fa[x]
if self._fa[y] == y:
return y
else:
z = self._fa[y] = self.get_father(y)
return z
def __repr__(self):
return repr([self.get_father(i) for i in range(len(self._fa))])
def solve(n, a, b, xs):
h = {x: i for i, x in enumerate(xs)}
if a == b:
if all(a - x in h for x in xs):
return [0] * n
return False
g1 = n
g2 = n + 1
ds = DisjointSet(n + 2)
for i, x in enumerate(xs):
for t in (a, b):
if t - x in h:
ds.union(i, h[t - x])
for i, x in enumerate(xs):
b1 = (a - x) in h
b2 = (b - x) in h
if b1 + b2 == 0:
return False
if b1 + b2 == 1:
if b1:
ds.union(i, g1)
else:
ds.union(i, g2)
if ds.get_father(g1) == ds.get_father(g2):
return False
group = [None] * n
for i, x in enumerate(xs):
f = ds.get_father(i)
if f < n:
return False
group[i] = f - n
return group
n, a, b = list(map(int, input().split()))
xs = list(map(int, input().split()))
group = solve(n, a, b, xs)
if isinstance(group, list):
print('YES')
print(' '.join(map(str, group)))
else:
print('NO')
| class DisjointSet:
def __init__(self, n):
self._fa = list(range(n))
def union(self, x, y):
x = self.get_father(x)
y = self.get_father(y)
self._fa[x] = y
return y
def get_father(self, x):
y = self._fa[x]
if self._fa[y] == y:
return y
else:
z = self._fa[y] = self.get_father(y)
return z
def __repr__(self):
return repr([self.get_father(i) for i in range(len(self._fa))])
def solve(n, a, b, xs):
h = {x: i for i, x in enumerate(xs)}
if a == b:
if all(a - x in h for x in xs):
return [0] * n
return False
g1 = n
g2 = n + 1
ds = DisjointSet(n + 2)
for i, x in enumerate(xs):
for t in (a, b):
if t - x in h:
ds.union(i, h[t - x])
for i, x in enumerate(xs):
b1 = (a - x) in h
b2 = (b - x) in h
if b1 + b2 == 0:
return False
if b1 + b2 == 1:
if b1:
ds.union(i, g1)
else:
ds.union(i, g2)
if ds.get_father(g1) == ds.get_father(g2):
return False
group = [None] * n
for i, x in enumerate(xs):
f = ds.get_father(i)
if f < n:
return False
group[i] = f - n
return group
n, a, b = list(map(int, input().split()))
xs = list(map(int, input().split()))
group = solve(n, a, b, xs)
if isinstance(group, list):
print('YES')
print(' '.join(map(str, group)))
else:
print('NO')
| train | APPS_structured |
Your job is to return the volume of a cup when given the diameter of the top, the diameter of the bottom and the height.
You know that there is a steady gradient from the top to the bottom.
You want to return the volume rounded to 2 decimal places.
Exmples:
```python
cup_volume(1, 1, 1)==0.79
cup_volume(10, 8, 10)==638.79
cup_volume(1000, 1000, 1000)==785398163.4
cup_volume(13.123, 123.12, 1)==4436.57
cup_volume(5, 12, 31)==1858.51
```
You will only be passed positive numbers. | import math
def cup_volume(d1, d2, height):
return round(math.pi * height * (d1**2 + d2**2 + d1*d2)/12, 2) | import math
def cup_volume(d1, d2, height):
return round(math.pi * height * (d1**2 + d2**2 + d1*d2)/12, 2) | train | APPS_structured |
We are given an array A of N lowercase letter strings, all of the same length.
Now, we may choose any set of deletion indices, and for each string, we delete all the characters in those indices.
For example, if we have an array A = ["babca","bbazb"] and deletion indices {0, 1, 4}, then the final array after deletions is ["bc","az"].
Suppose we chose a set of deletion indices D such that after deletions, the final array has every element (row) in lexicographic order.
For clarity, A[0] is in lexicographic order (ie. A[0][0] <= A[0][1] <= ... <= A[0][A[0].length - 1]), A[1] is in lexicographic order (ie. A[1][0] <= A[1][1] <= ... <= A[1][A[1].length - 1]), and so on.
Return the minimum possible value of D.length.
Example 1:
Input: ["babca","bbazb"]
Output: 3
Explanation: After deleting columns 0, 1, and 4, the final array is A = ["bc", "az"].
Both these rows are individually in lexicographic order (ie. A[0][0] <= A[0][1] and A[1][0] <= A[1][1]).
Note that A[0] > A[1] - the array A isn't necessarily in lexicographic order.
Example 2:
Input: ["edcba"]
Output: 4
Explanation: If we delete less than 4 columns, the only row won't be lexicographically sorted.
Example 3:
Input: ["ghi","def","abc"]
Output: 0
Explanation: All rows are already lexicographically sorted.
Note:
1 <= A.length <= 100
1 <= A[i].length <= 100 | class Solution:
def minDeletionSize(self, A: List[str]) -> int:
n = len(A[0])
dp = [1]*n
for i in range(1, n):
for j in range(i):
if all(s[j] <= s[i] for s in A):
dp[i] = max(dp[i], dp[j] + 1)
return n - max(dp)
| class Solution:
def minDeletionSize(self, A: List[str]) -> int:
n = len(A[0])
dp = [1]*n
for i in range(1, n):
for j in range(i):
if all(s[j] <= s[i] for s in A):
dp[i] = max(dp[i], dp[j] + 1)
return n - max(dp)
| train | APPS_structured |
In Byteland there are N cities, numbered 1 through N. Some pairs of cities are connected by bi-directional roads in such a way that starting from any one city you can visit all other cities either directly or indirectly.
Chef is currently at city A and wants to visit all other cities in Byteland. Chef can only move according to following rule.
If Chef is at city A then he continues to move from city A to city B, city B to city C (provided A is directly connected to B, B is directly connected to C) and so on unless there are no more cities leading from current city.
If so he jumps back to previous city and repeat the same tour with other cities leading from it which are not visited. Chef repeat this step unless all cities are not visited.
Help Chef to count number of ways in which he can visit all other cities . As this number can be large print it modulo 109+7
-----Input-----
- The first line of the input contains an integer T denoting the number of test cases. The description of T test cases follows.
- The first line of each test case contains a single integer N denoting the number of cities in Byteland.
- Next N-1 lines contain two space-separated integers u and v denoting there is bi-directional road between city numbered u and v.
- Next line contains a single integer A denoting the city number where Chef is present.
-----Output-----
- For each test case, output a single line containing number of ways in which Chef can visit all cities modulo 109+7.
-----Constraints-----
- 1 ≤ T ≤ 5
- 1 ≤ N ≤ 105
- 1 ≤ A ≤ N
-----Subtasks-----
Subtask #1 : (10 points)
- 1 ≤ N ≤ 5
Subtask #2 : (30 points)
- 1 ≤ N ≤ 100
Subtask #3 : (60 points)
- 1 ≤ N ≤ 105
-----Example-----
Input:
2
3
1 2
1 3
1
5
1 2
1 3
2 4
2 5
1
Output:
2
4
-----Explanation-----
Example case 1. Chef can visit cities in two ways according to the problem: 1-2-3 and 1-3-2
Example case 1. Chef can visit cities in four ways according to the problem:
1-2-4-5-3
1-2-5-4-3
1-3-2-4-5
1-3-2-5-4 | import sys
sys.setrecursionlimit(10**8)
MOD = 10**9+7
fac = [0]*(10**5+1)
def pre() :
fac[0] = 1
for i in range(1,10**5+1) :
fac[i] = fac[i-1]*i
fac[i] = fac[i]%MOD
def dfs(gp , vertex , visited , deg , ans) :
visited[vertex] = 1
stack = []
stack.append(vertex)
while len(stack)>0 :
vertex = stack.pop()
ans = ans%MOD * fac[deg[vertex]]%MOD
ans %= MOD
for i in gp[vertex] :
if not visited[i] :
visited[i] = 1
if vertex in gp[i] :
deg[i] -= 1
stack.append(i)
return ans%MOD
pre()
for __ in range(eval(input())) :
n = eval(input())
deg = [0]*(n+1)
st = [[] for __ in range(n+1)]
for _ in range(n-1) :
a , b = list(map(int,sys.stdin.readline().split()))
st[a].append(b)
st[b].append(a)
deg[a] += 1
deg[b] += 1
k = eval(input())
visited = [0]*(n+1)
print(dfs(st ,k,visited,deg , 1)%MOD)
| import sys
sys.setrecursionlimit(10**8)
MOD = 10**9+7
fac = [0]*(10**5+1)
def pre() :
fac[0] = 1
for i in range(1,10**5+1) :
fac[i] = fac[i-1]*i
fac[i] = fac[i]%MOD
def dfs(gp , vertex , visited , deg , ans) :
visited[vertex] = 1
stack = []
stack.append(vertex)
while len(stack)>0 :
vertex = stack.pop()
ans = ans%MOD * fac[deg[vertex]]%MOD
ans %= MOD
for i in gp[vertex] :
if not visited[i] :
visited[i] = 1
if vertex in gp[i] :
deg[i] -= 1
stack.append(i)
return ans%MOD
pre()
for __ in range(eval(input())) :
n = eval(input())
deg = [0]*(n+1)
st = [[] for __ in range(n+1)]
for _ in range(n-1) :
a , b = list(map(int,sys.stdin.readline().split()))
st[a].append(b)
st[b].append(a)
deg[a] += 1
deg[b] += 1
k = eval(input())
visited = [0]*(n+1)
print(dfs(st ,k,visited,deg , 1)%MOD)
| train | APPS_structured |
Find the largest palindrome made from the product of two n-digit numbers.
Since the result could be very large, you should return the largest palindrome mod 1337.
Example:
Input: 2
Output: 987
Explanation: 99 x 91 = 9009, 9009 % 1337 = 987
Note:
The range of n is [1,8]. | class Solution:
def largestPalindrome(self, n):
"""
:type n: int
:rtype: int
"""
return [9, 9009, 906609, 99000099, 9966006699, 999000000999, \
99956644665999, 9999000000009999][n - 1] % 1337 | class Solution:
def largestPalindrome(self, n):
"""
:type n: int
:rtype: int
"""
return [9, 9009, 906609, 99000099, 9966006699, 999000000999, \
99956644665999, 9999000000009999][n - 1] % 1337 | train | APPS_structured |
=====Problem Statement=====
Mr. Anant Asankhya is the manager at the INFINITE hotel. The hotel has an infinite amount of rooms.
One fine day, a finite number of tourists come to stay at the hotel.
The tourists consist of:
→ A Captain.
→ An unknown group of families consisting of K members per group where K ≠ 1.
The Captain was given a separate room, and the rest were given one room per group.
Mr. Anant has an unordered list of randomly arranged room entries. The list consists of the room numbers for all of the tourists. The room numbers will appear K times per group except for the Captain's room.
Mr. Anant needs you to help him find the Captain's room number.
The total number of tourists or the total number of groups of families is not known to you.
You only know the value of K and the room number list.
=====Input Format=====
The first consists of an integer, K, the size of each group.
The second line contains the unordered elements of the room number list.
=====Constraints=====
1<K<1000
=====Output Format=====
Output the Captain's room number. | #!/usr/bin/env python3
def __starting_point():
k = int(input().strip())
numbers = list(map(int, input().strip().split(' ')))
print((sum(set(numbers))*k - sum(numbers))//(k-1))
__starting_point() | #!/usr/bin/env python3
def __starting_point():
k = int(input().strip())
numbers = list(map(int, input().strip().split(' ')))
print((sum(set(numbers))*k - sum(numbers))//(k-1))
__starting_point() | train | APPS_structured |
Given the root of a binary tree, each node in the tree has a distinct value.
After deleting all nodes with a value in to_delete, we are left with a forest (a disjoint union of trees).
Return the roots of the trees in the remaining forest. You may return the result in any order.
Example 1:
Input: root = [1,2,3,4,5,6,7], to_delete = [3,5]
Output: [[1,2,null,4],[6],[7]]
Constraints:
The number of nodes in the given tree is at most 1000.
Each node has a distinct value between 1 and 1000.
to_delete.length <= 1000
to_delete contains distinct values between 1 and 1000. | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def delNodes(self, root: TreeNode, to_delete: List[int]) -> List[TreeNode]:
ret = []
def dfs(node, parent):
if node:
if node.val in to_delete:
node.left=dfs(node.left, False)
node.right=dfs(node.right, False)
else:
if not parent:
ret.append(node)
node.left=dfs(node.left, True)
node.right=dfs(node.right, True)
return node
dfs(root, False)
return ret | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def delNodes(self, root: TreeNode, to_delete: List[int]) -> List[TreeNode]:
ret = []
def dfs(node, parent):
if node:
if node.val in to_delete:
node.left=dfs(node.left, False)
node.right=dfs(node.right, False)
else:
if not parent:
ret.append(node)
node.left=dfs(node.left, True)
node.right=dfs(node.right, True)
return node
dfs(root, False)
return ret | train | APPS_structured |
Given a string s1, we may represent it as a binary tree by partitioning it to two non-empty substrings recursively.
Below is one possible representation of s1 = "great":
great
/ \
gr eat
/ \ / \
g r e at
/ \
a t
To scramble the string, we may choose any non-leaf node and swap its two children.
For example, if we choose the node "gr" and swap its two children, it produces a scrambled string "rgeat".
rgeat
/ \
rg eat
/ \ / \
r g e at
/ \
a t
We say that "rgeat" is a scrambled string of "great".
Similarly, if we continue to swap the children of nodes "eat" and "at", it produces a scrambled string "rgtae".
rgtae
/ \
rg tae
/ \ / \
r g ta e
/ \
t a
We say that "rgtae" is a scrambled string of "great".
Given two strings s1 and s2 of the same length, determine if s2 is a scrambled string of s1.
Example 1:
Input: s1 = "great", s2 = "rgeat"
Output: true
Example 2:
Input: s1 = "abcde", s2 = "caebd"
Output: false | class Solution:
def isScramble(self, A, B):
if len(A) != len(B) or sorted(A) != sorted(B):
return False
if len(A) == 1 or A == B:
return True
for i in range(1, len(A)):
if self.isScramble(A[:i], B[:i]) and self.isScramble(A[i:], B[i:]):
return True
elif self.isScramble(A[:i], B[-i:]) and self.isScramble(A[i:], B[:-i]):
return True
return False | class Solution:
def isScramble(self, A, B):
if len(A) != len(B) or sorted(A) != sorted(B):
return False
if len(A) == 1 or A == B:
return True
for i in range(1, len(A)):
if self.isScramble(A[:i], B[:i]) and self.isScramble(A[i:], B[i:]):
return True
elif self.isScramble(A[:i], B[-i:]) and self.isScramble(A[i:], B[:-i]):
return True
return False | train | APPS_structured |
In this kata you have to correctly return who is the "survivor", ie: the last element of a Josephus permutation.
Basically you have to assume that n people are put into a circle and that they are eliminated in steps of k elements, like this:
```
josephus_survivor(7,3) => means 7 people in a circle;
one every 3 is eliminated until one remains
[1,2,3,4,5,6,7] - initial sequence
[1,2,4,5,6,7] => 3 is counted out
[1,2,4,5,7] => 6 is counted out
[1,4,5,7] => 2 is counted out
[1,4,5] => 7 is counted out
[1,4] => 5 is counted out
[4] => 1 counted out, 4 is the last element - the survivor!
```
The above link about the "base" kata description will give you a more thorough insight about the origin of this kind of permutation, but basically that's all that there is to know to solve this kata.
**Notes and tips:** using the solution to the other kata to check your function may be helpful, but as much larger numbers will be used, using an array/list to compute the number of the survivor may be too slow; you may assume that both n and k will always be >=1. | import sys
# Set new (higher) recursion limit
sys.setrecursionlimit(int(1e6))
# Source: https://en.wikipedia.org/wiki/Josephus_problem#The_general_case
# (I couldn't come up with the formula myself :p)
josephus_survivor = lambda n, k: 1 if n == 1 else ((josephus_survivor(n - 1, k) + k - 1) % n) + 1 | import sys
# Set new (higher) recursion limit
sys.setrecursionlimit(int(1e6))
# Source: https://en.wikipedia.org/wiki/Josephus_problem#The_general_case
# (I couldn't come up with the formula myself :p)
josephus_survivor = lambda n, k: 1 if n == 1 else ((josephus_survivor(n - 1, k) + k - 1) % n) + 1 | train | APPS_structured |
The chef is trying to decode some pattern problems, Chef wants your help to code it. Chef has one number K to form a new pattern. Help the chef to code this pattern problem.
-----Input:-----
- First-line will contain $T$, the number of test cases. Then the test cases follow.
- Each test case contains a single line of input, one integer $K$.
-----Output:-----
For each test case, output as the pattern.
-----Constraints-----
- $1 \leq T \leq 10$
- $1 \leq K \leq 10$
-----Sample Input:-----
4
1
2
3
4
-----Sample Output:-----
0
0
1 1
0
1 1
2 3 5
0
1 1
2 3 5
8 13 21 34
-----EXPLANATION:-----
No need, else pattern can be decode easily. | t = int(input())
f = [0, 1]
for i in range(2, 100):
f.append(f[i - 1] + f[i - 2])
# print(f[i], ' ')
for i in range(t):
n = int(input())
cnt = 0
for j in range(1, n + 1):
for k in range(1, j + 1):
print(f[cnt], end=' ')
cnt += 1
print() | t = int(input())
f = [0, 1]
for i in range(2, 100):
f.append(f[i - 1] + f[i - 2])
# print(f[i], ' ')
for i in range(t):
n = int(input())
cnt = 0
for j in range(1, n + 1):
for k in range(1, j + 1):
print(f[cnt], end=' ')
cnt += 1
print() | train | APPS_structured |
-----
HALLOWEEN EVE
-----
In some other world, today is Halloween Eve.There are N trees planted in Mr. Smith’s
garden. The height of the i-th tree (1≤i≤N) is h i meters.
He decides to choose K trees from these trees and decorate them with electric lights.
To make the scenery more beautiful, the heights of the decorated trees should be as
close to each other as possible.
More specifically, let the height of the tallest decorated tree be hmax meters, and the
height of the shortest decorated tree be hmin meters.
The smaller the value hmax−hmin is, the better. What is the minimum possible value of
hmax−hmin?
-----Constraints-----
2≤K< N ≤105
1≤hi≤109
hi is an integer
-----Input Format-----
Input is given from Standard Input in the following format:
N K
h1
h2
:
hN
-----Output-----
Print the minimum possible value of hmax−hmin.
-----Example Text Case-----
Input:
5 3
10
15
11
14
12
Output:
2
Explanation
If we decorate the first, third and fifth trees, hmax=12,hmin=10 so hmax−hmin=2. This is
optimal.
| # cook your dish here
import sys
n, k = map(int, input().strip().split())
trees=[]
for _ in range(n):
trees.append(int(input().strip()))
trees.sort()
minimo=1000
for i in range(0,n-k+1):
minimo=min(minimo, trees[i+k-1]-trees[i])
print(minimo) | # cook your dish here
import sys
n, k = map(int, input().strip().split())
trees=[]
for _ in range(n):
trees.append(int(input().strip()))
trees.sort()
minimo=1000
for i in range(0,n-k+1):
minimo=min(minimo, trees[i+k-1]-trees[i])
print(minimo) | train | APPS_structured |
=====Problem Statement=====
The provided code stub reads two integers, a and b, from STDIN.
Add logic to print two lines. The first line should contain the result of integer division,
a // b. The second line should contain the result of float division, a / b.
No rounding or formatting is necessary.
=====Example=====
a = 3
b = 5
The result of the integer division 3//5 = 0.
The result of the float division is 3/5 = 0.6.
Print:
0
0.6
=====Input Format=====
The first line contains the first integer, a.
The second line contains the second integer, b.
=====Output Format=====
Print the two lines as described above. | def __starting_point():
a = int(input())
b = int(input())
print((a//b))
print((a/b))
__starting_point() | def __starting_point():
a = int(input())
b = int(input())
print((a//b))
print((a/b))
__starting_point() | train | APPS_structured |
Complete the function so that it takes an array of keys and a default value and returns a hash (Ruby) / dictionary (Python) with all keys set to the default value.
## Example
```python
["draft", "completed"], 0 # should return {"draft": 0, "completed: 0}
``` | def populate_dict(keys, default):
return dict(zip(keys, [default] * len(keys))) | def populate_dict(keys, default):
return dict(zip(keys, [default] * len(keys))) | train | APPS_structured |
Given an array of citations (each citation is a non-negative integer) of a researcher, write a function to compute the researcher's h-index.
According to the definition of h-index on Wikipedia: "A scientist has index h if h of his/her N papers have at least h citations each, and the other N − h papers have no more than h citations each."
Example:
Input: citations = [3,0,6,1,5]
Output: 3
Explanation: [3,0,6,1,5] means the researcher has 5 papers in total and each of them had
received 3, 0, 6, 1, 5 citations respectively.
Since the researcher has 3 papers with at least 3 citations each and the remaining
two with no more than 3 citations each, her h-index is 3.
Note: If there are several possible values for h, the maximum one is taken as the h-index. | class Solution:
def hIndex(self, citations):
"""
:type citations: List[int]
:rtype: int
"""
if len(citations) == 0:
return 0
else:
citations.sort()
i = 0
while i < len(citations) :
if citations[-i-1] >= (i+1):
i += 1
else:
break
return i
| class Solution:
def hIndex(self, citations):
"""
:type citations: List[int]
:rtype: int
"""
if len(citations) == 0:
return 0
else:
citations.sort()
i = 0
while i < len(citations) :
if citations[-i-1] >= (i+1):
i += 1
else:
break
return i
| train | APPS_structured |
Problem Statement:Captain America and Iron Man are at WAR and the rage inside Iron Man is rising.
But Iron Man faces a problem to identify the location of Captain America.
There are N buildings situtaed adjacently to each other and Captain America can be at any building.
Iron Man has to arrange the Buildings from 1 to N is such a way that Value(i.e abs(Building Number -Position of Building))=K for every building.
Can You help Iron Man to Find The Arrangement of the Buildings?
P.S- If no arrangement exist, then print
“CAPTAIN AMERICA EVADES”.
Input Format:
The first line of input contains a single integer,T, denoting the number of test cases.
Each of the T subsequent lines contains 2 space-separated integers describing the respective N and K values for a test case.
Output Format:
On a new line for each test case,
Print the lexicographically smallest arrangement;
If no absolute arrangement exists, print “CAPTAIN AMERICA EVADES”.
Constraints:
SubTask#1
1<=T<=10
1<=N<=10^5
0<=K<=N
SubTask#2
Original Constraints..
SubTask#3
Original Constraints..
Sample Input:
3
2 1
3 0
3 2
Sample Output:
2 1
1 2 3
CAPTAIN AMERICA EVADES
Explanation:
Case 1:
N=2 and K=1
Therefore the arrangement is [2,1].
Case 2:
N=3 and K=0
Therefore arrangement is [1,2,3]. | t = int(input())
while t:
t-=1
a=[int(i) for i in input().split()]
n=int(a[0])
k=int(a[1])
flag=1
if k==0:
res=[i+1 for i in range(n)]
elif k>n/2 or n%(2*k)!=0:
flag=0
else:
temp1=[i+1 for i in range(k)]
temp2=[i+1 for i in range(k,2*k)]
temp=temp2+temp1
res=[]
x=n/(2*k)
while x:
x-=1
res+=temp
temp = [i+2*k for i in temp]
if flag:
res=[str(i) for i in res]
print(" ".join(res))
else:
print("CAPTAIN AMERICA EVADES")
| t = int(input())
while t:
t-=1
a=[int(i) for i in input().split()]
n=int(a[0])
k=int(a[1])
flag=1
if k==0:
res=[i+1 for i in range(n)]
elif k>n/2 or n%(2*k)!=0:
flag=0
else:
temp1=[i+1 for i in range(k)]
temp2=[i+1 for i in range(k,2*k)]
temp=temp2+temp1
res=[]
x=n/(2*k)
while x:
x-=1
res+=temp
temp = [i+2*k for i in temp]
if flag:
res=[str(i) for i in res]
print(" ".join(res))
else:
print("CAPTAIN AMERICA EVADES")
| train | APPS_structured |
The thief has found himself a new place for his thievery again. There is only one entrance to this area, called the "root." Besides the root, each house has one and only one parent house. After a tour, the smart thief realized that "all houses in this place forms a binary tree". It will automatically contact the police if two directly-linked houses were broken into on the same night.
Determine the maximum amount of money the thief can rob tonight without alerting the police.
Example 1:
3
/ \
2 3
\ \
3 1
Maximum amount of money the thief can rob = 3 + 3 + 1 = 7.
Example 2:
3
/ \
4 5
/ \ \
1 3 1
Maximum amount of money the thief can rob = 4 + 5 = 9.
Credits:Special thanks to @dietpepsi for adding this problem and creating all test cases. | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def rob(self, root):
"""
:type root: TreeNode
:rtype: int
"""
valMap = dict()
def solve(root, path):
if root is None: return 0
if path not in valMap:
left, right = root.left, root.right
ll = lr = rl = rr = None
if left: ll, lr = left.left, left.right
if right: rl, rr = right.left, right.right
passup = solve(left, path + 'l') + solve(right, path + 'r')
grabit = root.val + solve(ll, path + 'll') + solve(lr, path + 'lr') \
+ solve(rl, path + 'rl') + solve(rr, path + 'rr')
valMap[path] = max(passup, grabit)
return valMap[path]
return solve(root, '')
| # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def rob(self, root):
"""
:type root: TreeNode
:rtype: int
"""
valMap = dict()
def solve(root, path):
if root is None: return 0
if path not in valMap:
left, right = root.left, root.right
ll = lr = rl = rr = None
if left: ll, lr = left.left, left.right
if right: rl, rr = right.left, right.right
passup = solve(left, path + 'l') + solve(right, path + 'r')
grabit = root.val + solve(ll, path + 'll') + solve(lr, path + 'lr') \
+ solve(rl, path + 'rl') + solve(rr, path + 'rr')
valMap[path] = max(passup, grabit)
return valMap[path]
return solve(root, '')
| train | APPS_structured |
Ada's classroom contains $N \cdot M$ tables distributed in a grid with $N$ rows and $M$ columns. Each table is occupied by exactly one student.
Before starting the class, the teacher decided to shuffle the students a bit. After the shuffling, each table should be occupied by exactly one student again. In addition, each student should occupy a table that is adjacent to that student's original table, i.e. immediately to the left, right, top or bottom of that table.
Is it possible for the students to shuffle while satisfying all conditions of the teacher?
-----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 $M$.
-----Output-----
For each test case, print a single line containing the string "YES" if it is possible to satisfy the conditions of the teacher or "NO" otherwise (without quotes).
-----Constraints-----
- $1 \le T \le 5,000$
- $2 \le N, M \le 50$
-----Example Input-----
2
3 3
4 4
-----Example Output-----
NO
YES
-----Explanation-----
Example case 2: The arrows in the following image depict how the students moved. | # cook your dish herefor _ in range(int(input())):
for _ in range(int(input())):
x,y=list(map(int,input().split()))
print("NO" if x*y%2 else "YES")
| # cook your dish herefor _ in range(int(input())):
for _ in range(int(input())):
x,y=list(map(int,input().split()))
print("NO" if x*y%2 else "YES")
| train | APPS_structured |
You are given a list of directions in the form of a list:
goal = ["N", "S", "E", "W"]
Pretend that each direction counts for 1 step in that particular direction.
Your task is to create a function called directions, that will return a reduced list that will get you to the same point.The order of directions must be returned as N then S then E then W.
If you get back to beginning, return an empty array. | def directions(goal):
count = lambda s: len([c for c in goal if c == s])
ns = 1 * count("N") - 1 * count("S")
we = 1 * count("W") - 1 * count("E")
ns = [("N" if ns > 0 else "S")] * abs(ns)
we = [("W" if we > 0 else "E")] * abs(we)
return ns + we
| def directions(goal):
count = lambda s: len([c for c in goal if c == s])
ns = 1 * count("N") - 1 * count("S")
we = 1 * count("W") - 1 * count("E")
ns = [("N" if ns > 0 else "S")] * abs(ns)
we = [("W" if we > 0 else "E")] * abs(we)
return ns + we
| train | APPS_structured |
A subsequence of a string S is a string that can be obtained by deleting zero or more characters from S without changing the order of the remaining characters.
For example, arc, artistic and (an empty string) are all subsequences of artistic; abc and ci are not.
You are given a string A consisting of lowercase English letters.
Find the shortest string among the strings consisting of lowercase English letters that are not subsequences of A.
If there are more than one such string, find the lexicographically smallest one among them.
-----Constraints-----
- 1 \leq |A| \leq 2 \times 10^5
- A consists of lowercase English letters.
-----Input-----
Input is given from Standard Input in the following format:
A
-----Output-----
Print the lexicographically smallest string among the shortest strings consisting of lowercase English letters that are not subsequences of A.
-----Sample Input-----
atcoderregularcontest
-----Sample Output-----
b
The string atcoderregularcontest contains a as a subsequence, but not b. | # import sys
from sys import stdout
# from copy import copy, deepcopy
# from functools import lru_cache
# from string import ascii_lowercase
# from math import inf
# inf = float('inf')
def main():
ans = solve_case()
stdout.write("{}\n".format(ans))
def solve_case():
S = read_str()
len_s = len(S)
int_s = [ord(c) - ord('a') for c in S]
# next_char_pos[from_idx][letter_idx] := the position of the next letter `letter_idx` from `from_idx`
next_char_pos = make_list((len_s + 1, 26), len_s)
for from_idx in reversed(list(range(len_s))):
for letter_idx in range(26):
if int_s[from_idx] == letter_idx:
pos = from_idx
else:
pos = next_char_pos[from_idx+1][letter_idx]
next_char_pos[from_idx][letter_idx] = pos
# non_subseq_len[from_idx] := the length of the shortest "non subsequence" in S[from_idx:]
non_subseq_len = make_list([len_s + 2], len_s + 1)
non_subseq_len[len_s] = 1
non_subseq_len[len_s + 1] = 0
ans_next_pos = make_list([len_s + 1], len_s)
ans_letter = make_list([len_s + 1], -1)
for from_idx in reversed(list(range(len_s))):
for letter_idx in range(26):
new_len = non_subseq_len[next_char_pos[from_idx][letter_idx] + 1] + 1
if non_subseq_len[from_idx] > new_len:
non_subseq_len[from_idx] = new_len
ans_letter[from_idx] = letter_idx
ans_next_pos[from_idx] = next_char_pos[from_idx][letter_idx] + 1
ans = ''
idx = 0
while idx < len(S):
ans += chr(ord('a') + ans_letter[idx])
idx = ans_next_pos[idx]
return ans
#################################
def read_str(): return input()
def read_int(): return int(input())
def read_str_list(): return input().split(' ')
def read_int_list(): return list(map(int, input().split(' ')))
def read_lines(n, read_func): return [read_func() for _ in range(n)]
def list_to_str(l, sep=' '): return sep.join(map(str, l))
l2s = list_to_str
# shape: tuple of ints | list of ints
def make_list(shape, value=None):
if len(shape) == 1:
return [value] * shape[0]
return [make_list(shape[1:], value) for _ in range(shape[0])]
def __starting_point():
# sys.setrecursionlimit(1000000)
main()
__starting_point() | # import sys
from sys import stdout
# from copy import copy, deepcopy
# from functools import lru_cache
# from string import ascii_lowercase
# from math import inf
# inf = float('inf')
def main():
ans = solve_case()
stdout.write("{}\n".format(ans))
def solve_case():
S = read_str()
len_s = len(S)
int_s = [ord(c) - ord('a') for c in S]
# next_char_pos[from_idx][letter_idx] := the position of the next letter `letter_idx` from `from_idx`
next_char_pos = make_list((len_s + 1, 26), len_s)
for from_idx in reversed(list(range(len_s))):
for letter_idx in range(26):
if int_s[from_idx] == letter_idx:
pos = from_idx
else:
pos = next_char_pos[from_idx+1][letter_idx]
next_char_pos[from_idx][letter_idx] = pos
# non_subseq_len[from_idx] := the length of the shortest "non subsequence" in S[from_idx:]
non_subseq_len = make_list([len_s + 2], len_s + 1)
non_subseq_len[len_s] = 1
non_subseq_len[len_s + 1] = 0
ans_next_pos = make_list([len_s + 1], len_s)
ans_letter = make_list([len_s + 1], -1)
for from_idx in reversed(list(range(len_s))):
for letter_idx in range(26):
new_len = non_subseq_len[next_char_pos[from_idx][letter_idx] + 1] + 1
if non_subseq_len[from_idx] > new_len:
non_subseq_len[from_idx] = new_len
ans_letter[from_idx] = letter_idx
ans_next_pos[from_idx] = next_char_pos[from_idx][letter_idx] + 1
ans = ''
idx = 0
while idx < len(S):
ans += chr(ord('a') + ans_letter[idx])
idx = ans_next_pos[idx]
return ans
#################################
def read_str(): return input()
def read_int(): return int(input())
def read_str_list(): return input().split(' ')
def read_int_list(): return list(map(int, input().split(' ')))
def read_lines(n, read_func): return [read_func() for _ in range(n)]
def list_to_str(l, sep=' '): return sep.join(map(str, l))
l2s = list_to_str
# shape: tuple of ints | list of ints
def make_list(shape, value=None):
if len(shape) == 1:
return [value] * shape[0]
return [make_list(shape[1:], value) for _ in range(shape[0])]
def __starting_point():
# sys.setrecursionlimit(1000000)
main()
__starting_point() | train | APPS_structured |
We have the following sequence:
```python
f(0) = 0
f(1) = 1
f(2) = 1
f(3) = 2
f(4) = 4;
f(n) = f(n-1) + f(n-2) + f(n-3) + f(n-4) + f(n-5);
```
Your task is to give the number of total values for the odd terms of the sequence up to the n-th term (included). (The number n (of n-th term) will be given as a positive integer)
The values 1 (one) is the only that is duplicated in the sequence and should be counted only once.
E.g.
```
count_odd_pentaFib(5) -----> 1 # because the terms up to 5 are: 0, 1, 1, 2, 4, 8 (only 1 is odd and counted once)
```
Other examples:
```
count_odd_pentaFib(10) ------> 3 #because the odds terms are: [1, 1, 31, 61] (three different values)
count_odd_pentaFib(15) ------> 5 # beacause the odd terms are: [1, 1, 31, 61, 1793, 3525] (five different values)
```
Good luck !!
(Your code should be fast. Many moderate high values will be waiting to test it.) | from collections import deque
def count_odd_pentaFib(n):
if n == 0: return 0
elif n < 6: return 1
def pentabonacci(max_term):
terms = deque((1,1,2,4,8), 5)
m = max_term - 5
for i in range(m):
next_term = sum(terms)
yield next_term
terms.append(next_term)
return len(set((term for term in pentabonacci(n) if term % 2 == 1))) + 1
| from collections import deque
def count_odd_pentaFib(n):
if n == 0: return 0
elif n < 6: return 1
def pentabonacci(max_term):
terms = deque((1,1,2,4,8), 5)
m = max_term - 5
for i in range(m):
next_term = sum(terms)
yield next_term
terms.append(next_term)
return len(set((term for term in pentabonacci(n) if term % 2 == 1))) + 1
| train | APPS_structured |
Write a function which outputs the positions of matching bracket pairs. The output should be a dictionary with keys the positions of the open brackets '(' and values the corresponding positions of the closing brackets ')'.
For example: input = "(first)and(second)" should return {0:6, 10:17}
If brackets cannot be paired or if the order is invalid (e.g. ')(') return False. In this kata we care only about the positions of round brackets '()', other types of brackets should be ignored. | def bracket_pairs(string):
ob, res = [], {}
for n,e in enumerate(string):
if e == '(':
ob.append(n)
elif e == ')':
if not ob:
return False
res[ob.pop()] = n
return False if ob else res | def bracket_pairs(string):
ob, res = [], {}
for n,e in enumerate(string):
if e == '(':
ob.append(n)
elif e == ')':
if not ob:
return False
res[ob.pop()] = n
return False if ob else res | train | APPS_structured |
Everyone Knows AdFly and their Sister Sites.
If we see the Page Source of an ad.fly site we can see this perticular line:
Believe it or not This is actually the Encoded url which you would skip to.
The Algorithm is as Follows:
```
1) The ysmm value is broken like this
ysmm = 0 1 2 3 4 5 6 7 8 9 = "0123456789"
code1 = 0 2 4 6 8 = "02468"
code2 = 9 7 5 3 1 = "97531"
2) code1+code2 is base64 Decoded
3) The result will be of this form :
https://adf.ly/go.php?u=
4) has to be further decoded and the result is to be returned
```
Your Task:
```
Make a function to Encode text to ysmm value.
and a function to Decode ysmm value.
```
Note: Take random values for The first 2 int values.
I personally hate trivial error checking like giving integer input in place of string.
```
Input For Decoder & Encoder: Strings
Return "Invalid" for invalid Strings
``` | import base64
def adFly_decoder(sc):
#your code here
code1 = ''
code2 = ''
flg = True
for ch in sc:
if flg:
code1 += ch
flg = not flg
flg = True
for ch in sc[::-1]:
if flg:
code1 += ch
flg = not flg
try:
s = base64.b64decode(code1 + code2).decode('utf-8')
s = s.split('//adf.ly/go.php?u=')[1]
return base64.b64decode(s).decode('utf-8')
except:
return 'Invalid'
def adFly_encoder(url):
s = '96https://adf.ly/go.php?u='
e_url = base64.b64encode(bytes(url, 'utf-8')).decode('utf-8')
s += e_url
b64 = list(base64.b64encode(bytes(s, 'utf-8')).decode('utf-8'))
yummy = ''
flg = True
while b64:
if flg:
yummy += b64.pop(0)
else:
yummy += b64.pop()
flg = not flg
return yummy | import base64
def adFly_decoder(sc):
#your code here
code1 = ''
code2 = ''
flg = True
for ch in sc:
if flg:
code1 += ch
flg = not flg
flg = True
for ch in sc[::-1]:
if flg:
code1 += ch
flg = not flg
try:
s = base64.b64decode(code1 + code2).decode('utf-8')
s = s.split('//adf.ly/go.php?u=')[1]
return base64.b64decode(s).decode('utf-8')
except:
return 'Invalid'
def adFly_encoder(url):
s = '96https://adf.ly/go.php?u='
e_url = base64.b64encode(bytes(url, 'utf-8')).decode('utf-8')
s += e_url
b64 = list(base64.b64encode(bytes(s, 'utf-8')).decode('utf-8'))
yummy = ''
flg = True
while b64:
if flg:
yummy += b64.pop(0)
else:
yummy += b64.pop()
flg = not flg
return yummy | train | APPS_structured |
=====Function Descriptions=====
We have seen the applications of union, intersection, difference and symmetric difference operations, but these operations do not make any changes or mutations to the set.
We can use the following operations to create mutations to a set:
.update() or |=
Update the set by adding elements from an iterable/another set.
>>> H = set("Hacker")
>>> R = set("Rank")
>>> H.update(R)
>>> print H
set(['a', 'c', 'e', 'H', 'k', 'n', 'r', 'R'])
.intersection_update() or &=
Update the set by keeping only the elements found in it and an iterable/another set.
>>> H = set("Hacker")
>>> R = set("Rank")
>>> H.intersection_update(R)
>>> print H
set(['a', 'k'])
.difference_update() or -=
Update the set by removing elements found in an iterable/another set.
>>> H = set("Hacker")
>>> R = set("Rank")
>>> H.difference_update(R)
>>> print H
set(['c', 'e', 'H', 'r'])
.symmetric_difference_update() or ^=
Update the set by only keeping the elements found in either set, but not in both.
>>> H = set("Hacker")
>>> R = set("Rank")
>>> H.symmetric_difference_update(R)
>>> print H
set(['c', 'e', 'H', 'n', 'r', 'R'])
=====Problem Statement=====
You are given a set A and N number of other sets. These N number of sets have to perform some specific mutation operations on set A.
Your task is to execute those operations and print the sum of elements from set A.
=====Input Format=====
The first line contains the number of elements in set A.
The second line contains the space separated list of elements in set A.
The third line contains integer N, the number of other sets.
The next 2 * N lines are divided into N parts containing two lines each.
The first line of each part contains the space separated entries of the operation name and the length of the other set.
The second line of each part contains space separated list of elements in the other set.
=====Constraints=====
0<len(set(A))<1000
0<len(otherSets)<100
0<N<100
=====Output Format=====
Output the sum of elements in set A. | #!/usr/bin/env python3
def __starting_point():
n = int(input())
s = set(map(int, input().split()))
num_cmds = int(input())
for _i in range(num_cmds):
cmd = list(input().strip().split(' '))
if cmd[0] == 'intersection_update':
get_set = set(map(int, input().split(' ')))
s &= get_set
elif cmd[0] == 'update':
get_set = set(map(int, input().split(' ')))
s |= get_set
elif cmd[0] == 'difference_update':
get_set = set(map(int, input().split(' ')))
s -= get_set
elif cmd[0] == 'symmetric_difference_update':
get_set = set(map(int, input().split(' ')))
s ^= get_set
print((sum(s)))
__starting_point() | #!/usr/bin/env python3
def __starting_point():
n = int(input())
s = set(map(int, input().split()))
num_cmds = int(input())
for _i in range(num_cmds):
cmd = list(input().strip().split(' '))
if cmd[0] == 'intersection_update':
get_set = set(map(int, input().split(' ')))
s &= get_set
elif cmd[0] == 'update':
get_set = set(map(int, input().split(' ')))
s |= get_set
elif cmd[0] == 'difference_update':
get_set = set(map(int, input().split(' ')))
s -= get_set
elif cmd[0] == 'symmetric_difference_update':
get_set = set(map(int, input().split(' ')))
s ^= get_set
print((sum(s)))
__starting_point() | train | APPS_structured |
Given an integer array nums, find the contiguous subarray within an array (containing at least one number) which has the largest product.
Example 1:
Input: [2,3,-2,4]
Output: 6
Explanation: [2,3] has the largest product 6.
Example 2:
Input: [-2,0,-1]
Output: 0
Explanation: The result cannot be 2, because [-2,-1] is not a subarray. | class Solution:
def maxProduct(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
n=len(nums)
if n==0: return 0
if n==1: return nums[0]
ans=nums[0]
l=0
r=n-1
prod=1
i=0
while i<n:
if nums[i]==0:
zero_idx=i
return max(self.maxProduct(nums[(zero_idx+1):]), max(0,self.maxProduct(nums[0:zero_idx])))
else:
prod=prod*nums[i]
i=i+1
if prod>0: return prod
prod_right=prod
max_prod_right=prod
prod_left=prod
max_prod_left=prod
if prod<0:
#print(max_prod_right)
while 0<=r:
prod_right=prod_right//nums[r]
r=r-1
if prod_right>max_prod_right:
if prod_right>0:
max_prod_right=prod_right
break
else:
max_prod_right=prod_right
print(max_prod_left)
while l<n:
prod_left=prod_left//nums[l]
l=l+1
#print(l, prod_left,"----", nums[l], nums[l:])
if prod_left>max_prod_left:
if prod_left>0:
max_prod_left=prod_left
break
else:
max_prod_left=prod_left
#print(max_prod_left, max_prod_right)
return max(max_prod_left, max_prod_right)
| class Solution:
def maxProduct(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
n=len(nums)
if n==0: return 0
if n==1: return nums[0]
ans=nums[0]
l=0
r=n-1
prod=1
i=0
while i<n:
if nums[i]==0:
zero_idx=i
return max(self.maxProduct(nums[(zero_idx+1):]), max(0,self.maxProduct(nums[0:zero_idx])))
else:
prod=prod*nums[i]
i=i+1
if prod>0: return prod
prod_right=prod
max_prod_right=prod
prod_left=prod
max_prod_left=prod
if prod<0:
#print(max_prod_right)
while 0<=r:
prod_right=prod_right//nums[r]
r=r-1
if prod_right>max_prod_right:
if prod_right>0:
max_prod_right=prod_right
break
else:
max_prod_right=prod_right
print(max_prod_left)
while l<n:
prod_left=prod_left//nums[l]
l=l+1
#print(l, prod_left,"----", nums[l], nums[l:])
if prod_left>max_prod_left:
if prod_left>0:
max_prod_left=prod_left
break
else:
max_prod_left=prod_left
#print(max_prod_left, max_prod_right)
return max(max_prod_left, max_prod_right)
| train | APPS_structured |
Given a positive integer n, find the least number of perfect square numbers (for example, 1, 4, 9, 16, ...) which sum to n.
Example 1:
Input: n = 12
Output: 3
Explanation: 12 = 4 + 4 + 4.
Example 2:
Input: n = 13
Output: 2
Explanation: 13 = 4 + 9. | class Solution:
def numSquares(self, n):
import math
def is_square(m):
sqrt_m = int(math.sqrt(m))
return sqrt_m * sqrt_m == m
if is_square(n):
return 1
while (n & 3) == 0:
n >>= 2
if (n & 7) == 7:
return 4
sqrt_n = int(math.sqrt(n))
for i in range(1, sqrt_n + 1):
if is_square(n - (i * i)):
return 2
return 3 | class Solution:
def numSquares(self, n):
import math
def is_square(m):
sqrt_m = int(math.sqrt(m))
return sqrt_m * sqrt_m == m
if is_square(n):
return 1
while (n & 3) == 0:
n >>= 2
if (n & 7) == 7:
return 4
sqrt_n = int(math.sqrt(n))
for i in range(1, sqrt_n + 1):
if is_square(n - (i * i)):
return 2
return 3 | train | APPS_structured |
Did you hear about the Nibiru collision ? It is a supposed disastrous encounter between the earth and a large planetary object. Astronomers reject this idea. But why listen to other people's beliefs and opinions. We are coders above all, so what better way than to verify it by a small code. The earth and N asteroids are in the 2D plane. Each of them is initially located at some integer coordinates at time = 0 and is moving parallel to one of the X or Y axis with constant velocity of 1 unit per second.
Direction of movement is given as 'U' ( Up = towards positive Y ), 'D' ( Down = towards negative Y ), 'R' ( Right = towards positive X ), 'L' ( Left = towards negative X ). Given the initial position and the direction of movement of the earth and each of the N asteroids, find the earliest time at which the earth collides with one of the asteroids. If there can not be any collisions with the earth, print "SAFE" ( without quotes ). You can ignore the collisions between asteroids ( i.e., they continue to move in same direction even after collisions between them ).
-----Input-----
First line contains T, number of test cases. T cases follow. In each test case, first line contains XE YE DIRE, where (XE,YE) is the initial position of the Earth, DIRE is the direction in which it moves. Second line contains N, the number of
asteroids. N lines follow, each containing XA YA DIRA, the initial position and the direction of movement of each asteroid. No asteroid is initially located at (XE,YE)
-----Output-----
For each test case, output the earliest time at which the earth can collide with an asteroid (rounded to 1 position after decimal). If there can not be any collisions with the earth, print "SAFE" (without quotes).
-----Constraints-----
1 ≤ T ≤ 10
1 ≤ N ≤ 2012
-100 ≤ XE, YE, XA, YA ≤ 100
(XE,YE) != any of (XA,YA)
DIRE, DIRA is one of 'U', 'R', 'D', 'L'
-----Example-----
Input:
3
0 0 R
2
1 -2 U
2 2 D
1 1 U
1
1 0 U
0 0 R
1
3 0 L
Output:
2.0
SAFE
1.5
Explanation:
Case 1 :
Time 0 - Earth (0,0) Asteroids { (1,-2), (2,2) }
Time 1 - Earth (1,0) Asteroids { (1,-1), (2,1) }
Time 2 - Earth (2,0) Asteroids { (1,0 ), (2,0) }
Case 2 :
The only asteroid is just one unit away below the earth and following us always, but it will never collide :)
Case 3 :
Time 0 - Earth (0,0) Asteroid (3,0)
Time 1 - Earth (1,0) Asteroid (2,0)
Time 1.5 - Earth (1.5,0) Asteroid (1.5,0)
Note : There are multiple test sets, and the judge shows the sum of the time taken over all test sets of your submission, if Accepted. | #-*- coding:utf-8 -*-
import sys
# class Point:
# def __init__(self, x, y):
# self.x = x
# self.y = y
# def mul(self, k):
# return Point(k * self.x, k * self.y)
# def __add__(self, other):
# return Point(self.x + other.x, self.y + other.y)
# def __sub__(self, other):
# return self + (-other)
# def __neg__(self):
# return Point(-self.x, -self.y)
# def __eq__(self, other):
# return self.x == other.x and self.y == other.y
# def __getitem__(self, index):
# return (self.x, self.y)[index]
# def __str__(self):
# return "(%d;%d)" % (self.x, self.y)
DIRS = dict(
U=(0, 1),
D=(0, -1),
R=(1, 0),
L=(-1, 0)
)
KOEF = 0.2
def div(a, b):
return round(float(a) / b, 1)
# class Moving:
# def __init__(self, x, y, dir):
# self.p = Point(x, y)
# self.dir = Point(*DIRS[dir.upper()])
# def collide(self, other):
# times = []
# for coord in range(2):
# d = abs(self.p[coord] - other.p[coord])
# d2 = abs((self.p + self.dir.mul(KOEF) - other.p)[coord])
# d3 = abs((other.p + other.dir.mul(KOEF) - self.p)[coord])
# d_next = abs((self.p + self.dir.mul(KOEF) - (other.p + other.dir .mul(KOEF)))[coord])
# if d2 > d or d3 > d:
# return None
# speed = abs(d_next - d)
# if speed == 0:
# if self.p[coord] != other.p[coord]:
# return None
# continue
# times.append( div(d, speed / KOEF) )
# if len(times) == 2 and times[0] != times[1]:
# return
# return times[0]
def collide_coord(ex, edx, x, dx):
d = abs(ex - x)
d2 = abs(ex + edx - x)
d3 = abs(ex - x - dx)
if d2 > d or d3 > d:
return False
d_next = abs(ex + edx * KOEF - x - dx * KOEF)
speed = abs(d_next - d)
if speed == 0:
if ex != x:
return
return "all" # all
else:
return div(d, speed / KOEF)
def main():
t = int(input())
for _ in range(t):
ex, ey, dir = sys.stdin.readline().strip().split()
ex = int(ex)
ey = int(ey)
edx, edy = DIRS[dir]
n = int(sys.stdin.readline())
min_time = float("+inf")
for _ in range(n):
x, y, dir = sys.stdin.readline().strip().split()
x = int(x)
y = int(y)
dx, dy = DIRS[dir]
tx = collide_coord(ex, edx, x, dx)
if tx is False:
continue
ty = collide_coord(ey, edy, y, dy)
if ty is False:
continue
if tx == "all":
min_time = min(min_time, ty)
elif ty == "all":
min_time = min(min_time, tx)
elif tx == ty:
min_time = min(min_time, tx)
print(min_time if min_time < 1000000 else "SAFE")
def __starting_point():
main()
__starting_point() | #-*- coding:utf-8 -*-
import sys
# class Point:
# def __init__(self, x, y):
# self.x = x
# self.y = y
# def mul(self, k):
# return Point(k * self.x, k * self.y)
# def __add__(self, other):
# return Point(self.x + other.x, self.y + other.y)
# def __sub__(self, other):
# return self + (-other)
# def __neg__(self):
# return Point(-self.x, -self.y)
# def __eq__(self, other):
# return self.x == other.x and self.y == other.y
# def __getitem__(self, index):
# return (self.x, self.y)[index]
# def __str__(self):
# return "(%d;%d)" % (self.x, self.y)
DIRS = dict(
U=(0, 1),
D=(0, -1),
R=(1, 0),
L=(-1, 0)
)
KOEF = 0.2
def div(a, b):
return round(float(a) / b, 1)
# class Moving:
# def __init__(self, x, y, dir):
# self.p = Point(x, y)
# self.dir = Point(*DIRS[dir.upper()])
# def collide(self, other):
# times = []
# for coord in range(2):
# d = abs(self.p[coord] - other.p[coord])
# d2 = abs((self.p + self.dir.mul(KOEF) - other.p)[coord])
# d3 = abs((other.p + other.dir.mul(KOEF) - self.p)[coord])
# d_next = abs((self.p + self.dir.mul(KOEF) - (other.p + other.dir .mul(KOEF)))[coord])
# if d2 > d or d3 > d:
# return None
# speed = abs(d_next - d)
# if speed == 0:
# if self.p[coord] != other.p[coord]:
# return None
# continue
# times.append( div(d, speed / KOEF) )
# if len(times) == 2 and times[0] != times[1]:
# return
# return times[0]
def collide_coord(ex, edx, x, dx):
d = abs(ex - x)
d2 = abs(ex + edx - x)
d3 = abs(ex - x - dx)
if d2 > d or d3 > d:
return False
d_next = abs(ex + edx * KOEF - x - dx * KOEF)
speed = abs(d_next - d)
if speed == 0:
if ex != x:
return
return "all" # all
else:
return div(d, speed / KOEF)
def main():
t = int(input())
for _ in range(t):
ex, ey, dir = sys.stdin.readline().strip().split()
ex = int(ex)
ey = int(ey)
edx, edy = DIRS[dir]
n = int(sys.stdin.readline())
min_time = float("+inf")
for _ in range(n):
x, y, dir = sys.stdin.readline().strip().split()
x = int(x)
y = int(y)
dx, dy = DIRS[dir]
tx = collide_coord(ex, edx, x, dx)
if tx is False:
continue
ty = collide_coord(ey, edy, y, dy)
if ty is False:
continue
if tx == "all":
min_time = min(min_time, ty)
elif ty == "all":
min_time = min(min_time, tx)
elif tx == ty:
min_time = min(min_time, tx)
print(min_time if min_time < 1000000 else "SAFE")
def __starting_point():
main()
__starting_point() | train | APPS_structured |
Given an array of integers arr, and three integers a, b and c. You need to find the number of good triplets.
A triplet (arr[i], arr[j], arr[k]) is good if the following conditions are true:
0 <= i < j < k < arr.length
|arr[i] - arr[j]| <= a
|arr[j] - arr[k]| <= b
|arr[i] - arr[k]| <= c
Where |x| denotes the absolute value of x.
Return the number of good triplets.
Example 1:
Input: arr = [3,0,1,1,9,7], a = 7, b = 2, c = 3
Output: 4
Explanation: There are 4 good triplets: [(3,0,1), (3,0,1), (3,1,1), (0,1,1)].
Example 2:
Input: arr = [1,1,2,2,3], a = 0, b = 0, c = 1
Output: 0
Explanation: No triplet satisfies all conditions.
Constraints:
3 <= arr.length <= 100
0 <= arr[i] <= 1000
0 <= a, b, c <= 1000 | class Solution:
def countGoodTriplets(self, arr: List[int], a: int, b: int, c: int) -> int:
ans = 0
for i1,v1 in enumerate(arr):
for i2, v2 in enumerate(arr[i1+1:]):
if abs(v1 - v2) <= a:
for v3 in arr[i1+i2+2:]:
if abs(v1 - v3) <= c and abs(v2 - v3) <= b:
ans += 1
return ans | class Solution:
def countGoodTriplets(self, arr: List[int], a: int, b: int, c: int) -> int:
ans = 0
for i1,v1 in enumerate(arr):
for i2, v2 in enumerate(arr[i1+1:]):
if abs(v1 - v2) <= a:
for v3 in arr[i1+i2+2:]:
if abs(v1 - v3) <= c and abs(v2 - v3) <= b:
ans += 1
return ans | train | APPS_structured |
Please write a function that sums a list, but ignores any duplicate items in the list.
For instance, for the list [3, 4, 3, 6] , the function should return 10. | from collections import Counter
def sum_no_duplicates(l):
c = Counter(l)
return sum(k for k,v in c.items() if v == 1) | from collections import Counter
def sum_no_duplicates(l):
c = Counter(l)
return sum(k for k,v in c.items() if v == 1) | train | APPS_structured |
To protect people from evil,
a long and tall wall was constructed a few years ago.
But just a wall is not safe, there should also be soldiers on it,
always keeping vigil.
The wall is very long and connects the left and the right towers.
There are exactly N spots (numbered 1 to N) on the wall for soldiers.
The Kth spot is K miles far from the left tower and (N+1-K) miles from the right tower.
Given a permutation of spots P of {1, 2, ..., N}, soldiers occupy the N spots in that order.
The P[i]th spot is occupied before the P[i+1]th spot.
When a soldier occupies a spot, he is connected to his nearest soldier already placed to his left.
If there is no soldier to his left, he is connected to the left tower. The same is the case with right side.
A connection between two spots requires a wire of length equal to the distance between the two.
The realm has already purchased a wire of M miles long from Nokia,
possibly the wire will be cut into smaller length wires.
As we can observe, the total length of the used wire depends on the permutation of the spots P. Help the realm in minimizing the length of the unused wire. If there is not enough wire, output -1.
-----Input-----
First line contains an integer T (number of test cases, 1 ≤ T ≤ 10 ). Each of the next T lines contains two integers N M, as explained in the problem statement (1 ≤ N ≤ 30 , 1 ≤ M ≤ 1000).
-----Output-----
For each test case, output the minimum length of the unused wire, or -1 if the the wire is not sufficient.
-----Example-----
Input:
4
3 8
3 9
2 4
5 25
Output:
0
0
-1
5
Explanation:
In the 1st case, for example, the permutation P = {2, 1, 3} will use the exact 8 miles wires in total.
In the 2nd case, for example, the permutation P = {1, 3, 2} will use the exact 9 miles wires in total.
To understand the first two cases, you can see the following figures:
In the 3rd case, the minimum length of wire required is 5, for any of the permutations {1,2} or {2,1}, so length 4 is not sufficient.
In the 4th case, for the permutation {1, 2, 3, 4, 5} we need the maximum length of the wire = 20. So minimum possible unused wire length = 25 - 20 = 5. | NumOfTests = int(input())
pwrOfTwo = [2, 4, 8, 16]
for test in range(NumOfTests):
N, M = input().split()
N = int(N)
M = int(M)
if N == 1:
used_m = 2
m_div = M - used_m
if m_div < 0:
print(-1)
else:
print(m_div)
else:
x, y = divmod(N, 2)
max_p = x*(N+3) + y*(N+3)/2
max_pwr = max([x for x in pwrOfTwo if N+1 >= x])
min_p = (N+1)*(pwrOfTwo.index(max_pwr)+1) + 2*(N+1-max_pwr)
if min_p > M:
print(-1)
elif M <= max_p:
print(0)
else:
print(M - max_p)
| NumOfTests = int(input())
pwrOfTwo = [2, 4, 8, 16]
for test in range(NumOfTests):
N, M = input().split()
N = int(N)
M = int(M)
if N == 1:
used_m = 2
m_div = M - used_m
if m_div < 0:
print(-1)
else:
print(m_div)
else:
x, y = divmod(N, 2)
max_p = x*(N+3) + y*(N+3)/2
max_pwr = max([x for x in pwrOfTwo if N+1 >= x])
min_p = (N+1)*(pwrOfTwo.index(max_pwr)+1) + 2*(N+1-max_pwr)
if min_p > M:
print(-1)
elif M <= max_p:
print(0)
else:
print(M - max_p)
| train | APPS_structured |
Karen has just arrived at school, and she has a math test today! [Image]
The test is about basic addition and subtraction. Unfortunately, the teachers were too busy writing tasks for Codeforces rounds, and had no time to make an actual test. So, they just put one question in the test that is worth all the points.
There are n integers written on a row. Karen must alternately add and subtract each pair of adjacent integers, and write down the sums or differences on the next row. She must repeat this process on the values on the next row, and so on, until only one integer remains. The first operation should be addition.
Note that, if she ended the previous row by adding the integers, she should start the next row by subtracting, and vice versa.
The teachers will simply look at the last integer, and then if it is correct, Karen gets a perfect score, otherwise, she gets a zero for the test.
Karen has studied well for this test, but she is scared that she might make a mistake somewhere and it will cause her final answer to be wrong. If the process is followed, what number can she expect to be written on the last row?
Since this number can be quite large, output only the non-negative remainder after dividing it by 10^9 + 7.
-----Input-----
The first line of input contains a single integer n (1 ≤ n ≤ 200000), the number of numbers written on the first row.
The next line contains n integers. Specifically, the i-th one among these is a_{i} (1 ≤ a_{i} ≤ 10^9), the i-th number on the first row.
-----Output-----
Output a single integer on a line by itself, the number on the final row after performing the process above.
Since this number can be quite large, print only the non-negative remainder after dividing it by 10^9 + 7.
-----Examples-----
Input
5
3 6 9 12 15
Output
36
Input
4
3 7 5 2
Output
1000000006
-----Note-----
In the first test case, the numbers written on the first row are 3, 6, 9, 12 and 15.
Karen performs the operations as follows: [Image]
The non-negative remainder after dividing the final number by 10^9 + 7 is still 36, so this is the correct output.
In the second test case, the numbers written on the first row are 3, 7, 5 and 2.
Karen performs the operations as follows: [Image]
The non-negative remainder after dividing the final number by 10^9 + 7 is 10^9 + 6, so this is the correct output. | #!/usr/bin/env pypy3
import math
def make_nCr_mod(max_n=2*10**5 + 100, mod=10**9 + 7):
fact, inv_fact = [0] * (max_n + 1), [0] * (max_n + 1)
fact[0] = 1
for i in range(max_n):
fact[i + 1] = fact[i] * (i + 1) % mod
inv_fact[-1] = pow(fact[-1], mod - 2, mod)
for i in reversed(range(max_n)):
inv_fact[i] = inv_fact[i + 1] * (i + 1) % mod
def nCr_mod(n, r):
res = 1
while n or r:
a, b = n % mod, r % mod
if a < b:
return 0
res = res * fact[a] % mod * inv_fact[b] % mod * inv_fact[a - b] % mod
n //= mod
r //= mod
return res
return nCr_mod
nCr_mod = make_nCr_mod()
MODULUS = 10**9+7
input()
A = input().split(' ')
A = list(map(int, A))
if len(A) == 1:
print(A[0])
return
if len(A) % 2 == 1:
new_A = []
next_plus = True
for i in range(len(A) - 1):
if next_plus:
new_A += [A[i] + A[i+1]]
else:
new_A += [A[i] - A[i+1]]
next_plus = not next_plus
A = new_A
if len(A) % 4 == 2:
new_A = []
for i in range(len(A) // 2):
new_A += [A[2*i] + A[2*i+1]]
A = new_A
else:
new_A = []
for i in range(len(A) // 2):
new_A += [A[2*i] - A[2*i+1]]
A = new_A
# binomial sum
N = len(A)-1
ret = 0
for i in range(N+1):
ret += A[i]*nCr_mod(N, i)
ret = ret % MODULUS
print(ret) | #!/usr/bin/env pypy3
import math
def make_nCr_mod(max_n=2*10**5 + 100, mod=10**9 + 7):
fact, inv_fact = [0] * (max_n + 1), [0] * (max_n + 1)
fact[0] = 1
for i in range(max_n):
fact[i + 1] = fact[i] * (i + 1) % mod
inv_fact[-1] = pow(fact[-1], mod - 2, mod)
for i in reversed(range(max_n)):
inv_fact[i] = inv_fact[i + 1] * (i + 1) % mod
def nCr_mod(n, r):
res = 1
while n or r:
a, b = n % mod, r % mod
if a < b:
return 0
res = res * fact[a] % mod * inv_fact[b] % mod * inv_fact[a - b] % mod
n //= mod
r //= mod
return res
return nCr_mod
nCr_mod = make_nCr_mod()
MODULUS = 10**9+7
input()
A = input().split(' ')
A = list(map(int, A))
if len(A) == 1:
print(A[0])
return
if len(A) % 2 == 1:
new_A = []
next_plus = True
for i in range(len(A) - 1):
if next_plus:
new_A += [A[i] + A[i+1]]
else:
new_A += [A[i] - A[i+1]]
next_plus = not next_plus
A = new_A
if len(A) % 4 == 2:
new_A = []
for i in range(len(A) // 2):
new_A += [A[2*i] + A[2*i+1]]
A = new_A
else:
new_A = []
for i in range(len(A) // 2):
new_A += [A[2*i] - A[2*i+1]]
A = new_A
# binomial sum
N = len(A)-1
ret = 0
for i in range(N+1):
ret += A[i]*nCr_mod(N, i)
ret = ret % MODULUS
print(ret) | train | APPS_structured |
A [Narcissistic Number](https://en.wikipedia.org/wiki/Narcissistic_number) is a positive number which is the sum of its own digits, each raised to the power of the number of digits in a given base. In this Kata, we will restrict ourselves to decimal (base 10).
For example, take 153 (3 digits):
```
1^3 + 5^3 + 3^3 = 1 + 125 + 27 = 153
```
and 1634 (4 digits):
```
1^4 + 6^4 + 3^4 + 4^4 = 1 + 1296 + 81 + 256 = 1634
```
The Challenge:
Your code must return **true or false** depending upon whether the given number is a Narcissistic number in base 10.
Error checking for text strings or other invalid inputs is not required, only valid positive non-zero integers will be passed into the function. | def narcissistic(value):
num_str = str(value)
length = len(num_str)
return sum(int(a) ** length for a in num_str) == value
| def narcissistic(value):
num_str = str(value)
length = len(num_str)
return sum(int(a) ** length for a in num_str) == value
| train | APPS_structured |
There are 2N balls in the xy-plane. The coordinates of the i-th of them is (x_i, y_i).
Here, x_i and y_i are integers between 1 and N (inclusive) for all i, and no two balls occupy the same coordinates.
In order to collect these balls, Snuke prepared 2N robots, N of type A and N of type B.
Then, he placed the type-A robots at coordinates (1, 0), (2, 0), ..., (N, 0), and the type-B robots at coordinates (0, 1), (0, 2), ..., (0, N), one at each position.
When activated, each type of robot will operate as follows.
- When a type-A robot is activated at coordinates (a, 0), it will move to the position of the ball with the lowest y-coordinate among the balls on the line x = a, collect the ball and deactivate itself. If there is no such ball, it will just deactivate itself without doing anything.
- When a type-B robot is activated at coordinates (0, b), it will move to the position of the ball with the lowest x-coordinate among the balls on the line y = b, collect the ball and deactivate itself. If there is no such ball, it will just deactivate itself without doing anything.
Once deactivated, a robot cannot be activated again. Also, while a robot is operating, no new robot can be activated until the operating robot is deactivated.
When Snuke was about to activate a robot, he noticed that he may fail to collect all the balls, depending on the order of activating the robots.
Among the (2N)! possible orders of activating the robots, find the number of the ones such that all the balls can be collected, modulo 1 000 000 007.
-----Constraints-----
- 2 \leq N \leq 10^5
- 1 \leq x_i \leq N
- 1 \leq y_i \leq N
- If i ≠ j, either x_i ≠ x_j or y_i ≠ y_j.
-----Inputs-----
Input is given from Standard Input in the following format:
N
x_1 y_1
...
x_{2N} y_{2N}
-----Outputs-----
Print the number of the orders of activating the robots such that all the balls can be collected, modulo 1 000 000 007.
-----Sample Input-----
2
1 1
1 2
2 1
2 2
-----Sample Output-----
8
We will refer to the robots placed at (1, 0) and (2, 0) as A1 and A2, respectively, and the robots placed at (0, 1) and (0, 2) as B1 and B2, respectively.
There are eight orders of activation that satisfy the condition, as follows:
- A1, B1, A2, B2
- A1, B1, B2, A2
- A1, B2, B1, A2
- A2, B1, A1, B2
- B1, A1, B2, A2
- B1, A1, A2, B2
- B1, A2, A1, B2
- B2, A1, B1, A2
Thus, the output should be 8. | import sys
input = sys.stdin.readline
MOD = 10**9 + 7
N = int(input())
ball = (tuple(int(x) for x in row.split()) for row in sys.stdin.readlines())
# x座標を1,2,...,N
# y座標をN+1,N+2,...,N+N
graph = [set() for _ in range(N+N+1)]
for x,y in ball:
graph[x].add(y+N)
graph[y+N].add(x)
visited = [False] * (N+N+1)
components = []
for x in range(1,N+N+1):
if visited[x]:
continue
V = set([x])
E = []
q = [x]
visited[x] = True
while q:
y = q.pop()
for z in graph[y]:
if y < z:
E.append((y,z))
if visited[z]:
continue
V.add(z)
visited[z] = True
q.append(z)
components.append((V,E))
def make_get_pattern(V):
deg1 = [x for x in V if len(graph[x]) == 1]
get = {}
while deg1:
x = deg1.pop()
if not graph[x]:
continue
y = graph[x].pop()
se = graph[y]; se.remove(x)
if len(se) == 1: deg1.append(y)
if x < y:
get[(x,y)] = 0
else:
get[(y,x)] = 1
for x in V:
if graph[x]:
y = graph[x].pop()
break
# 残りはサイクル
graph[y].remove(x)
if x > y: x,y = y,x
get[(x,y)] = 2
while graph[x]:
y = graph[x].pop()
graph[y].remove(x)
if x < y:
get[(x,y)] = 3
else:
get[(y,x)] = 2
x = y
return get
def F(V,E):
# V is connected
if len(E) != len(V):
return 0
ret = 0
E.sort()
get = make_get_pattern(V)
den1,den2 = 1,1
dp1 = {x:0 for x in V}
dp2 = {x:0 for x in V}
for x,y in E:
if get[(x,y)] == 0:
k1 = dp1[x] + 1; k2 = dp2[x] + 1
elif get[(x,y)] == 1:
k1 = dp1[y] + 1; k2 = dp2[y] + 1
elif get[(x,y)] == 2:
k1 = dp1[x] + 1; k2 = dp2[y] + 1
else:
k1 = dp1[y] + 1; k2 = dp2[x] + 1
dp1[x] += k1; dp1[y] += k1
dp2[x] += k2; dp2[y] += k2
den1 *= k1; den2 *= k2
den1 %= MOD; den2 %= MOD
return sum(pow(x,MOD-2,MOD) for x in (den1,den2))
prob = 1
for c in components:
prob *= F(*c)
prob %= MOD
answer = prob
for n in range(1,N+N+1):
answer *= n
answer %= MOD
print(answer) | import sys
input = sys.stdin.readline
MOD = 10**9 + 7
N = int(input())
ball = (tuple(int(x) for x in row.split()) for row in sys.stdin.readlines())
# x座標を1,2,...,N
# y座標をN+1,N+2,...,N+N
graph = [set() for _ in range(N+N+1)]
for x,y in ball:
graph[x].add(y+N)
graph[y+N].add(x)
visited = [False] * (N+N+1)
components = []
for x in range(1,N+N+1):
if visited[x]:
continue
V = set([x])
E = []
q = [x]
visited[x] = True
while q:
y = q.pop()
for z in graph[y]:
if y < z:
E.append((y,z))
if visited[z]:
continue
V.add(z)
visited[z] = True
q.append(z)
components.append((V,E))
def make_get_pattern(V):
deg1 = [x for x in V if len(graph[x]) == 1]
get = {}
while deg1:
x = deg1.pop()
if not graph[x]:
continue
y = graph[x].pop()
se = graph[y]; se.remove(x)
if len(se) == 1: deg1.append(y)
if x < y:
get[(x,y)] = 0
else:
get[(y,x)] = 1
for x in V:
if graph[x]:
y = graph[x].pop()
break
# 残りはサイクル
graph[y].remove(x)
if x > y: x,y = y,x
get[(x,y)] = 2
while graph[x]:
y = graph[x].pop()
graph[y].remove(x)
if x < y:
get[(x,y)] = 3
else:
get[(y,x)] = 2
x = y
return get
def F(V,E):
# V is connected
if len(E) != len(V):
return 0
ret = 0
E.sort()
get = make_get_pattern(V)
den1,den2 = 1,1
dp1 = {x:0 for x in V}
dp2 = {x:0 for x in V}
for x,y in E:
if get[(x,y)] == 0:
k1 = dp1[x] + 1; k2 = dp2[x] + 1
elif get[(x,y)] == 1:
k1 = dp1[y] + 1; k2 = dp2[y] + 1
elif get[(x,y)] == 2:
k1 = dp1[x] + 1; k2 = dp2[y] + 1
else:
k1 = dp1[y] + 1; k2 = dp2[x] + 1
dp1[x] += k1; dp1[y] += k1
dp2[x] += k2; dp2[y] += k2
den1 *= k1; den2 *= k2
den1 %= MOD; den2 %= MOD
return sum(pow(x,MOD-2,MOD) for x in (den1,den2))
prob = 1
for c in components:
prob *= F(*c)
prob %= MOD
answer = prob
for n in range(1,N+N+1):
answer *= n
answer %= MOD
print(answer) | train | APPS_structured |
Create a function hollow_triangle(height) that returns a hollow triangle of the correct height. The height is passed through to the function and the function should return a list containing each line of the hollow triangle.
```
hollow_triangle(6) should return : ['_____#_____', '____#_#____', '___#___#___', '__#_____#__', '_#_______#_', '###########']
hollow_triangle(9) should return : ['________#________', '_______#_#_______', '______#___#______', '_____#_____#_____', '____#_______#____', '___#_________#___', '__#___________#__', '_#_____________#_', '#################']
```
The final idea is for the hollow triangle is to look like this if you decide to print each element of the list:
```
hollow_triangle(6) will result in:
_____#_____ 1
____#_#____ 2
___#___#___ 3
__#_____#__ 4
_#_______#_ 5
########### 6 ---- Final Height
hollow_triangle(9) will result in:
________#________ 1
_______#_#_______ 2
______#___#______ 3
_____#_____#_____ 4
____#_______#____ 5
___#_________#___ 6
__#___________#__ 7
_#_____________#_ 8
################# 9 ---- Final Height
```
Pad spaces with underscores i.e _ so each line is the same length.Goodluck and have fun coding ! | def hollow_triangle(n):
return [(f'#{"_" * (2*i-1)}#' if i else '#').center(2*n-1, '_') for i in range(n-1)] + ['#' * (2*n-1)] | def hollow_triangle(n):
return [(f'#{"_" * (2*i-1)}#' if i else '#').center(2*n-1, '_') for i in range(n-1)] + ['#' * (2*n-1)] | train | APPS_structured |
Witua is a little student from the University of Lviv. He enjoys studying math. Witua knows a lot of famous mathematicians like Eratosthenes, Pythagoras, Fermat, Diophantus, Furko, Gauss and so on. However, his favorite one is Euler. The only thing Witua likes more than Euler is Euler’s totient function φ. He is exploring the nature of this function. One of the steps of his work is finding φ(i)/i for all 2≤i≤N. He doesn’t need to know every such value, but Witua wonders for what value i, is φ(i)/i the maximum he can get? Help little student to find such i that φ(i)/i is maximum among all the 2≤i≤N.
-----Input-----
The first line contains single integer T - the number of test cases. Each of the next T lines contains a single integer N.
-----Output-----
For every test case output i such that φ(i)/i is maximum among all i (2≤i≤N) in a separate line.
-----Constrains-----
T (1≤T≤500 )
N(2≤N≤10^18)
-----Example-----
Input:
3
2
3
4
Output:
2
3
3
Explanationφ(2)/2=1/2
φ(3)/3=2/3
φ(4)/4=2/4 | # cook your dish here
def modular_pow(base, exponent, modulus):
result = 1
while exponent > 0:
if(exponent %2 == 1):
result = (result * base) % modulus
exponent = exponent//2
base = (base * base)%modulus
return result
def passesMillerRabinTest(n, a):
s = 0
d = n-1
while(d%2 == 0):
s += 1
d >>= 1
x = modular_pow(a, d, n)
if(x == 1 or x == n-1):
return True
for ss in range(s - 1):
x = (x*x)%n
if(x == 1):
return False
if(x == n-1):
return True
return False
primeList = (2, 3,5,7,11,13,17,19, 23,29, 31,37)
def isPrime(n):
for p in primeList:
if n%p == 0:
return n == p
for p in primeList:
if passesMillerRabinTest(n, p) == False:
return False
return True
t = int(input())
for tt in range(t):
n = int(input())
if(n == 2):
print(2)
continue
if n%2 == 0:
n -= 1
while True:
if(isPrime(n)):
print(n)
break
n -= 2
| # cook your dish here
def modular_pow(base, exponent, modulus):
result = 1
while exponent > 0:
if(exponent %2 == 1):
result = (result * base) % modulus
exponent = exponent//2
base = (base * base)%modulus
return result
def passesMillerRabinTest(n, a):
s = 0
d = n-1
while(d%2 == 0):
s += 1
d >>= 1
x = modular_pow(a, d, n)
if(x == 1 or x == n-1):
return True
for ss in range(s - 1):
x = (x*x)%n
if(x == 1):
return False
if(x == n-1):
return True
return False
primeList = (2, 3,5,7,11,13,17,19, 23,29, 31,37)
def isPrime(n):
for p in primeList:
if n%p == 0:
return n == p
for p in primeList:
if passesMillerRabinTest(n, p) == False:
return False
return True
t = int(input())
for tt in range(t):
n = int(input())
if(n == 2):
print(2)
continue
if n%2 == 0:
n -= 1
while True:
if(isPrime(n)):
print(n)
break
n -= 2
| train | APPS_structured |
Given an array (arr) as an argument complete the function `countSmileys` that should return the total number of smiling faces.
Rules for a smiling face:
- Each smiley face must contain a valid pair of eyes. Eyes can be marked as `:` or `;`
- A smiley face can have a nose but it does not have to. Valid characters for a nose are `-` or `~`
- Every smiling face must have a smiling mouth that should be marked with either `)` or `D`
No additional characters are allowed except for those mentioned.
**Valid smiley face examples:** `:) :D ;-D :~)`
**Invalid smiley faces:** `;( :> :} :]`
## Example
```
countSmileys([':)', ';(', ';}', ':-D']); // should return 2;
countSmileys([';D', ':-(', ':-)', ';~)']); // should return 3;
countSmileys([';]', ':[', ';*', ':$', ';-D']); // should return 1;
```
## Note
In case of an empty array return 0. You will not be tested with invalid input (input will always be an array). Order of the face (eyes, nose, mouth) elements will always be the same. | def count_smileys(arr):
eyes = [":", ";"]
noses = ["", "-", "~"]
mouths = [")", "D"]
count = 0
for eye in eyes:
for nose in noses:
for mouth in mouths:
face = eye + nose + mouth
count += arr.count(face)
return count | def count_smileys(arr):
eyes = [":", ";"]
noses = ["", "-", "~"]
mouths = [")", "D"]
count = 0
for eye in eyes:
for nose in noses:
for mouth in mouths:
face = eye + nose + mouth
count += arr.count(face)
return count | train | APPS_structured |
Chef is playing a game with two of his friends. In this game, each player chooses an integer between $1$ and $P$ inclusive. Let's denote the integers chosen by Chef, friend 1 and friend 2 by $i$, $j$ and $k$ respectively; then, Chef's score is
(((Nmodi)modj)modk)modN.(((Nmodi)modj)modk)modN.(((N\,\mathrm{mod}\,i)\,\mathrm{mod}\,j)\,\mathrm{mod}\,k)\,\mathrm{mod}\,N\,.
Chef wants to obtain the maximum possible score. Let's denote this maximum score by $M$. Find the number of ways to choose the triple $(i,j,k)$ so that Chef's score is equal to $M$.
-----Input-----
- The first line of the input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows.
- The first and only line of each test case contains two space-separated integers $N$ and $P$.
-----Output-----
For each test case, print a single line containing one integer — the number of ways to obtain the maximum score.
-----Constraints-----
- $1 \le T \le 10^6$
- $1 \le N \le P \le 10^6$
-----Subtasks-----
Subtask #1 (10 points):
- $1 \le T \le 100$
- $1 \le N \le P \le 100$
Subtask #2 (90 points): original constraints
-----Example Input-----
2
4 4
3 4
-----Example Output-----
9
13
-----Explanation-----
Example case 1: Chef's maximum possible score is $M = 1$. All possible values of $(i, j, k)$ such that the score is $1$ are
$(3, 2, 2)$,
$(3, 2, 3)$,
$(3, 2, 4)$,
$(3, 3, 2)$,
$(3, 3, 3)$,
$(3, 3, 4)$,
$(3, 4, 2)$,
$(3, 4, 3)$,
$(3, 4, 4)$. | # -*- coding: utf-8 -*-
"""
@author: anishukla
"""
T = int(input())
for i in range(T):
N, P = map(int,input().split())
req = (N//2)+1
if(N==1 or N==2):
print(P**3)
else:
req=N%req
b=(P-req)**2
c=(P-N)*(P-req)
a=(P-N)*(P-N)
print(a+b+c) | # -*- coding: utf-8 -*-
"""
@author: anishukla
"""
T = int(input())
for i in range(T):
N, P = map(int,input().split())
req = (N//2)+1
if(N==1 or N==2):
print(P**3)
else:
req=N%req
b=(P-req)**2
c=(P-N)*(P-req)
a=(P-N)*(P-N)
print(a+b+c) | train | APPS_structured |
The integer ```64``` is the first integer that has all of its digits even and furthermore, is a perfect square.
The second one is ```400``` and the third one ```484```.
Give the numbers of this sequence that are in the range ```[a,b] ```(both values inclusive)
Examples:
``` python
even_digit_squares(100, 1000) == [400, 484] # the output should be sorted.
even_digit_squares(1000, 4000) == []
```
Features of the random tests for ```even_digit_squares(a, b)```
```
number of Tests = 167
maximum value for a = 1e10
maximum value for b = 1e12
```
You do not have to check the entries, ```a``` and ```b``` always positive integers and ```a < b```
Happy coding!! | def is_even(x):
return all(int(i) % 2 == 0 for i in str(x))
def even_digit_squares(a, b):
first = int(a ** (1 / 2)) + 1
last = int(b ** (1 / 2)) + 1
return sorted([x * x for x in range(first, last) if is_even(x * x)]) | def is_even(x):
return all(int(i) % 2 == 0 for i in str(x))
def even_digit_squares(a, b):
first = int(a ** (1 / 2)) + 1
last = int(b ** (1 / 2)) + 1
return sorted([x * x for x in range(first, last) if is_even(x * x)]) | train | APPS_structured |
Once Vasya and Petya assembled a figure of m cubes, each of them is associated with a number between 0 and m - 1 (inclusive, each number appeared exactly once). Let's consider a coordinate system such that the OX is the ground, and the OY is directed upwards. Each cube is associated with the coordinates of its lower left corner, these coordinates are integers for each cube.
The figure turned out to be stable. This means that for any cube that is not on the ground, there is at least one cube under it such that those two cubes touch by a side or a corner. More formally, this means that for the cube with coordinates (x, y) either y = 0, or there is a cube with coordinates (x - 1, y - 1), (x, y - 1) or (x + 1, y - 1).
Now the boys want to disassemble the figure and put all the cubes in a row. In one step the cube is removed from the figure and being put to the right of the blocks that have already been laid. The guys remove the cubes in such order that the figure remains stable. To make the process more interesting, the guys decided to play the following game. The guys take out the cubes from the figure in turns. It is easy to see that after the figure is disassembled, the integers written on the cubes form a number, written in the m-ary positional numerical system (possibly, with a leading zero). Vasya wants the resulting number to be maximum possible, and Petya, on the contrary, tries to make it as small as possible. Vasya starts the game.
Your task is to determine what number is formed after the figure is disassembled, if the boys play optimally. Determine the remainder of the answer modulo 10^9 + 9.
-----Input-----
The first line contains number m (2 ≤ m ≤ 10^5).
The following m lines contain the coordinates of the cubes x_{i}, y_{i} ( - 10^9 ≤ x_{i} ≤ 10^9, 0 ≤ y_{i} ≤ 10^9) in ascending order of numbers written on them. It is guaranteed that the original figure is stable.
No two cubes occupy the same place.
-----Output-----
In the only line print the answer to the problem.
-----Examples-----
Input
3
2 1
1 0
0 1
Output
19
Input
5
0 0
0 1
0 2
0 3
0 4
Output
2930 | import heapq
def coor_neighbor(coor, dxs, dys):
x, y = coor
for dx in dxs:
for dy in dys:
yield x + dx, y + dy
def coor_bottoms(coor):
return coor_neighbor(coor, (-1, 0, 1), (-1, ))
def coor_tops(coor):
return coor_neighbor(coor, (-1, 0, 1), (1, ))
def coor_sibs(coor):
return coor_neighbor(coor, (-2, -1, 1, 2), (0, ))
class Figure:
def __init__(self, coors):
self._coors = dict()
self._stables_min = []
self._stables_max = []
self._pushed = set()
self._dropped = set()
cubes = dict()
self._bots = dict()
self._tops = dict()
for idx, coor in enumerate(coors):
cubes[coor] = idx
self._coors[idx] = coor
self._bots[idx] = set()
self._tops[idx] = set()
coor_set = set(coors)
for idx, coor in enumerate(coors):
for bottom in coor_bottoms(coor):
if bottom in coor_set:
self._bots[idx].add(cubes[bottom])
for top in coor_tops(coor):
if top in coor_set:
self._tops[idx].add(cubes[top])
for idx in self._coors:
if self.isdroppable(idx):
self.push(idx)
def sibs(self, idx):
for top_idx in self._tops[idx]:
for sib_idx in self._bots[top_idx]:
if sib_idx not in self._dropped:
yield sib_idx
def bottom_count(self, idx):
return len(self._bots[idx])
def isdroppable(self, idx):
return all(len(self._bots[top_idx]) > 1 for top_idx in self._tops[idx])
def push(self, idx):
if idx not in self._pushed:
heapq.heappush(self._stables_min, idx)
heapq.heappush(self._stables_max, -idx)
self._pushed.add(idx)
def unpush(self, idx):
if idx in self._pushed:
self._pushed.remove(idx)
def drop(self, idx):
if idx not in self._pushed:
return False
self._pushed.remove(idx)
self._dropped.add(idx)
for bot_idx in self._bots[idx]:
self._tops[bot_idx].remove(idx)
for top_idx in self._tops[idx]:
self._bots[top_idx].remove(idx)
coor = self._coors[idx]
for bot_idx in self._bots[idx]:
if self.isdroppable(bot_idx):
self.push(bot_idx)
for sib_idx in self.sibs(idx):
if not self.isdroppable(sib_idx):
self.unpush(sib_idx)
return True
def drop_min(self):
while True:
if not self._stables_min:
return None
min_idx = heapq.heappop(self._stables_min)
if self.drop(min_idx):
return min_idx
def drop_max(self):
while True:
if not self._stables_max:
return None
max_idx = - heapq.heappop(self._stables_max)
if self.drop(max_idx):
return max_idx
def __bool__(self):
return len(self._coors) != len(self._dropped)
def input_tuple():
return tuple(map(int, input().split()))
def result_add(result, base, num):
return (result * base + num) % (10 ** 9 + 9)
N = int(input())
coors = [input_tuple() for _ in range(N)]
figure = Figure(coors)
result = 0
while True:
if not figure:
break
result = result_add(result, N, figure.drop_max())
if not figure:
break
result = result_add(result, N, figure.drop_min())
print(result)
| import heapq
def coor_neighbor(coor, dxs, dys):
x, y = coor
for dx in dxs:
for dy in dys:
yield x + dx, y + dy
def coor_bottoms(coor):
return coor_neighbor(coor, (-1, 0, 1), (-1, ))
def coor_tops(coor):
return coor_neighbor(coor, (-1, 0, 1), (1, ))
def coor_sibs(coor):
return coor_neighbor(coor, (-2, -1, 1, 2), (0, ))
class Figure:
def __init__(self, coors):
self._coors = dict()
self._stables_min = []
self._stables_max = []
self._pushed = set()
self._dropped = set()
cubes = dict()
self._bots = dict()
self._tops = dict()
for idx, coor in enumerate(coors):
cubes[coor] = idx
self._coors[idx] = coor
self._bots[idx] = set()
self._tops[idx] = set()
coor_set = set(coors)
for idx, coor in enumerate(coors):
for bottom in coor_bottoms(coor):
if bottom in coor_set:
self._bots[idx].add(cubes[bottom])
for top in coor_tops(coor):
if top in coor_set:
self._tops[idx].add(cubes[top])
for idx in self._coors:
if self.isdroppable(idx):
self.push(idx)
def sibs(self, idx):
for top_idx in self._tops[idx]:
for sib_idx in self._bots[top_idx]:
if sib_idx not in self._dropped:
yield sib_idx
def bottom_count(self, idx):
return len(self._bots[idx])
def isdroppable(self, idx):
return all(len(self._bots[top_idx]) > 1 for top_idx in self._tops[idx])
def push(self, idx):
if idx not in self._pushed:
heapq.heappush(self._stables_min, idx)
heapq.heappush(self._stables_max, -idx)
self._pushed.add(idx)
def unpush(self, idx):
if idx in self._pushed:
self._pushed.remove(idx)
def drop(self, idx):
if idx not in self._pushed:
return False
self._pushed.remove(idx)
self._dropped.add(idx)
for bot_idx in self._bots[idx]:
self._tops[bot_idx].remove(idx)
for top_idx in self._tops[idx]:
self._bots[top_idx].remove(idx)
coor = self._coors[idx]
for bot_idx in self._bots[idx]:
if self.isdroppable(bot_idx):
self.push(bot_idx)
for sib_idx in self.sibs(idx):
if not self.isdroppable(sib_idx):
self.unpush(sib_idx)
return True
def drop_min(self):
while True:
if not self._stables_min:
return None
min_idx = heapq.heappop(self._stables_min)
if self.drop(min_idx):
return min_idx
def drop_max(self):
while True:
if not self._stables_max:
return None
max_idx = - heapq.heappop(self._stables_max)
if self.drop(max_idx):
return max_idx
def __bool__(self):
return len(self._coors) != len(self._dropped)
def input_tuple():
return tuple(map(int, input().split()))
def result_add(result, base, num):
return (result * base + num) % (10 ** 9 + 9)
N = int(input())
coors = [input_tuple() for _ in range(N)]
figure = Figure(coors)
result = 0
while True:
if not figure:
break
result = result_add(result, N, figure.drop_max())
if not figure:
break
result = result_add(result, N, figure.drop_min())
print(result)
| train | APPS_structured |
My grandfather always predicted how old people would get, and right before he passed away he revealed his secret!
In honor of my grandfather's memory we will write a function using his formula!
* Take a list of ages when each of your great-grandparent died.
* Multiply each number by itself.
* Add them all together.
* Take the square root of the result.
* Divide by two.
## Example
```R
predict_age(65, 60, 75, 55, 60, 63, 64, 45) == 86
```
```python
predict_age(65, 60, 75, 55, 60, 63, 64, 45) == 86
```
Note: the result should be rounded down to the nearest integer.
Some random tests might fail due to a bug in the JavaScript implementation. Simply resubmit if that happens to you. | def predict_age(age_1, age_2, age_3, age_4, age_5, age_6, age_7, age_8):
starting_list = [age_1, age_2, age_3, age_4, age_5, age_6, age_7, age_8]
each_muliply_itself = []
for age in starting_list:
each_muliply_itself.append(age*age)
total_multiplied_ages = sum(each_muliply_itself)
square_root_result = total_multiplied_ages**(.5)
result = square_root_result/2
return int(result) | def predict_age(age_1, age_2, age_3, age_4, age_5, age_6, age_7, age_8):
starting_list = [age_1, age_2, age_3, age_4, age_5, age_6, age_7, age_8]
each_muliply_itself = []
for age in starting_list:
each_muliply_itself.append(age*age)
total_multiplied_ages = sum(each_muliply_itself)
square_root_result = total_multiplied_ages**(.5)
result = square_root_result/2
return int(result) | train | APPS_structured |
A special type of prime is generated by the formula `p = 2^m * 3^n + 1` where `m` and `n` can be any non-negative integer.
The first `5` of these primes are `2, 3, 5, 7, 13`, and are generated as follows:
```Haskell
2 = 2^0 * 3^0 + 1
3 = 2^1 * 3^0 + 1
5 = 2^2 * 3^0 + 1
7 = 2^1 * 3^1 + 1
13 = 2^2 * 3^1 + 1
..and so on
```
You will be given a range and your task is to return the number of primes that have this property. For example, `solve(0,15) = 5`, because there are only `5` such primes `>= 0 and < 15`; they are `2,3,5,7,13`. The upper limit of the tests will not exceed `1,500,000`.
More examples in the test cases.
Good luck!
If you like Prime Katas, you will enjoy this Kata: [Simple Prime Streaming](https://www.codewars.com/kata/5a908da30025e995880000e3) | M=[2,3,5,7,13,17,19,37,73,97,109,163,193,257,433,487,577,769,1153,1297,1459,2593,2917,3457,3889,10369,12289,17497,18433,39367,52489,65537,139969,147457,209953,331777,472393,629857,746497,786433,839809,995329,1179649,1492993]
solve=lambda L,R:sum(L<=V<R for V in M) | M=[2,3,5,7,13,17,19,37,73,97,109,163,193,257,433,487,577,769,1153,1297,1459,2593,2917,3457,3889,10369,12289,17497,18433,39367,52489,65537,139969,147457,209953,331777,472393,629857,746497,786433,839809,995329,1179649,1492993]
solve=lambda L,R:sum(L<=V<R for V in M) | train | APPS_structured |
The Little Elephant loves lucky strings. Everybody knows that the lucky string is a string of digits that contains only the lucky digits 4 and 7. For example, strings "47", "744", "4" are lucky while "5", "17", "467" are not.
The Little Elephant has the strings A and B of digits. These strings are of equal lengths, that is |A| = |B|. He wants to get some lucky string from them. For this he performs the following operations. At first he arbitrary reorders digits of A. Then he arbitrary reorders digits of B. After that he creates the string C such that its i-th digit is the maximum between the i-th digit of A and the i-th digit of B. In other words, C[i] = max{A[i], B[i]} for i from 1 to |A|. After that he removes from C all non-lucky digits saving the order of the remaining (lucky) digits. So C now becomes a lucky string. For example, if after reordering A = "754" and B = "873", then C is at first "874" and then it becomes "74".
The Little Elephant wants the resulting string to be as lucky as possible. The formal definition of this is that the resulting string should be the lexicographically greatest possible string among all the strings that can be obtained from the given strings A and B by the described process.
Notes
- |A| denotes the length of the string A.
- A[i] denotes the i-th digit of the string A. Here we numerate the digits starting from 1. So 1 ≤ i ≤ |A|.
- The string A is called lexicographically greater than the string B if either there exists some index i such that A[i] > B[i] and for each j < i we have A[j] = B[j], or B is a proper prefix of A, that is, |A| > |B| and first |B| digits of A coincide with the corresponding digits of B.
-----Input-----
The first line of the input contains a single integer T, the number of test cases. T test cases follow. Each test case consists of two lines. The first line contains the string A. The second line contains the string B.
-----Output-----
For each test case output a single line containing the answer for the corresponding test case. Note, that the answer can be an empty string. In this case you should print an empty line for the corresponding test case.
-----Constraints-----
1 ≤ T ≤ 10000
1 ≤ |A| ≤ 20000
|A| = |B|
Each character of A and B is a digit.
Sum of |A| across all the tests in the input does not exceed 200000.
-----Example-----
Input:
4
4
7
435
479
7
8
1675475
9756417
Output:
7
74
777744
-----Explanation-----
Case 1. In this case the only possible string C we can get is "7" and it is the lucky string.
Case 2. If we reorder A and B as A = "543" and B = "749" the string C will be at first "749" and then becomes "74". It can be shown that this is the lexicographically greatest string for the given A and B.
Case 3. In this case the only possible string C we can get is "8" and it becomes and empty string after removing of non-lucky digits.
Case 4. If we reorder A and B as A = "7765541" and B = "5697714" the string C will be at first "7797744" and then becomes "777744". Note that we can construct any lexicographically greater string for the given A and B since we have only four "sevens" and two "fours" among digits of both strings A and B as well the constructed string "777744". | tests=int(input())
for t in range(tests):
a=input()
b=input()
aSev=a.count('7')
aLesS=a.count('5')+a.count('6')
aFor=a.count('4')
aLess=a.count('3')+a.count('2')+a.count('1')+a.count('0')
bSev=b.count('7')
bLesS=b.count('5')+b.count('6')
bFor=b.count('4')
bLess=b.count('3')+b.count('2')+b.count('1')+b.count('0')
fin7=0
fin4=0
if aSev<=bLesS:
fin7+=aSev
bLesS-=aSev
aSev=0
else:
fin7+=bLesS
aSev-=bLesS
bLesS=0
if aSev<=bLess:
fin7+=aSev
bLess-=aSev
aSev=0
else:
fin7+=bLess
aSev-=bLess
bLess=0
if aSev<=bFor:
fin7+=aSev
bFor-=aSev
aSev=0
else:
fin7+=bFor
aSev-=bFor
bFor=0
if bSev<=aLesS:
fin7+=bSev
aLesS-=bSev
bSev=0
else:
fin7+=aLesS
bSev-=aLesS
aLesS=0
if bSev<=aLess:
fin7+=bSev
aLess-=bSev
bSev=0
else:
fin7+=aLess
bSev-=aLess
aLess=0
if bSev<=aFor:
fin7+=bSev
aFor-=bSev
aSev=0
else:
fin7+=aFor
bSev-=aFor
aFor=0
fin7+=min(aSev,bSev)
if aFor<=bLess:
fin4+=aFor
bLess-=aFor
aFor=0
else:
fin4+=bLess
aFor-=bLess
bLess=0
if bFor<=aLess:
fin4+=bFor
aLess-=bFor
bFor=0
else:
fin4+=aLess
bFor-=aLess
aLess=0
fin4+=min(aFor,bFor)
print('7'*fin7+'4'*fin4)
| tests=int(input())
for t in range(tests):
a=input()
b=input()
aSev=a.count('7')
aLesS=a.count('5')+a.count('6')
aFor=a.count('4')
aLess=a.count('3')+a.count('2')+a.count('1')+a.count('0')
bSev=b.count('7')
bLesS=b.count('5')+b.count('6')
bFor=b.count('4')
bLess=b.count('3')+b.count('2')+b.count('1')+b.count('0')
fin7=0
fin4=0
if aSev<=bLesS:
fin7+=aSev
bLesS-=aSev
aSev=0
else:
fin7+=bLesS
aSev-=bLesS
bLesS=0
if aSev<=bLess:
fin7+=aSev
bLess-=aSev
aSev=0
else:
fin7+=bLess
aSev-=bLess
bLess=0
if aSev<=bFor:
fin7+=aSev
bFor-=aSev
aSev=0
else:
fin7+=bFor
aSev-=bFor
bFor=0
if bSev<=aLesS:
fin7+=bSev
aLesS-=bSev
bSev=0
else:
fin7+=aLesS
bSev-=aLesS
aLesS=0
if bSev<=aLess:
fin7+=bSev
aLess-=bSev
bSev=0
else:
fin7+=aLess
bSev-=aLess
aLess=0
if bSev<=aFor:
fin7+=bSev
aFor-=bSev
aSev=0
else:
fin7+=aFor
bSev-=aFor
aFor=0
fin7+=min(aSev,bSev)
if aFor<=bLess:
fin4+=aFor
bLess-=aFor
aFor=0
else:
fin4+=bLess
aFor-=bLess
bLess=0
if bFor<=aLess:
fin4+=bFor
aLess-=bFor
bFor=0
else:
fin4+=aLess
bFor-=aLess
aLess=0
fin4+=min(aFor,bFor)
print('7'*fin7+'4'*fin4)
| train | APPS_structured |
A family of kookaburras are in my backyard.
I can't see them all, but I can hear them!
# How many kookaburras are there?
## Hint
The trick to counting kookaburras is to listen carefully
* The males go ```HaHaHa```...
* The females go ```hahaha```...
* And they always alternate male/female
^ Kata Note : No validation is necessary; only valid input will be passed :-) | def kooka_counter(laughing):
return laughing.count("Haha") + laughing.count("haHa") + bool(laughing) | def kooka_counter(laughing):
return laughing.count("Haha") + laughing.count("haHa") + bool(laughing) | train | APPS_structured |
Given the number pledged for a year, current value and name of the month, return string that gives information about the challenge status:
- ahead of schedule
- behind schedule
- on track
- challenge is completed
Examples:
`(12, 1, "February")` - should return `"You are on track."`
`(12, 1, "March")` - should return `"You are 1 behind schedule."`
`(12, 5, "March")` - should return `"You are 3 ahead of schedule."`
`(12, 12, "September")` - should return `"Challenge is completed."`
Details:
- you do not need to do any prechecks (input will always be a natural number and correct name of the month)
- months should be as even as possible (i.e. for 100 items: January, February, March and April - 9, other months 8)
- count only the item for completed months (i.e. for March check the values from January and February) and it means that for January you should always return `"You are on track."`. | from calendar import month_name
months = {m:i for i,m in enumerate(month_name)}
def check_challenge(pledged, current, month):
if pledged == current: return "Challenge is completed."
q, r = divmod(pledged, 12)
m = months[month] - 1
val = current - m*q - min(m, r)
if m and val:
return f"You are {-val} behind schedule." if val < 0 else f"You are {val} ahead of schedule!"
return "You are on track." | from calendar import month_name
months = {m:i for i,m in enumerate(month_name)}
def check_challenge(pledged, current, month):
if pledged == current: return "Challenge is completed."
q, r = divmod(pledged, 12)
m = months[month] - 1
val = current - m*q - min(m, r)
if m and val:
return f"You are {-val} behind schedule." if val < 0 else f"You are {val} ahead of schedule!"
return "You are on track." | train | APPS_structured |
Given a binary string s and an integer k.
Return True if every binary code of length k is a substring of s. Otherwise, return False.
Example 1:
Input: s = "00110110", k = 2
Output: true
Explanation: The binary codes of length 2 are "00", "01", "10" and "11". They can be all found as substrings at indicies 0, 1, 3 and 2 respectively.
Example 2:
Input: s = "00110", k = 2
Output: true
Example 3:
Input: s = "0110", k = 1
Output: true
Explanation: The binary codes of length 1 are "0" and "1", it is clear that both exist as a substring.
Example 4:
Input: s = "0110", k = 2
Output: false
Explanation: The binary code "00" is of length 2 and doesn't exist in the array.
Example 5:
Input: s = "0000000001011100", k = 4
Output: false
Constraints:
1 <= s.length <= 5 * 10^5
s consists of 0's and 1's only.
1 <= k <= 20 | class Solution:
def hasAllCodes(self, s: str, k: int) -> bool:
codes = {format(i, f'0{k}b'): False for i in range(2**k)}
for i in range(len(s) - k + 1):
ss = s[i:i + k]
if ss in codes:
codes[ss] = True
return all(codes.values()) | class Solution:
def hasAllCodes(self, s: str, k: int) -> bool:
codes = {format(i, f'0{k}b'): False for i in range(2**k)}
for i in range(len(s) - k + 1):
ss = s[i:i + k]
if ss in codes:
codes[ss] = True
return all(codes.values()) | train | APPS_structured |
Alice is a very brilliant student. He considers '4' and '7' as Magic numbers. The numbers containing only magic numbers are also magical. Given a magic number N ,he wants to know what could be the next magical number greater than the given number.
-----Input-----
First line of input contains number of test cases T. For each test case, there is exits only one line containing a magic number N.
-----Output-----
For each test case, output a single line containing the next greater magical number.
-----Constraints-----
1<=T<=1000
4<= N<=10^100
-----Example-----
Input:
2
4
47
Output:
7
74 | #!/usr/bin/env python
def process(N):
if not '4' in N:
return '4' * (len(N) + 1)
i = N.rindex('4')
return N[:i] + '7' + '4' * len(N[i+1:])
def main():
T = int(input().strip())
for t in range(T):
N = input().strip()
print(process(N))
main()
| #!/usr/bin/env python
def process(N):
if not '4' in N:
return '4' * (len(N) + 1)
i = N.rindex('4')
return N[:i] + '7' + '4' * len(N[i+1:])
def main():
T = int(input().strip())
for t in range(T):
N = input().strip()
print(process(N))
main()
| train | APPS_structured |
## Task:
You have to write a function **pattern** which returns the following Pattern(See Examples) upto (2n-1) rows, where n is parameter.
### Rules/Note:
* If the Argument is 0 or a Negative Integer then it should return "" i.e. empty string.
* All the lines in the pattern have same length i.e equal to the number of characters in the longest line.
* Range of n is (-∞,100]
## Examples:
pattern(5):
1
121
12321
1234321
123454321
1234321
12321
121
1
pattern(10):
1
121
12321
1234321
123454321
12345654321
1234567654321
123456787654321
12345678987654321
1234567890987654321
12345678987654321
123456787654321
1234567654321
12345654321
123454321
1234321
12321
121
1
pattern(15):
1
121
12321
1234321
123454321
12345654321
1234567654321
123456787654321
12345678987654321
1234567890987654321
123456789010987654321
12345678901210987654321
1234567890123210987654321
123456789012343210987654321
12345678901234543210987654321
123456789012343210987654321
1234567890123210987654321
12345678901210987654321
123456789010987654321
1234567890987654321
12345678987654321
123456787654321
1234567654321
12345654321
123454321
1234321
12321
121
1
pattern(20):
1
121
12321
1234321
123454321
12345654321
1234567654321
123456787654321
12345678987654321
1234567890987654321
123456789010987654321
12345678901210987654321
1234567890123210987654321
123456789012343210987654321
12345678901234543210987654321
1234567890123456543210987654321
123456789012345676543210987654321
12345678901234567876543210987654321
1234567890123456789876543210987654321
123456789012345678909876543210987654321
1234567890123456789876543210987654321
12345678901234567876543210987654321
123456789012345676543210987654321
1234567890123456543210987654321
12345678901234543210987654321
123456789012343210987654321
1234567890123210987654321
12345678901210987654321
123456789010987654321
1234567890987654321
12345678987654321
123456787654321
1234567654321
12345654321
123454321
1234321
12321
121
1 | def pattern(n):
lines = []
for c in range(1,n+1):
s = (' ' * (n-c)) + ''.join([str(s)[-1] for s in range(1,c+1)])
lines += [s + s[::-1][1:]]
lines += lines[::-1][1:]
return '\n'.join(str(x) for x in lines)
| def pattern(n):
lines = []
for c in range(1,n+1):
s = (' ' * (n-c)) + ''.join([str(s)[-1] for s in range(1,c+1)])
lines += [s + s[::-1][1:]]
lines += lines[::-1][1:]
return '\n'.join(str(x) for x in lines)
| train | APPS_structured |
The Head Chef is receiving a lot of orders for cooking the best of the problems lately. For this, he organized an hiring event to hire some talented Chefs. He gave the following problem to test the skills of the participating Chefs. Can you solve this problem and be eligible for getting hired by Head Chef.
A non-negative number n is said to be magical if it satisfies the following property. Let S denote the multi-set of numbers corresponding to the non-empty subsequences of the digits of the number n in decimal representation. Please note that the numbers in the set S can have leading zeros. Let us take an element s of the multi-set S, prod(s) denotes the product of all the digits of number s in decimal representation.
The number n will be called magical if sum of prod(s) for all elements s in S, is even.
For example, consider a number 246, its all possible non-empty subsequence will be S = {2, 4, 6, 24, 46, 26, 246}. Products of digits of these subsequences will be {prod(2) = 2, prod(4) = 4, prod(6) = 6, prod(24) = 8, prod(46) = 24, prod(26) = 12, prod(246) = 48, i.e. {2, 4, 6, 8, 24, 12, 48}. Sum of all of these is 104, which is even. Hence 246 is a magical number.
Please note that multi-set S can contain repeated elements, e.g. if number is 55, then S = {5, 5, 55}. Products of digits of these subsequences will be {prod(5) = 5, prod(5) = 5, prod(55) = 25}, i.e. {5, 5, 25}. Sum of all of these is 35 which is odd. Hence 55 is not a
magical number.
Consider a number 204, then S = {2, 0, 4, 20, 04, 24, 204}. Products of digits of these subsequences will be {2, 0, 4, 0, 0, 8, 0}. Sum of all these elements will be 14 which is even. So 204 is a magical number.
The task was to simply find the Kth magical number.
-----Input-----
- First line of the input contains an integer T denoting the number of test cases.
- Each of the next T lines contains a single integer K.
-----Output-----
For each test case, print a single integer corresponding to the Kth magical number.
-----Constraints-----
- 1 ≤ T ≤ 105
- 1 ≤ K ≤ 1012.
-----Subtasks-----
Subtask #1 : (20 points)
- 1 ≤ T ≤ 100
- 1 ≤ K ≤ 104.
Subtask 2 : (80 points) Original Constraints
-----Example-----
Input:
2
2
5
Output:
2
8
-----Explanation-----
Example case 1.
2 is the 2nd magical number, since it satisfies the property of the magical number. The first magical number will be of course 0. | import math
def answer(n):
n-=1
if n>0:
a=int(math.log(n,5))
else:
a=0
total=0
while a!=0:
x=math.pow(5,a)
g=n//x
n=int(n%x)
total+=2*math.pow(10,a)*g
if n>0:
a=int(math.log(n,5))
else:
a=0
total+=2*(n)
total=int(total)
return total
T=int(input(''))
while T:
T-=1
n=int(input(''))
print(answer(n))
| import math
def answer(n):
n-=1
if n>0:
a=int(math.log(n,5))
else:
a=0
total=0
while a!=0:
x=math.pow(5,a)
g=n//x
n=int(n%x)
total+=2*math.pow(10,a)*g
if n>0:
a=int(math.log(n,5))
else:
a=0
total+=2*(n)
total=int(total)
return total
T=int(input(''))
while T:
T-=1
n=int(input(''))
print(answer(n))
| train | APPS_structured |
As a treat, I'll let you read part of the script from a classic 'I'm Alan Partridge episode:
```
Lynn: Alan, there’s that teacher chap.
Alan: Michael, if he hits me, will you hit him first?
Michael: No, he’s a customer. I cannot hit customers. I’ve been told. I’ll go and get some stock.
Alan: Yeah, chicken stock.
Phil: Hello Alan.
Alan: Lynn, hand me an apple pie. And remove yourself from the theatre of conflict.
Lynn: What do you mean?
Alan: Go and stand by the yakults. The temperature inside this apple turnover is 1,000 degrees. If I squeeze it, a jet of molten Bramley apple is going to squirt out. Could go your way, could go mine. Either way, one of us is going down.
```
Alan is known for referring to the temperature of the apple turnover as 'Hotter than the sun!'. According to space.com the temperature of the sun's corona is 2,000,000 degrees C, but we will ignore the science for now.
Your job is simple, if (x) squared is more than 1000, return 'It's hotter than the sun!!', else, return 'Help yourself to a honeycomb Yorkie for the glovebox.'.
X will be either a number or a string. Both are valid.
Other katas in this series:
Alan Partridge I - Partridge Watch
Alan Partridge III - London | def apple(x):
intx = int(x)
if intx ** 2 > 1000:
return "It's hotter than the sun!!"
else:
return "Help yourself to a honeycomb Yorkie for the glovebox." | def apple(x):
intx = int(x)
if intx ** 2 > 1000:
return "It's hotter than the sun!!"
else:
return "Help yourself to a honeycomb Yorkie for the glovebox." | train | APPS_structured |
You are climbing a stair case. It takes n steps to reach to the top.
Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?
Note: Given n will be a positive integer.
Example 1:
Input: 2
Output: 2
Explanation: There are two ways to climb to the top.
1. 1 step + 1 step
2. 2 steps
Example 2:
Input: 3
Output: 3
Explanation: There are three ways to climb to the top.
1. 1 step + 1 step + 1 step
2. 1 step + 2 steps
3. 2 steps + 1 step | class Solution:
def climbStairs(self, n):
"""
:type n: int
:rtype: int
"""
a = 1
b = 2
if n < 2:
return 1
for i in range(n-2):
a,b = b, a+b
return b | class Solution:
def climbStairs(self, n):
"""
:type n: int
:rtype: int
"""
a = 1
b = 2
if n < 2:
return 1
for i in range(n-2):
a,b = b, a+b
return b | train | APPS_structured |
Given an `x` and `y` find the smallest and greatest numbers **above** and **below** a given `n` that are divisible by both `x` and `y`.
### Examples
```python
greatest(2, 3, 20) => 18 # 18 is the greatest number under 20 that is divisible by both 2 and 3
smallest(2, 3, 20) => 24 # 24 is the smallest number above 20 that is divisible by both 2 and 3
greatest(5, 15, 100) => 90
smallest(5, 15, 100) => 105
greatest(123, 456, 789) => 0 # there are no numbers under 789 that are divisible by both 123 and 456
smallest(123, 456, 789) => 18696
```
**Notes:**
1. you should never return `n` even if it is divisible by `x` and `y` always the number above or below it
2. `greatest` should return 0 if there are no numbers under `n` that are divisible by both `x` and `y`
3. and all arguments will be valid (integers greater than 0).
### Note for Haskell users
>Please take a look at [bkaes comment](http://www.codewars.com/kata/when-greatest-is-less-than-smallest/discuss#56418f0fbf1f44834d000050) and give us your opinion | from fractions import gcd
def near(x, y, n):
lcm = x * y // gcd(x, y)
return n // lcm * lcm, lcm
def greatest(x, y, n):
result, lcm = near(x, y, n)
if result >= n:
result -= lcm
return result
def smallest(x, y, n):
result, lcm = near(x, y, n)
if result <= n:
result += lcm
return result
| from fractions import gcd
def near(x, y, n):
lcm = x * y // gcd(x, y)
return n // lcm * lcm, lcm
def greatest(x, y, n):
result, lcm = near(x, y, n)
if result >= n:
result -= lcm
return result
def smallest(x, y, n):
result, lcm = near(x, y, n)
if result <= n:
result += lcm
return result
| train | APPS_structured |
We are given S, a length n string of characters from the set {'D', 'I'}. (These letters stand for "decreasing" and "increasing".)
A valid permutation is a permutation P[0], P[1], ..., P[n] of integers {0, 1, ..., n}, such that for all i:
If S[i] == 'D', then P[i] > P[i+1], and;
If S[i] == 'I', then P[i] < P[i+1].
How many valid permutations are there? Since the answer may be large, return your answer modulo 10^9 + 7.
Example 1:
Input: "DID"
Output: 5
Explanation:
The 5 valid permutations of (0, 1, 2, 3) are:
(1, 0, 3, 2)
(2, 0, 3, 1)
(2, 1, 3, 0)
(3, 0, 2, 1)
(3, 1, 2, 0)
Note:
1 <= S.length <= 200
S consists only of characters from the set {'D', 'I'}. | class Solution:
def numPermsDISequence(self, S: str) -> int:
MOD = 10**9+7
N = len(S)
@lru_cache(None)
def dp(i,j):
if i==0:
return 1
elif S[i-1] == 'D':
return sum(dp(i-1, k) for k in range(j,i)) % MOD
else:
return sum(dp(i-1,k) for k in range(j)) % MOD
return sum(dp(N,j) for j in range(N+1)) % MOD | class Solution:
def numPermsDISequence(self, S: str) -> int:
MOD = 10**9+7
N = len(S)
@lru_cache(None)
def dp(i,j):
if i==0:
return 1
elif S[i-1] == 'D':
return sum(dp(i-1, k) for k in range(j,i)) % MOD
else:
return sum(dp(i-1,k) for k in range(j)) % MOD
return sum(dp(N,j) for j in range(N+1)) % MOD | train | APPS_structured |
Your task is to calculate ab mod 1337 where a is a positive integer and b is an extremely large positive integer given in the form of an array.
Example1:
a = 2
b = [3]
Result: 8
Example2:
a = 2
b = [1,0]
Result: 1024
Credits:Special thanks to @Stomach_ache for adding this problem and creating all test cases. | class Solution:
def superPow(self, a, b):
"""
:type a: int
:type b: List[int]
:rtype: int
"""
return pow(a, int(''.join(map(str, b))), 1337)
# from functools import reduce
# k=reduce(lambda x,y:x*10+y, b)
# print(k)
# return (a%1337)**k
| class Solution:
def superPow(self, a, b):
"""
:type a: int
:type b: List[int]
:rtype: int
"""
return pow(a, int(''.join(map(str, b))), 1337)
# from functools import reduce
# k=reduce(lambda x,y:x*10+y, b)
# print(k)
# return (a%1337)**k
| train | APPS_structured |
An even sequence has the following property: each maximal contiguous subsequence which contains only equal integers (i.e. the same integer repeated a number of times) has an even length. In particular, the empty sequence is even. A subsequence is maximal if it is not contained in a larger contiguous subsequence which contains only equal integers.
Chef was given an integer sequence $A_1, A_2, \ldots, A_N$ by his friend Mr. Z. He may perform the following operation any number of times: either delete an element of the current sequence (if it is non-empty) or insert an integer anywhere in the current sequence (possibly at the beginning or at the end).
Find the minimum number of operations needed to make the sequence even.
-----Input-----
- The first line of the input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows.
- The first line of each test case contains a single integer $N$.
- The second line contains $N$ space-separated integers $A_1, A_2, \ldots, A_N$.
-----Output-----
For each test case, print a single line containing one integer — the minimum number of operations.
-----Constraints-----
- $1 \leq T \leq 10$
- $1 \leq N \leq 2 \cdot 10^5$
- $1 \leq A_i \leq N$ for each valid $i$
- the sum of $N$ over all test cases does not exceed $2 \cdot 10^6$
-----Subtasks-----
Subtask #1 (10 points): $N \leq 18$
Subtask #2 (10 points): $A_i \leq A_{i+1}$ for each valid $i$
Subtask #3 (20 points): $N \leq 3,000$
Subtask #4 (20 points): $A_i \leq 26$ for each valid $i$
Subtask #5 (40 points): original constraints
-----Example Input-----
2
4
1 1 2 1
11
2 2 2 10 2 10 1 1 5 3 5
-----Example Output-----
2
3
-----Explanation-----
Example case 1: Here are two ways to make the sequence even using $2$ operations:
- Delete the first element $1$ and the only element $2$, resulting in a sequence $(1, 1)$, which is even.
- Delete the last element $1$ and insert $2$ at the end, resulting in a sequence $(1,1,2,2)$, which is even.
It can be proved that one operation is not enough to make the initial sequence even. | """
Code Chef :: December 2020 Lunchtime :: Even Sequence Problem Code: EVSTR
https://www.codechef.com/LTIME91B/problems/EVSTR
"""
import sys
from math import inf
def solve(i, prev, cnt, ops, A):
# Base Case
if i >= len(A):
if cnt % 2 == 0:
return ops
else:
return inf
result = inf
if A[i] == prev:
result = min(result, solve(i + 1, prev, cnt + 1, ops, A))
else:
if cnt % 2:
# If cnt is odd, we can
# (1) Fix it and add current. It will cost on op to fix.
result = min(result, solve(i + 1, A[i], 1, ops + 1, A))
# (2) Not fix it and delete current.
result = min(result, solve(i + 1, prev, cnt, ops + 1, A))
else:
# If cnt is even, we can
# (1) Delete current
result = min(result, solve(i + 1, prev, cnt, ops + 1, A))
# (2) Add current
result = min(result, solve(i + 1, A[i], 1, ops, A))
return result
def main():
"""Main program."""
sys.setrecursionlimit(pow(10, 9))
test_cases = int(sys.stdin.readline())
for _ in range(test_cases):
N = int(sys.stdin.readline())
A = [int(i) for i in sys.stdin.readline().split()]
soln = solve(0, 0, 0, 0, A)
print(soln)
def __starting_point():
main()
__starting_point() | """
Code Chef :: December 2020 Lunchtime :: Even Sequence Problem Code: EVSTR
https://www.codechef.com/LTIME91B/problems/EVSTR
"""
import sys
from math import inf
def solve(i, prev, cnt, ops, A):
# Base Case
if i >= len(A):
if cnt % 2 == 0:
return ops
else:
return inf
result = inf
if A[i] == prev:
result = min(result, solve(i + 1, prev, cnt + 1, ops, A))
else:
if cnt % 2:
# If cnt is odd, we can
# (1) Fix it and add current. It will cost on op to fix.
result = min(result, solve(i + 1, A[i], 1, ops + 1, A))
# (2) Not fix it and delete current.
result = min(result, solve(i + 1, prev, cnt, ops + 1, A))
else:
# If cnt is even, we can
# (1) Delete current
result = min(result, solve(i + 1, prev, cnt, ops + 1, A))
# (2) Add current
result = min(result, solve(i + 1, A[i], 1, ops, A))
return result
def main():
"""Main program."""
sys.setrecursionlimit(pow(10, 9))
test_cases = int(sys.stdin.readline())
for _ in range(test_cases):
N = int(sys.stdin.readline())
A = [int(i) for i in sys.stdin.readline().split()]
soln = solve(0, 0, 0, 0, A)
print(soln)
def __starting_point():
main()
__starting_point() | train | APPS_structured |
## Task
You are given three non negative integers `a`, `b` and `n`, and making an infinite sequence just like fibonacci sequence, use the following rules:
- step 1: use `ab` as the initial sequence.
- step 2: calculate the sum of the last two digits of the sequence, and append it to the end of sequence.
- repeat step 2 until you have enough digits
Your task is to complete the function which returns the `n`th digit (0-based) of the sequence.
### Notes:
- `0 <= a, b <= 9`, `0 <= n <= 10^10`
- `16` fixed testcases
- `100` random testcases, testing for correctness of solution
- `100` random testcases, testing for performance of code
- All inputs are valid.
- Pay attention to code performance.
## Examples
For `a = 7, b = 8 and n = 9` the output should be `5`, because the sequence is:
```
78 -> 7815 -> 78156 -> 7815611 -> 78156112 -> 781561123 -> 7815611235 -> ...
```
and the 9th digit of the sequence is `5`.
---
For `a = 0, b = 0 and n = 100000000` the output should be `0`, because all the digits in this sequence are `0`. | # Precompute all 2 digit suffixes into an associated prefix and repeating loop
# E.g. build until we get two repeating values:
# 98 -> [17, 8, 15, 6, 11, 2, 3, 5, 8, 13, 4, 7, 11, 2] (Note: [11, 2] is repeated)
# -> Prefix '17815611', Loop: '2358134711'
#
# Now any number ending with 98 has a predefined prefix and cycle, e.g.:
# 123 + 598 -> 123598 -> 98 -> Prefix '17815611', Loop: '2358134711'
# Hence 123 + 598 starts with '12359817815611' and then repeats '2358134711' indefinitely
# Dict[str, Tuple[str, str]]
lookup = {}
for i in range(10):
for j in range(10):
start = f'{i}{j}'
n = int(start)
s = [0, n]
seen = {}
while True:
x = s[-1]
if x < 10:
x = x + s[-2] % 10
else:
x = (x // 10) + (x % 10)
pair = (s[-1], x)
if pair not in seen:
s.append(x)
seen[pair] = len(s)
else:
# idx is the point where prefix finishes and loop starts
idx = seen[pair] - 1
prefix = s[2:idx] # Skip the leading zero and the starting value
loop = s[idx:]
lookup[start] = (''.join(map(str, prefix)), ''.join(map(str, loop)))
break
def find(a, b, n):
start = f'{a}{b}'[-2:].rjust(2, '0')
prefix, loop = lookup[start]
s = str(a) + str(b) + prefix + loop
if n < len(s):
# Digit in initial supplied digits, the sum of their last two digits or the prefix
return int(s[n])
# Digit is in the loop
m = (n - len(s)) % len(loop)
return int(loop[m])
| # Precompute all 2 digit suffixes into an associated prefix and repeating loop
# E.g. build until we get two repeating values:
# 98 -> [17, 8, 15, 6, 11, 2, 3, 5, 8, 13, 4, 7, 11, 2] (Note: [11, 2] is repeated)
# -> Prefix '17815611', Loop: '2358134711'
#
# Now any number ending with 98 has a predefined prefix and cycle, e.g.:
# 123 + 598 -> 123598 -> 98 -> Prefix '17815611', Loop: '2358134711'
# Hence 123 + 598 starts with '12359817815611' and then repeats '2358134711' indefinitely
# Dict[str, Tuple[str, str]]
lookup = {}
for i in range(10):
for j in range(10):
start = f'{i}{j}'
n = int(start)
s = [0, n]
seen = {}
while True:
x = s[-1]
if x < 10:
x = x + s[-2] % 10
else:
x = (x // 10) + (x % 10)
pair = (s[-1], x)
if pair not in seen:
s.append(x)
seen[pair] = len(s)
else:
# idx is the point where prefix finishes and loop starts
idx = seen[pair] - 1
prefix = s[2:idx] # Skip the leading zero and the starting value
loop = s[idx:]
lookup[start] = (''.join(map(str, prefix)), ''.join(map(str, loop)))
break
def find(a, b, n):
start = f'{a}{b}'[-2:].rjust(2, '0')
prefix, loop = lookup[start]
s = str(a) + str(b) + prefix + loop
if n < len(s):
# Digit in initial supplied digits, the sum of their last two digits or the prefix
return int(s[n])
# Digit is in the loop
m = (n - len(s)) % len(loop)
return int(loop[m])
| train | APPS_structured |
You're playing a game with a friend involving a bag of marbles. In the bag are ten marbles:
* 1 smooth red marble
* 4 bumpy red marbles
* 2 bumpy yellow marbles
* 1 smooth yellow marble
* 1 bumpy green marble
* 1 smooth green marble
You can see that the probability of picking a smooth red marble from the bag is `1 / 10` or `0.10` and the probability of picking a bumpy yellow marble is `2 / 10` or `0.20`.
The game works like this: your friend puts her hand in the bag, chooses a marble (without looking at it) and tells you whether it's bumpy or smooth. Then you have to guess which color it is before she pulls it out and reveals whether you're correct or not.
You know that the information about whether the marble is bumpy or smooth changes the probability of what color it is, and you want some help with your guesses.
Write a function `color_probability()` that takes two arguments: a color (`'red'`, `'yellow'`, or `'green'`) and a texture (`'bumpy'` or `'smooth'`) and returns the probability as a decimal fraction accurate to two places.
The probability should be a string and should discard any digits after the 100ths place. For example, `2 / 3` or `0.6666666666666666` would become the string `'0.66'`. Note this is different from rounding.
As a complete example, `color_probability('red', 'bumpy')` should return the string `'0.57'`. | # R Y G
PROBS = [[1, 1, 1], # Smooth
[4, 2, 1]] # Bumpy
IDX = {'red': 0, 'yellow': 1, 'green': 2, 'smooth': 0, 'bumpy': 1}
def color_probability(color, texture):
prob = PROBS[IDX[texture]][IDX[color]] / sum(PROBS[IDX[texture]])
return "{:.2}".format(int(prob*100)/100) | # R Y G
PROBS = [[1, 1, 1], # Smooth
[4, 2, 1]] # Bumpy
IDX = {'red': 0, 'yellow': 1, 'green': 2, 'smooth': 0, 'bumpy': 1}
def color_probability(color, texture):
prob = PROBS[IDX[texture]][IDX[color]] / sum(PROBS[IDX[texture]])
return "{:.2}".format(int(prob*100)/100) | train | APPS_structured |
Devu is a class teacher of a class of n students. One day, in the morning prayer of the school, all the students of his class were standing in a line. You are given information of their arrangement by a string s. The string s consists of only letters 'B' and 'G', where 'B' represents a boy and 'G' represents a girl.
Devu wants inter-gender interaction among his class should to be maximum. So he does not like seeing two or more boys/girls standing nearby (i.e. continuous) in the line. e.g. he does not like the arrangements BBG and GBB, but he likes BG, GBG etc.
Now by seeing the initial arrangement s of students, Devu may get furious and now he wants to change this arrangement into a likable arrangement. For achieving that, he can swap positions of any two students (not necessary continuous). Let the cost of swapping people from position i with position j (i ≠ j) be c(i, j). You are provided an integer variable type, then the cost of the the swap will be defined by c(i, j) = |j − i|type.
Please help Devu in finding minimum cost of swaps needed to convert the current arrangement into a likable one.
-----Input-----
The first line of input contains an integer T, denoting the number of test cases. Then T test cases are follow.
The first line of each test case contains an integer type, denoting the type of the cost function. Then the next line contains string s of length n, denoting the initial arrangement s of students.
Note that the integer n is not given explicitly in input.
-----Output-----
For each test case, print a single line containing the answer of the test case, that is, the minimum cost to convert the current arrangement into a likable one. If it is not possible to convert the current arrangement into a likable one, then print -1 instead of the minimum cost.
-----Constraints and Subtasks-----Subtask 1: 25 points
- 1 ≤ T ≤ 105
- 1 ≤ n ≤ 105
- type = 0
- Sum of n over all the test cases in one test file does not exceed 106.
Subtask 2: 25 points
- 1 ≤ T ≤ 105
- 1 ≤ n ≤ 105
- type = 1
- Sum of n over all the test cases in one test file does not exceed 106.
Subtask 3: 25 points
- 1 ≤ T ≤ 105
- 1 ≤ n ≤ 105
- type = 2
- Sum of n over all the test cases in one test file does not exceed 106.
Subtask 4: 25 points
- 1 ≤ T ≤ 102
- 1 ≤ n ≤ 103
- type can be 0, 1 or 2, that is type ∈ {0, 1, 2}.
-----Example-----
Input:
8
0
BB
0
BG
0
BBGG
1
BGG
1
BGGB
1
BBBGG
2
BBGG
2
BGB
Output:
-1
0
1
1
1
3
1
0
-----Explanation-----
Note type of the first 3 test cases is 0. So c(i, j) = 1. Hence we just have to count minimum number of swaps needed.
Example case 1. There is no way to make sure that both the boys does not stand nearby. So answer is -1.
Example case 2. Arrangement is already valid. No swap is needed. So answer is 0.
Example case 3. Swap boy at position 1 with girl at position 2. After swap the arrangement will be BGBG which is a valid arrangement. So answer is 1.
Now type of the next 3 test cases is 1. So c(i, j) = |j − i|, that is, the absolute value of the difference between i and j.
Example case 4. Swap boy at position 0 with girl at position 1. After swap the arrangement will be GBG which is a valid arrangement. So answer is |1 - 0| = 1.
Example case 5. Swap boy at position 0 with girl at position 1. After swap the arrangement will be GBGB which is a valid arrangement. So answer is |1 - 0| = 1.
Example case 6. Swap boy at position 1 with girl at position 4. After swap the arrangement will be BGBGB which is a valid arrangement. So answer is |4 - 1| = 3.
Then type of the last 2 test cases is 2. So c(i, j) = (j − i)2
Example case 7. Swap boy at position 1 with girl at position 2. After swap the arrangement will be BGBG which is a valid arrangement. So answer is (2 - 1)2 = 1.
Example case 8. Arrangement is already valid. No swap is needed. So answer is 0. | def compute(s,c):
bcount = s.count('B')
gcount = s.count('G')
if(abs(bcount-gcount)>1):
return -1
stack = [(0,s[0])]
bans = 0
gans = 0
for i in range(1,len(s)):
if(len(stack)>0 and stack[len(stack)-1][1]!=s[i]):
idx,char = stack[len(stack)-1]
if((idx%2 and s[i]=='B') or (i%2 and char=='B')):
bans += abs(i-idx)**c
elif((idx%2 and s[i]=='G') or (i%2 and char=='G')):
gans += abs(i-idx)**c
stack.pop(len(stack)-1)
else:
stack.append((i,s[i]))
if(gcount==bcount):
return min(bans,gans)
elif(gcount>bcount):
return bans
return gans
for t in range(int(input())):
c = int(input())
print(compute(input(),c))
| def compute(s,c):
bcount = s.count('B')
gcount = s.count('G')
if(abs(bcount-gcount)>1):
return -1
stack = [(0,s[0])]
bans = 0
gans = 0
for i in range(1,len(s)):
if(len(stack)>0 and stack[len(stack)-1][1]!=s[i]):
idx,char = stack[len(stack)-1]
if((idx%2 and s[i]=='B') or (i%2 and char=='B')):
bans += abs(i-idx)**c
elif((idx%2 and s[i]=='G') or (i%2 and char=='G')):
gans += abs(i-idx)**c
stack.pop(len(stack)-1)
else:
stack.append((i,s[i]))
if(gcount==bcount):
return min(bans,gans)
elif(gcount>bcount):
return bans
return gans
for t in range(int(input())):
c = int(input())
print(compute(input(),c))
| train | APPS_structured |
"Humankind cannot gain anything without first giving something in return. To obtain, something of equal value must be lost. That is alchemy's first law of Equivalent Exchange. In those days, we really believed that to be the world's one, and only truth."
-- Alphonse Elric
Now, here we have an equivalent exchange law for triangles which states that two right-angled isosceles triangles of the same color can be made into a square of the same color using Alchemy.
You are given N$N$ right-angled isosceles colored triangles numbered from 1$1$ to N$N$. For each triangle, the two equal sides have a length of 1$1$ unit. The Color of i$i$-th triangle is given by Ci$C_i$.
To create a tower, we choose some consecutive (2×k)+1$2 \times k)+1$ triangles for any k≥0$k \geq 0$. We then pick some 2×k$2 \times k$ of them (these need not be consecutive), and form k$k$ pairs of triangles such that both triangles in pair have the same color. Also, each of the 2×k$2 \times k$ should be in exactly one pair. Then the two triangles in each pair are joined using Alchemy (following the law of equivalent exchange for triangles) to form squares and these k$k$ squares are placed one upon other. The one remaining triangle is placed as a roof to the tower. This results in a tower of the height of k$k$.
Find the maximum height of the tower that can be formed.
In other words, you should select the largest consecutive segment of triangles, such that you can form a tower using every single one of those triangles. In particular, you leave out one triangle, which will form the roof, and the other triangles should all be paired up such that both triangles in a pair have the same colour.
-----Input:-----
- The first line contains T$T$, the number of test cases. Then the test cases follow.
- For every test case, the first line contains N$N$ denoting the number of triangles.
- For every test case, the second line contains N$N$ space-separated integers Ci$C_{i}$ denoting the color of the triangles. ( 1≤i≤N$1 \leq i \leq N$).
-----Output:-----
For every test case, output a single integer denoting the maximum height of the tower that can be formed.
-----Constraints-----
- 1≤T≤100$1 \leq T \leq 100$
- 1≤N≤105$1 \leq N \leq 10^{5}$
- 1≤Ci≤30$1 \leq C_{i} \leq 30$
- Sum of N$N$ over all test cases doesn't exceed 5×105$5\times 10^{5}$
-----Sample Input:-----
4
14
5 4 2 2 3 2 1 3 2 7 4 9 9 9
3
1 2 1
3
1 1 1
5
1 2 3 4 1
-----Sample Output:-----
3
1
1
0
-----EXPLANATION:-----
- #1$1$: The subarray [2,2,3,2,1,3,2]$[2, 2, 3, 2, 1, 3, 2]$ results in a tower of height 3$3$.
- #2$2$: The subarray [1,2,1]$[ 1, 2, 1 ]$ results in a tower of height 1$1$.
- #3$3$: The subarray [1,1,1]$[ 1, 1, 1 ]$ results in a tower of height 1$1$.
- #4$4$: The subarrays [1]$[ 1 ]$, [2]$[ 2 ]$ , [3]$[ 3 ]$, [4]$[ 4 ]$ and [1]$[ 1 ]$ all results in a tower of height 0$0$.
The above tower is possible by subarray [2,2,3,2,1,3,2]$[2, 2, 3, 2, 1, 3, 2]$ resulting in a height of 3$3$ in test case 1$1$. | for t in range(int(input())):
n = int(input())
c = list(map(int,input().split()))
dictionary = {0:0}
parity = 0
k = 0
for i in range(n):
parity ^= (1<<c[i]-1)
if parity not in dictionary:
dictionary[parity] = i+1;
for j in range(30):
x = parity ^ (1<<j);
if x in dictionary:
k=max(k,i-dictionary[x])
print(k//2)
| for t in range(int(input())):
n = int(input())
c = list(map(int,input().split()))
dictionary = {0:0}
parity = 0
k = 0
for i in range(n):
parity ^= (1<<c[i]-1)
if parity not in dictionary:
dictionary[parity] = i+1;
for j in range(30):
x = parity ^ (1<<j);
if x in dictionary:
k=max(k,i-dictionary[x])
print(k//2)
| train | APPS_structured |
Sereja loves all sorts of algorithms. He has recently come up with a new algorithm, which receives a string as an input. Let's represent the input string of the algorithm as q = q_1q_2... q_{k}. The algorithm consists of two steps:
Find any continuous subsequence (substring) of three characters of string q, which doesn't equal to either string "zyx", "xzy", "yxz". If q doesn't contain any such subsequence, terminate the algorithm, otherwise go to step 2. Rearrange the letters of the found subsequence randomly and go to step 1.
Sereja thinks that the algorithm works correctly on string q if there is a non-zero probability that the algorithm will be terminated. But if the algorithm anyway will work for infinitely long on a string, then we consider the algorithm to work incorrectly on this string.
Sereja wants to test his algorithm. For that, he has string s = s_1s_2... s_{n}, consisting of n characters. The boy conducts a series of m tests. As the i-th test, he sends substring s_{l}_{i}s_{l}_{i} + 1... s_{r}_{i} (1 ≤ l_{i} ≤ r_{i} ≤ n) to the algorithm input. Unfortunately, the implementation of his algorithm works too long, so Sereja asked you to help. For each test (l_{i}, r_{i}) determine if the algorithm works correctly on this test or not.
-----Input-----
The first line contains non-empty string s, its length (n) doesn't exceed 10^5. It is guaranteed that string s only contains characters: 'x', 'y', 'z'.
The second line contains integer m (1 ≤ m ≤ 10^5) — the number of tests. Next m lines contain the tests. The i-th line contains a pair of integers l_{i}, r_{i} (1 ≤ l_{i} ≤ r_{i} ≤ n).
-----Output-----
For each test, print "YES" (without the quotes) if the algorithm works correctly on the corresponding test and "NO" (without the quotes) otherwise.
-----Examples-----
Input
zyxxxxxxyyz
5
5 5
1 3
1 11
1 4
3 6
Output
YES
YES
NO
YES
NO
-----Note-----
In the first example, in test one and two the algorithm will always be terminated in one step. In the fourth test you can get string "xzyx" on which the algorithm will terminate. In all other tests the algorithm doesn't work correctly. | def f(x, y, z): return abs(y - x) > 1 or abs(z - x) > 1 or abs(y - z) > 1
t = input()
n, p = len(t), {'x': 0, 'y': 1, 'z': 2}
s = [[0] * (n + 1) for i in range(3)]
for i, c in enumerate(t, 1): s[p[c]][i] = 1
for i in range(3):
for j in range(1, n): s[i][j + 1] += s[i][j]
a, b, c = s
q = [map(int, input().split()) for i in range(int(input()))]
d = ['YES'] * len(q)
for i, (l, r) in enumerate(q):
if r - l > 1 and f(a[r] - a[l - 1], b[r] - b[l - 1], c[r] - c[l - 1]): d[i] = 'NO'
print('\n'.join(d)) | def f(x, y, z): return abs(y - x) > 1 or abs(z - x) > 1 or abs(y - z) > 1
t = input()
n, p = len(t), {'x': 0, 'y': 1, 'z': 2}
s = [[0] * (n + 1) for i in range(3)]
for i, c in enumerate(t, 1): s[p[c]][i] = 1
for i in range(3):
for j in range(1, n): s[i][j + 1] += s[i][j]
a, b, c = s
q = [map(int, input().split()) for i in range(int(input()))]
d = ['YES'] * len(q)
for i, (l, r) in enumerate(q):
if r - l > 1 and f(a[r] - a[l - 1], b[r] - b[l - 1], c[r] - c[l - 1]): d[i] = 'NO'
print('\n'.join(d)) | train | APPS_structured |
The goal of this exercise is to convert a string to a new string where each character in the new string is `"("` if that character appears only once in the original string, or `")"` if that character appears more than once in the original string. Ignore capitalization when determining if a character is a duplicate.
## Examples
```
"din" => "((("
"recede" => "()()()"
"Success" => ")())())"
"(( @" => "))(("
```
**Notes**
Assertion messages may be unclear about what they display in some languages. If you read `"...It Should encode XXX"`, the `"XXX"` is the expected result, not the input! | def duplicate_encode(word):
return "".join(["(" if word.lower().count(c) == 1 else ")" for c in word.lower()]) | def duplicate_encode(word):
return "".join(["(" if word.lower().count(c) == 1 else ")" for c in word.lower()]) | train | APPS_structured |
You're playing a game called Osu! Here's a simplified version of it. There are n clicks in a game. For each click there are two outcomes: correct or bad. Let us denote correct as "O", bad as "X", then the whole play can be encoded as a sequence of n characters "O" and "X".
Using the play sequence you can calculate the score for the play as follows: for every maximal consecutive "O"s block, add the square of its length (the number of characters "O") to the score. For example, if your play can be encoded as "OOXOOOXXOO", then there's three maximal consecutive "O"s block "OO", "OOO", "OO", so your score will be 2^2 + 3^2 + 2^2 = 17. If there are no correct clicks in a play then the score for the play equals to 0.
You know that the probability to click the i-th (1 ≤ i ≤ n) click correctly is p_{i}. In other words, the i-th character in the play sequence has p_{i} probability to be "O", 1 - p_{i} to be "X". You task is to calculate the expected score for your play.
-----Input-----
The first line contains an integer n (1 ≤ n ≤ 10^5) — the number of clicks. The second line contains n space-separated real numbers p_1, p_2, ..., p_{n} (0 ≤ p_{i} ≤ 1).
There will be at most six digits after the decimal point in the given p_{i}.
-----Output-----
Print a single real number — the expected score for your play. Your answer will be considered correct if its absolute or relative error does not exceed 10^{ - 6}.
-----Examples-----
Input
3
0.5 0.5 0.5
Output
2.750000000000000
Input
4
0.7 0.2 0.1 0.9
Output
2.489200000000000
Input
5
1 1 1 1 1
Output
25.000000000000000
-----Note-----
For the first example. There are 8 possible outcomes. Each has a probability of 0.125. "OOO" → 3^2 = 9; "OOX" → 2^2 = 4; "OXO" → 1^2 + 1^2 = 2; "OXX" → 1^2 = 1; "XOO" → 2^2 = 4; "XOX" → 1^2 = 1; "XXO" → 1^2 = 1; "XXX" → 0.
So the expected score is $\frac{9 + 4 + 2 + 1 + 4 + 1 + 1}{8} = 2.75$ | n=int(input().strip())
p=[0]+list(map(float,input().split()))
a=[0]*(n+1)
b=[0]*(n+1)
for i in range(1,n+1):
b[i]=(b[i-1]+1)*p[i]
a[i]=(a[i-1]+2*b[i-1]+1)*p[i]+a[i-1]*(1-p[i])
print(a[-1])
| n=int(input().strip())
p=[0]+list(map(float,input().split()))
a=[0]*(n+1)
b=[0]*(n+1)
for i in range(1,n+1):
b[i]=(b[i-1]+1)*p[i]
a[i]=(a[i-1]+2*b[i-1]+1)*p[i]+a[i-1]*(1-p[i])
print(a[-1])
| train | APPS_structured |
A permutation of length n is an array of size n consisting of n distinct integers in the range [1, n]. For example, (3, 2, 4, 1) is a permutation of length 4, but (3, 3, 1, 4) and (2, 3, 4, 5) are not, as (3, 3, 1, 4) contains duplicate elements, and (2, 3, 4, 5) contains elements not in range [1,4].
A permutation p of length n is good if and only if for any 1 ≤ i ≤ n, pi ≠ i.
Please find the lexicographically smallest good permutation p.
Definition for "lexicographically smaller":
For two permutations p and q, we say that p is lexicographically smaller than q if and only if there exists a index 1 ≤ l ≤ n such that:
- For any 1 ≤ i < l, pi = qi. Note that if l = 1, this constraint means nothing.
- and, pl < ql.
For example, (2, 3, 1, 4) < (2, 3, 4, 1) < (3, 4, 1, 2). The lexicographically smallest permutation is, of course, (1, 2, ..., n), though this one is not good.
-----Input-----
First line of the input contains an integer T denoting number of test cases.
For each test case, the only line contains an integer n.
-----Output-----
For each test case, output the lexicographically smallest good permutation of length n. It's guaranteed that this permutation exists.
-----Constraints-----
- 1 ≤ T ≤ 10
- 2 ≤ n ≤ 105
-----Subtasks-----
- Subtask #1 (17 points): 2 ≤ n ≤ 9
- Subtask #2 (83 points): Original Constraints
-----Example-----
Input:
4
2
3
5
6
Output:
2 1
2 3 1
2 1 4 5 3
2 1 4 3 6 5
-----Explanation-----
Example case 1. The only good permutation of length 2 is (2, 1).
Example case 2. Consider all permutations of length 3, they are(in lexicographically order):
- p = (1, 2, 3), it's not good since p[1] = 1, p[2] = 2 and p[3] = 3;
- p = (1, 3, 2), it's not good since p[1] = 1;
- p = (2, 1, 3), it's not good since p[3] = 3;
- p = (2, 3, 1), it's good since p[1] ≠ 1, p[2] ≠ 2 and p[3] ≠ 3;
- p = (3, 1, 2), it's good since p[1] ≠ 1, p[2] ≠ 2 and p[3] ≠ 3;
- p = (3, 2, 1), it's not good since p[2] = 2.
Thus the minimum good one is (2, 3, 1).
Example case 3. Consider two good permutations for third test case: p=(2, 1, 4, 5, 3) and q=(2, 4, 1, 5, 3), then p < q. You can check lexicographically condition as follows. Find the first index where the entries of two permutations are different, and compare those entries. For example, in this case, the first position where the entries differ is index 2. You can see that p[2] < q[2], as 1 < 4, so p is lexicographically smaller than q. | # cook your dish here
for _ in range(int(input())):
n = int(input())
if n == 2:
print(*[2,1])
elif n == 3:
print(*[2,3,1])
else:
arr = list(range(1,n+1))
for i in range(1,n,2):
if n%2 == 1 and n-i == 2:
arr[i-1], arr[i], arr[i+1] = arr[i], arr[i+1], arr[i-1]
break
else:
arr[i], arr[i-1] = arr[i-1], arr[i]
print(*arr)
| # cook your dish here
for _ in range(int(input())):
n = int(input())
if n == 2:
print(*[2,1])
elif n == 3:
print(*[2,3,1])
else:
arr = list(range(1,n+1))
for i in range(1,n,2):
if n%2 == 1 and n-i == 2:
arr[i-1], arr[i], arr[i+1] = arr[i], arr[i+1], arr[i-1]
break
else:
arr[i], arr[i-1] = arr[i-1], arr[i]
print(*arr)
| train | APPS_structured |
Alice and Johnny are playing a simple guessing game. Johnny picks an arbitrary positive integer n (1<=n<=109) and gives Alice exactly k hints about the value of n. It is Alice's task to guess n, based on the received hints.
Alice often has a serious problem guessing the value of n, and she's beginning to suspect that Johnny occasionally cheats, that is, gives her incorrect hints.
After the last game, they had the following little conversation:
- [Alice] Johnny, you keep cheating!
- [Johnny] Indeed? You cannot prove it.
- [Alice] Oh yes I can. In fact, I can tell you with the utmost certainty that in the last game you lied to me at least *** times.
So, how many times at least did Johnny lie to Alice? Try to determine this, knowing only the hints Johnny gave to Alice.
-----Input-----
The first line of input contains t, the number of test cases (about 20). Exactly t test cases follow.
Each test case starts with a line containing a single integer k, denoting the number of hints given by Johnny (1<=k<=100000). Each of the next k lines contains exactly one hint. The i-th hint is of the form:
operator li logical_value
where operator denotes one of the symbols < , > , or =; li is an integer (1<=li<=109), while logical_value is one of the words: Yes or No. The hint is considered correct if logical_value is the correct reply to the question: "Does the relation: n operator li hold?", and is considered to be false (a lie) otherwise.
-----Output-----
For each test case output a line containing a single integer, equal to the minimal possible number of Johnny's lies during the game.
-----Example-----
Input:
3
2
< 100 No
> 100 No
3
< 2 Yes
> 4 Yes
= 3 No
6
< 2 Yes
> 1 Yes
= 1 Yes
= 1 Yes
> 1 Yes
= 1 Yes
Output:
0
1
2
Explanation: for the respective test cases, the number picked by Johnny could have been e.g. n=100, n=5, and n=1. | # cook your dish here
def guessingGame (l):
a = []
m = 1000000001
for i in range (len(l)):
k=int(l[i][1])
if (l[i][0]=='<' and l[i][2]=='Yes'):
a.append((1,1))
a.append((k,-1))
if (l[i][0]=='<' and l[i][2]=='No'):
a.append((k,1))
a.append((m,-1))
if (l[i][0]=='=' and l[i][2]=='Yes'):
a.append((k,1))
a.append((k+1,-1))
if (l[i][0]=='=' and l[i][2]=='No'):
a.append((1,1))
a.append((k,-1))
a.append((k+1,1))
a.append((m,-1))
if (l[i][0]=='>' and l[i][2]=='Yes'):
a.append((k+1,1))
a.append((m,-1))
if (l[i][0]=='>' and l[i][2]=='No'):
a.append((1,1))
a.append((k+1,-1))
a.sort()
w=0
r=0
for i in range (len(a)):
w+=a[i][1]
r=max(w,r)
return len(l)-r
def __starting_point():
T = int(input())
answer = []
for _ in range (T):
e = int(input())
temp = []
for q_t in range (e):
q = list(map(str,input().rstrip().split()))
temp.append(q)
result = guessingGame(temp)
print(result)
__starting_point() | # cook your dish here
def guessingGame (l):
a = []
m = 1000000001
for i in range (len(l)):
k=int(l[i][1])
if (l[i][0]=='<' and l[i][2]=='Yes'):
a.append((1,1))
a.append((k,-1))
if (l[i][0]=='<' and l[i][2]=='No'):
a.append((k,1))
a.append((m,-1))
if (l[i][0]=='=' and l[i][2]=='Yes'):
a.append((k,1))
a.append((k+1,-1))
if (l[i][0]=='=' and l[i][2]=='No'):
a.append((1,1))
a.append((k,-1))
a.append((k+1,1))
a.append((m,-1))
if (l[i][0]=='>' and l[i][2]=='Yes'):
a.append((k+1,1))
a.append((m,-1))
if (l[i][0]=='>' and l[i][2]=='No'):
a.append((1,1))
a.append((k+1,-1))
a.sort()
w=0
r=0
for i in range (len(a)):
w+=a[i][1]
r=max(w,r)
return len(l)-r
def __starting_point():
T = int(input())
answer = []
for _ in range (T):
e = int(input())
temp = []
for q_t in range (e):
q = list(map(str,input().rstrip().split()))
temp.append(q)
result = guessingGame(temp)
print(result)
__starting_point() | train | APPS_structured |
## Decode the diagonal.
Given a grid of characters. Output a decoded message as a string.
Input
```
H Z R R Q
D I F C A E A !
G H T E L A E
L M N H P R F
X Z R P E
```
Output
`HITHERE!` (diagonally down right `↘` and diagonally up right `↗` if you can't go further).
The message ends when there is no space at the right up or down diagonal.
To make things even clearer: the same example, but in a simplified view
```
H _ _ _ _
_ I _ _ _ _ _ !
_ _ T _ _ _ E
_ _ _ H _ R _
_ _ _ _ E
``` | def get_diagonale_code(grid: str) -> str:
ans=[]
if grid:
grid = [k.strip().split(" ") for k in grid.split("\n")]
i=j=0
dir = True
while j <len(grid[i]):
ans.append(grid[i][j])
if i == len(grid) - 1:dir = False
if (i == 0): dir = True
i = 0 if len(grid) == 1 else i +1 if dir else i - 1
j+=1
return "".join(ans)
| def get_diagonale_code(grid: str) -> str:
ans=[]
if grid:
grid = [k.strip().split(" ") for k in grid.split("\n")]
i=j=0
dir = True
while j <len(grid[i]):
ans.append(grid[i][j])
if i == len(grid) - 1:dir = False
if (i == 0): dir = True
i = 0 if len(grid) == 1 else i +1 if dir else i - 1
j+=1
return "".join(ans)
| train | APPS_structured |
You are given an array (which will have a length of at least 3, but could be very large) containing integers. The array is either entirely comprised of odd integers or entirely comprised of even integers except for a single integer `N`. Write a method that takes the array as an argument and returns this "outlier" `N`.
## Examples
```python
[2, 4, 0, 100, 4, 11, 2602, 36]
Should return: 11 (the only odd number)
[160, 3, 1719, 19, 11, 13, -21]
Should return: 160 (the only even number)
``` | def find_outlier(integers):
listEven = []
listOdd = []
for n in integers:
if n % 2 == 0:
listEven.append(n)
else:
listOdd.append(n)
if len(listEven) == 1:
return listEven[0]
else:
return listOdd[0] | def find_outlier(integers):
listEven = []
listOdd = []
for n in integers:
if n % 2 == 0:
listEven.append(n)
else:
listOdd.append(n)
if len(listEven) == 1:
return listEven[0]
else:
return listOdd[0] | train | APPS_structured |
>When no more interesting kata can be resolved, I just choose to create the new kata, to solve their own, to enjoy the process --myjinxin2015 said
# Description:
Give you two number `m` and `n`(two positive integer, m < n), make a triangle pattern with number sequence `m to n`. The order is clockwise, starting from the top corner, like this:
```
When m=1 n=10 triangle is:
1
9 2
8 0 3
7 6 5 4
```
Note: The pattern only uses the last digit of each number; Each row separated by "\n"; Each digit separated by a space; Left side may need pad some spaces, but don't pad the right side; If `m to n` can not make the triangle, return `""`.
# Some examples:
```
makeTriangle(1,3) should return:
1
3 2
makeTriangle(6,20) should return:
6
7 7
6 8 8
5 0 9 9
4 3 2 1 0
makeTriangle(1,12) should return ""
``` | def make_triangle(n,m):
layers = layer(m-n+1)
if layers == False:
return ""
board = []
for i in range(layers):
board.append([""]*(i+1))
triangle = make(n%10,board,0,0,len(board))
return tri_print(triangle)
def layer(n):
a = 0
layer = 0
for i in range(1,n):
a+= i
layer += 1
if a == n:
return layer
elif a > n:
return False
else:
continue
def tri_print(board):
sentence = ""
for i in range(len(board)):
sentence += " "*(len(board)-1-i)
for j in range(len(board[i])):
sentence+= str(board[i][j]) + " "
sentence = sentence[:-1] + "\n"
return sentence[:-1]
def make(n,board,row,col,x):
for i in range(row,x):
if board[i][col] == "":
board[i][col] = n
if n == 9:
n = 0
else:
n+=1
col +=1
for j in range(x-1,-1,-1):
if board[x-1][j] == "" :
board[x-1][j] = n
n_col = j
if n == 9:
n = 0
else:
n+=1
if check(board):
return board
for z in range(x-1,row,-1):
if board[z][n_col] == "":
board[z][n_col] = n
rw,cl = z,n_col
if n == 9:
n = 0
else:
n+=1
if not check(board):
return make(n,board,rw,cl,x-1)
return board
def check(board):
for i in board:
for j in i:
if j == "" :
return False
return True | def make_triangle(n,m):
layers = layer(m-n+1)
if layers == False:
return ""
board = []
for i in range(layers):
board.append([""]*(i+1))
triangle = make(n%10,board,0,0,len(board))
return tri_print(triangle)
def layer(n):
a = 0
layer = 0
for i in range(1,n):
a+= i
layer += 1
if a == n:
return layer
elif a > n:
return False
else:
continue
def tri_print(board):
sentence = ""
for i in range(len(board)):
sentence += " "*(len(board)-1-i)
for j in range(len(board[i])):
sentence+= str(board[i][j]) + " "
sentence = sentence[:-1] + "\n"
return sentence[:-1]
def make(n,board,row,col,x):
for i in range(row,x):
if board[i][col] == "":
board[i][col] = n
if n == 9:
n = 0
else:
n+=1
col +=1
for j in range(x-1,-1,-1):
if board[x-1][j] == "" :
board[x-1][j] = n
n_col = j
if n == 9:
n = 0
else:
n+=1
if check(board):
return board
for z in range(x-1,row,-1):
if board[z][n_col] == "":
board[z][n_col] = n
rw,cl = z,n_col
if n == 9:
n = 0
else:
n+=1
if not check(board):
return make(n,board,rw,cl,x-1)
return board
def check(board):
for i in board:
for j in i:
if j == "" :
return False
return True | train | APPS_structured |
Johnny is a boy who likes to open and close lockers. He loves it so much that one day, when school was out, he snuck in just to play with the lockers.
Each locker can either be open or closed. If a locker is closed when Johnny gets to it, he opens it, and vice versa.
The lockers are numbered sequentially, starting at 1.
Starting at the first locker, Johnny runs down the row, opening each locker.
Then he runs all the way back to the beginning and runs down the row again, this time skipping to every other locker. (2,4,6, etc)
Then he runs all the way back and runs through again, this time skipping two lockers for every locker he opens or closes. (3,6,9, etc)
He continues this until he has finished running past the last locker (i.e. when the number of lockers he skips is greater than the number of lockers he has).
------
The equation could be stated as follows:
> Johnny runs down the row of lockers `n` times, starting at the first locker each run and skipping `i` lockers as he runs, where `n` is the number of lockers there are in total and `i` is the current run.
The goal of this kata is to determine which lockers are open at the end of Johnny's running.
The program accepts an integer giving the total number of lockers, and should output an array filled with the locker numbers of those which are open at the end of his run. | from math import floor
#Pretty sure this is the fastest implementation; only one square root, and sqrt(n) multiplications.
#Plus, no booleans, because they're super slow.
locker_run = lambda l: [i * i for i in range(1, int(floor(l ** .5)) + 1)] | from math import floor
#Pretty sure this is the fastest implementation; only one square root, and sqrt(n) multiplications.
#Plus, no booleans, because they're super slow.
locker_run = lambda l: [i * i for i in range(1, int(floor(l ** .5)) + 1)] | train | APPS_structured |
```if:java
___Note for Java users:___ Due to type checking in Java, inputs and outputs are formated quite differently in this language. See the footnotes of the description.
```
You have the following lattice points with their corresponding coordinates and each one with an specific colour.
```
Point [x , y] Colour
----------------------------
A [ 3, 4] Blue
B [-7, -1] Red
C [ 7, -6] Yellow
D [ 2, 5] Yellow
E [ 1, -5] Red
F [-1, 4] Red
G [ 1, 7] Red
H [-3, 5] Red
I [-3, -5] Blue
J [ 4, 1] Blue
```
We want to count the triangles that have the three vertices with the same colour. The following picture shows the distribution of the points in the plane with the required triangles.
![source: imgur.com](http://i.imgur.com/sP0l1i1.png)
The input that we will have for the field of lattice points described above is:
```
[[[3, -4], "blue"], [[-7, -1], "red"], [[7, -6], "yellow"], [[2, 5], "yellow"],
[[1, -5], "red"], [[-1, 4], "red"], [[1, 7], "red"], [[-3, 5], "red"],
[[-3, -5], "blue"], [[4, 1], "blue"] ]
```
We see the following result from it:
```
Colour Amount of Triangles Triangles
Yellow 0 -------
Blue 1 AIJ
Red 10 BEF,BEG,BEH,BFG,BFH,BGH,EFG,EFH,EHG,FGH
```
As we have 5 different points in red and each combination of 3 points that are not aligned.
We need a code that may give us the following information in order:
```
1) Total given points
2) Total number of colours
3) Total number of possible triangles
4) and 5) The colour (or colours, sorted alphabetically) with the highest amount of triangles
```
In Python our function will work like:
```
[10, 3, 11, ["red",10]]) == count_col_triang([[[3, -4], "blue"], [[-7, -1], "red"], [[7, -6], "yellow"], [[2, 5], "yellow"],
[[1, -5], "red"], [[-1, 4], "red"], [[1, 7], "red"], [[-3, 5], "red"],
[[-3, -5], "blue"], [[4, 1], "blue"] ])
```
In the following case we have some points that are aligned and we have less triangles that can be formed:
```
[10, 3, 7, ["red", 6]] == count_col_triang([[[3, -4], "blue"], [[-7, -1], "red"], [[7, -6], "yellow"], [[2, 5], "yellow"],
[[1, -5], "red"], [[1, 1], "red"], [[1, 7], "red"], [[1, 4], "red"],
[[-3, -5], "blue"], [[4, 1], "blue"] ])
```
Just to see the change with the previous case we have this:
![source: imgur.com](http://i.imgur.com/cCgO7ql.png)
In the special case that the list of points does not generate an even single triangle, the output will be like this case:
```
[9, 3, 0, []] == count_col_triang([[[1, -2], "red"], [[7, -6], "yellow"], [[2, 5], "yellow"], [[1, -5], "red"],
[[1, 1], "red"], [[1, 7], "red"], [[1, 4], "red"], [[-3, -5], "blue"],
[[4, 1], "blue"] ])
```
It will be this case:
![source: imgur.com](http://i.imgur.com/VB7t7Ij.png)
If in the result we have two or more colours with the same maximum amount of triangles, the last list should be like (e.g)
```
[35, 6, 35, ["blue", "red", "yellow", 23]] # having the names of the colours sorted alphabetically
```
For the condition of three algined points A, B, C, you should know that the the following determinant should be 0.
```
| xA yA 1|
| xB yB 1| = 0
| xC yC 1|
```
Assumptions:
- In the list you have unique points, so a point can have only one colour.
- All the inputs are valid
Enjoy it!
````if:java
---
___For java users:___
Two immutable objects, `ColouredPoint` and `TriangleResult`, have been designed for you in the preloaded part. You will receive inputs as lists of ColouredPoint objects and will return a TriangleResult object. For the last one, you may note the organization of the arguments of the constructor which differs a bit from the description above.
You may find below the signatures of the available methods of these objects:
```` | import numpy as np
from itertools import combinations
def ctri(lst):
if len(lst)<3:
return 0
return sum(1 for j in combinations(lst, 3) if abs(np.linalg.det(np.mat([i+[1] for i in j])))>1e-3)
def count_col_triang(ipt):
d = {}
for i in ipt:
if i[1] not in d:
d[i[1]] = [i[0]]
else:
d[i[1]].append(i[0])
p = {i:ctri(d[i]) for i in d}
pmax = max(p.values())
plst = [] if pmax == 0 else sorted([i for i in p if p[i]==pmax]) + [pmax]
return [len(ipt), len(p), sum(p.values()), plst] | import numpy as np
from itertools import combinations
def ctri(lst):
if len(lst)<3:
return 0
return sum(1 for j in combinations(lst, 3) if abs(np.linalg.det(np.mat([i+[1] for i in j])))>1e-3)
def count_col_triang(ipt):
d = {}
for i in ipt:
if i[1] not in d:
d[i[1]] = [i[0]]
else:
d[i[1]].append(i[0])
p = {i:ctri(d[i]) for i in d}
pmax = max(p.values())
plst = [] if pmax == 0 else sorted([i for i in p if p[i]==pmax]) + [pmax]
return [len(ipt), len(p), sum(p.values()), plst] | train | APPS_structured |
Limak is a little polar bear.
He is playing a video game and he needs your help.
There is a row with N cells, each either empty or occupied by a soldier, denoted by '0' and '1' respectively.
The goal of the game is to move all soldiers to the right (they should occupy some number of rightmost cells).
The only possible command is choosing a soldier and telling him to move to the right as far as possible.
Choosing a soldier takes 1 second, and a soldier moves with the speed of a cell per second.
The soldier stops immediately if he is in the last cell of the row or the next cell is already occupied.
Limak isn't allowed to choose a soldier that can't move at all (the chosen soldier must move at least one cell to the right).
Limak enjoys this game very much and wants to play as long as possible.
In particular, he doesn't start a new command while the previously chosen soldier moves.
Can you tell him, how many seconds he can play at most?
-----Input-----
The first line of the input contains an integer T denoting the number of test cases. The description of T test cases follows.
The only line of each test case contains a string S describing the row with N cells.
Each character is either '0' or '1', denoting an empty cell or a cell with a soldier respectively.
-----Output-----
For each test case, output a single line containing one integer — the maximum possible number of seconds Limak will play the game.
-----Constraints-----
- 1 ≤ T ≤ 5
- 1 ≤ N ≤ 105 (N denotes the length of the string S)
-----Subtasks-----
- Subtask #1 (25 points): 1 ≤ N ≤ 10
- Subtask #2 (25 points): 1 ≤ N ≤ 2000
- Subtask #3 (50 points): Original constraints.
-----Example-----
Input:
4
10100
1100001
000000000111
001110100011010
Output:
8
10
0
48
-----Explanation-----
Test case 1.
The initial string is 10100.
There are N = 5 cells.
There is one soldier in the first cell, and one soldier in the third cell.
The following scenario maximizes the total time:
- Limak chooses the soldier in the first cell.
This soldier can move only one cell to the right.
It takes 1 second to choose a soldier and 1 second for a soldier to move to the next cell (2 seconds in total).
The string is 01100 now.
- Limak has only one choice.
He must choose the soldier in the third cell because the other soldier can't move at all (the soldier in the second cell can't move to the right because the next cell is already occupied).
Choosing a soldier takes 1 second.
The chosen soldier moves from the third cell to the fifth cell, which takes 2 seconds.
This operation takes 1 + 2 = 3 seconds in total.
The string is 01001 now.
- Limak has only one choice again.
Since the soldier in the last row can't move further to the right, the soldier in the second cell must be chosen.
He will move 2 cells to the right.
This operation takes 1 + 2 = 3 seconds in total.
The string become 00011 and the game is over.
The total time is 2 + 3 + 3 = 8.
Test case 2.
The initial string is 1100001.
There is only one possible scenario:
- 1100001 is changed to 1000011 in 5 seconds (1 second to choose a soldier and 4 seconds for the soldier to move 4 cells to the right).
- 1000011 is changed to 0000111 in 5 seconds.
The total time is 5 + 5 = 10 seconds.
Test case 3.
The game is over immediately because all soldiers occupy rightmost cells already.
The answer is 0. | for _ in range(int(input())):
s = input()
count = 0
n = len(s)
count = 0
total = 0
lastindex = n-1
curr = n-1
while (curr >= 0 and s[lastindex] == "1"):
curr -= 1
lastindex -= 1
while curr >= 0:
if s[curr] == "1":
if s[curr+1] == "0":
count += 1
total += count + (lastindex - curr)
lastindex -= 1
curr -= 1
print(total) | for _ in range(int(input())):
s = input()
count = 0
n = len(s)
count = 0
total = 0
lastindex = n-1
curr = n-1
while (curr >= 0 and s[lastindex] == "1"):
curr -= 1
lastindex -= 1
while curr >= 0:
if s[curr] == "1":
if s[curr+1] == "0":
count += 1
total += count + (lastindex - curr)
lastindex -= 1
curr -= 1
print(total) | train | APPS_structured |
**Story**
On some island lives a chameleon population. Chameleons here can be of only one of three colors - red, green and blue. Whenever two chameleons of different colors meet, they can change their colors to a third one (i.e. when red and blue chameleons meet, they can both become green). There is no other way for chameleons to change their color (in particular, when red and blue chameleons meet, they can't become both red, only third color can be assumed).
Chameleons want to become of one certain color. They may plan they meetings to reach that goal. Chameleons want to know, how fast their goal can be achieved (if it can be achieved at all).
**Formal problem**
*Input:*
Color is coded as integer, 0 - red, 1 - green, 2 - blue.
Chameleon starting population is given as an array of three integers, with index corresponding to color (i.e. [2, 5, 3] means 2 red, 5 green and 3 blue chameleons). All numbers are non-negative, their sum is between `1` and `int.MaxValue` (maximal possible value for `int` type, in other languages). Desired color is given as an integer from 0 to 2.
*Output:*
`Kata.Chameleon` should return *minimal* number of meetings required to change all chameleons to a given color, or -1 if it is impossible (for example, if all chameleons are initially of one other color).
**Notes and hints**
-- Some tests use rather big input values. Be effective.
-- There is a strict proof that answer is either -1 or no greater than total number of chameleons (thus, return type `int` is justified). Don't worry about overflow.
**Credits**
Kata based on "Chameleons" puzzle from braingames.ru: http://www.braingames.ru/?path=comments&puzzle=226 (russian, not translated). | def chameleon(chameleons, color):
(_,a), (_,b), (_,c) = sorted((i==color, v) for i,v in enumerate(chameleons))
return -1 if not a and not c or (b-a) % 3 else b | def chameleon(chameleons, color):
(_,a), (_,b), (_,c) = sorted((i==color, v) for i,v in enumerate(chameleons))
return -1 if not a and not c or (b-a) % 3 else b | train | APPS_structured |
Given two integer arrays where the second array is a shuffled duplicate of the first array with one element missing, find the missing element.
Please note, there may be duplicates in the arrays, so checking if a numerical value exists in one and not the other is not a valid solution.
```
find_missing([1, 2, 2, 3], [1, 2, 3]) => 2
```
```
find_missing([6, 1, 3, 6, 8, 2], [3, 6, 6, 1, 2]) => 8
```
The first array will always have at least one element. | def find_missing(arr1, arr2):
for x in set(arr1):
if arr1.count(x) != arr2.count(x): return x
| def find_missing(arr1, arr2):
for x in set(arr1):
if arr1.count(x) != arr2.count(x): return x
| train | APPS_structured |
The chef won a duet singing award at Techsurge & Mridang 2012. From that time he is obsessed with the number 2.
He just started calculating the powers of two. And adding the digits of the results.
But he got puzzled after a few calculations. So gave you the job to generate the solutions to 2^n and find their sum of digits.
-----Input-----
N : number of inputs N<=100
then N lines with input T<=2000
-----Output-----
The output for the corresponding input T
-----Example-----
Input:
3
5
10
4
Output:
5
7
7
Explanation:
2^5=32
3+2=5
2^10=1024
1+0+2+4=7
2^4=16
1+6=7 | for _ in range(int(input())):
i=int(input())
a=str(2**i)
sums=0
for d in a:
d=int(d)
sums+=d
print(sums) | for _ in range(int(input())):
i=int(input())
a=str(2**i)
sums=0
for d in a:
d=int(d)
sums+=d
print(sums) | train | APPS_structured |
## Task
In your favorite game, you must shoot a target with a water-gun to gain points. Each target can be worth a different amount of points.
You are guaranteed to hit every target that you try to hit. You cannot hit consecutive targets though because targets are only visible for one second (one at a time) and it takes you a full second to reload your water-gun after shooting (you start the game already loaded).
Given an array `vals` with the order of each target's point value, determine the maximum number of points that you can win.
## Example
For `vals = [1, 2, 3, 4]`, the result should be `6`.
your optimal strategy would be to let the first one pass and shoot the second one with value 2 and the 4th one with value 4 thus:
`vals[1](2) + vals[3](4) = 6`
For `vals = [5, 5, 5, 5, 5]`, the result should be `15`.
your optimal strategy would be to shoot the 1st, 3rd and 5th value:
`5 + 5 + 5 = 15`
You haven't shoot the 2nd, 4th value because you are reloading your water-gun after shooting other values.
Note that the value can be zero or negative, don't shoot them ;-)
For `vals = [0, 0, -1, -1]`, the result should be `0`.
For `vals = [5, -2, -9, -4]`, the result should be `5`.
Shoot the first one is enough.
## Input/Output
- `[input]` integer array `vals`
The point values (negative or non-negative) of the targets (in order of appearance).
- `[output]` an integer
The maximum number of points that you can score. | def target_game(values):
sum1 = 0
sum2 = 0
for value in values:
sum1 = max(sum1 + value, sum2)
sum1, sum2 = sum2, sum1
return max(sum1, sum2)
| def target_game(values):
sum1 = 0
sum2 = 0
for value in values:
sum1 = max(sum1 + value, sum2)
sum1, sum2 = sum2, sum1
return max(sum1, sum2)
| train | APPS_structured |
In the world of DragonBool there are fierce warriors called Soints. Also there are even fiercer warriors called Sofloats – the mortal enemies of Soints.
The power of each warrior is determined by the amount of chakra he possesses which is some positive integer. Warriors with zero level of chakra are dead warriors :) When the fight between Soint with power CI and Sofloat with power CF occurs the warrior with lower power will die and the winner will lose the amount of chakra that his enemy have possessed before the fight. So three cases are possible:
- CI > CF. Then Sofloat will die while the new power of Soint will be CI – CF.
- CI < CF. Then Soint will die while the new power of Sofloat will be CF – CI.
- CI = CF. In this special case both warriors die.
Each warrior (Soint or Sofloat) has his level of skills which is denoted by some positive integer. The fight between two warriors can occur only when these warriors are Soint and Sofloat of the same level. In particual, friendly fights are not allowed, i.e., a Soint cannot fight with another Soint and the same holds for Sofloats.
Lets follow the following convention to denote the warriors. A Soint of level L and power C will be denoted as (I, C, L), while Sofloat of level L and power C will be denoted as (F, C, L). Consider some examples. If A = (I, 50, 1) fights with B = (F, 20, 1), B dies and A becomes (I, 30, 1). On the other hand, (I, 50, 1) cannot fight with (F, 20, 2) as they have different levels.
There is a battle between Soints and Sofloats. There are N Soints and M Sofloats in all. The battle will consist of series of fights. As was mentioned above in each fight one Soint and one Sofloat of the same level take part and after the fight the warrior with lower power will die (or both will die if they have the same power). The battle proceeds as long as there exists at least one pair of warriors who can fight. The distribution of warriors by levels satisfies the following condition: for every Soint of level L there exists at least one Sofloat of the same level L and vice-versa. So if for some level L we have at least one warrior of this level then there is at least one Soint of level L and at least one Sofloat of level L.
There is a powerful wizard, whose name is SoChef, on the side of Soints. He can increase the amount of chakra of each Soint by any number. SoChef wants the army of Soints to win this battle. But increasing amount of chakra of any Soint by one costs him a lot of his magic power. Hence he wants to minimize the total amount of additional chakra he should give to Soints in order for them to win. Note, however, that the win here means that all Sofloats should be dead irregardless of whether any Soint is alive. Also note that the battle can proceed by different scenarios and the SoChef need to distribute additional chakra among the Soints in such a way that they will win for any possible battle scenario. Help SoChef and find the minimal amount of additional chakra he should give to Soints in order for them to win.
-----Input-----
The first line of the input contains an integer T, the number of test cases. T test cases follow. The first line of each test case contains two space separated integers N and M. Here N is the number of Soints participating in the battle and M is the number of Sofloats for the same. Each of the next N lines contains two space separated integers Ci and Li, the amount of chakra and level of i-th Soint correspondingly. The next M lines describe power and level of Sofloats participating in the battle in the same format.
-----Output-----
For each test case output a single integer on a single line, the minimum amount of chakra SoChef should give to Soints in order for them to win the battle.
-----Constraints-----
Each integer in the input file is positive and does not exceed 100. That is1 ≤ T ≤ 100
1 ≤ N ≤ 100
1 ≤ M ≤ 100
1 ≤ Ci ≤ 100
1 ≤ Li ≤ 100
For every Soint of level L there exists at least one Sofloat of the same level L and vice-versa.
It is guaranteed that each official test file will satisfy all these constraints. You DON'T need to verify them in your program.
-----Example-----
Input:
2
2 3
10 1
20 2
5 2
5 2
18 1
5 5
73 87
69 13
36 36
77 46
43 93
49 46
74 93
78 87
99 13
59 36
Output:
8
89
-----Explanation-----
Case 1.
The warriors are I1 = (I, 10, 1), I2 = (I, 20, 2), F1 = (F, 5, 2), F2 = (F, 5, 2), F3 = (F, 18, 1). Without the SoChef help the battle can proceed as follows.
- I2 fights with F1, F1 dies, I2 becomes (I, 15, 2).
- I2 fights with F2, F2 dies, I2 becomes (I, 10, 2).
- I1 fights with F3, I1 dies, F3 becomes (F, 8, 1).
So if SoChef will give 8 additional units of chakra to I1 the Soints will win the battle and even one Soint (I2) will left alive. Hence the answer is 8. | T = int(input())
for t in range(0, T):
N, M = input().split()
I = []
F = []
for n in range(0, int(N)):
C, L = input().split()
I.append((int(C), int(L)))
for n in range(0, int(M)):
C, L = input().split()
F.append((int(C), int(L)))
chakra = 0
for l in set([i[1] for i in I]):
Cil = [i[0] for i in I if i[1] == l]
Cfl = [f[0] for f in F if f[1] == l]
temp = (sum(Cfl) - sum(Cil))
if temp > 0:
chakra += temp
print(chakra)
| T = int(input())
for t in range(0, T):
N, M = input().split()
I = []
F = []
for n in range(0, int(N)):
C, L = input().split()
I.append((int(C), int(L)))
for n in range(0, int(M)):
C, L = input().split()
F.append((int(C), int(L)))
chakra = 0
for l in set([i[1] for i in I]):
Cil = [i[0] for i in I if i[1] == l]
Cfl = [f[0] for f in F if f[1] == l]
temp = (sum(Cfl) - sum(Cil))
if temp > 0:
chakra += temp
print(chakra)
| train | APPS_structured |