inputs
stringlengths 175
2.22k
| targets
stringlengths 10
2.05k
| language
stringclasses 1
value | split
stringclasses 2
values | template
stringclasses 2
values | dataset
stringclasses 1
value | config
stringclasses 1
value |
---|---|---|---|---|---|---|
Solve in Python:
You play your favourite game yet another time. You chose the character you didn't play before. It has $str$ points of strength and $int$ points of intelligence. Also, at start, the character has $exp$ free experience points you can invest either in strength or in intelligence (by investing one point you can either raise strength by $1$ or raise intelligence by $1$).
Since you'd like to make some fun you want to create a jock character, so it has more strength than intelligence points (resulting strength is strictly greater than the resulting intelligence).
Calculate the number of different character builds you can create (for the purpose of replayability) if you must invest all free points. Two character builds are different if their strength and/or intellect are different.
-----Input-----
The first line contains the single integer $T$ ($1 \le T \le 100$) — the number of queries. Next $T$ lines contain descriptions of queries — one per line.
This line contains three integers $str$, $int$ and $exp$ ($1 \le str, int \le 10^8$, $0 \le exp \le 10^8$) — the initial strength and intelligence of the character and the number of free points, respectively.
-----Output-----
Print $T$ integers — one per query. For each query print the number of different character builds you can create.
-----Example-----
Input
4
5 3 4
2 1 0
3 5 5
4 10 6
Output
3
1
2
0
-----Note-----
In the first query there are only three appropriate character builds: $(str = 7, int = 5)$, $(8, 4)$ and $(9, 3)$. All other builds are either too smart or don't use all free points.
In the second query there is only one possible build: $(2, 1)$.
In the third query there are two appropriate builds: $(7, 6)$, $(8, 5)$.
In the fourth query all builds have too much brains. | T = int(input())
for i in range(T):
s, k, f = map(int, input().split())
print(min(f + 1, max(0, (s + f - k + 1) // 2))) | python | test | qsol | codeparrot/apps | all |
I found an interesting problem on https://leetcode.com/problems/factorial-trailing-zeroes/:
Given an integer n, return the number of trailing zeroes in n!.
Example 1:
Input: 3
Output: 0
Explanation: 3! = 6, no trailing zero.
Example 2:
Input: 5
Output: 1
Explanation: 5! = 120, one trailing zero.
Note: Your solution should be in logarithmic time complexity.
I tried it in Python, but could not do it. Can you solve it? | class Solution:
def trailingZeroes(self, n):
"""
:type n: int
:rtype: int
"""
c=0
while n>0:
n//=5
c+=n
return c | python | train | abovesol | codeparrot/apps | all |
Solve in Python:
Let us call a pair of integer numbers m-perfect, if at least one number in the pair is greater than or equal to m. Thus, the pairs (3, 3) and (0, 2) are 2-perfect while the pair (-1, 1) is not.
Two integers x, y are written on the blackboard. It is allowed to erase one of them and replace it with the sum of the numbers, (x + y).
What is the minimum number of such operations one has to perform in order to make the given pair of integers m-perfect?
-----Input-----
Single line of the input contains three integers x, y and m ( - 10^18 ≤ x, y, m ≤ 10^18).
Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preffered to use the cin, cout streams or the %I64d specifier.
-----Output-----
Print the minimum number of operations or "-1" (without quotes), if it is impossible to transform the given pair to the m-perfect one.
-----Examples-----
Input
1 2 5
Output
2
Input
-1 4 15
Output
4
Input
0 -1 5
Output
-1
-----Note-----
In the first sample the following sequence of operations is suitable: (1, 2) $\rightarrow$ (3, 2) $\rightarrow$ (5, 2).
In the second sample: (-1, 4) $\rightarrow$ (3, 4) $\rightarrow$ (7, 4) $\rightarrow$ (11, 4) $\rightarrow$ (15, 4).
Finally, in the third sample x, y cannot be made positive, hence there is no proper sequence of operations. | x, y, m = list(map(int, input().split()))
if max(x, y) >= m:
print(0)
elif m < 0 or max(x, y) <= 0:
print(-1)
else:
if x + y < 0:
cnt = (max(x, y) - min(x, y)) // max(x, y)
x, y = min(x, y) + max(x, y) * cnt, max(x, y)
else:
cnt = 0
while max(x, y) < m:
x, y = max(x, y), x + y
cnt += 1
print(cnt) | python | test | qsol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/1062/B:
JATC's math teacher always gives the class some interesting math problems so that they don't get bored. Today the problem is as follows. Given an integer $n$, you can perform the following operations zero or more times: mul $x$: multiplies $n$ by $x$ (where $x$ is an arbitrary positive integer). sqrt: replaces $n$ with $\sqrt{n}$ (to apply this operation, $\sqrt{n}$ must be an integer).
You can perform these operations as many times as you like. What is the minimum value of $n$, that can be achieved and what is the minimum number of operations, to achieve that minimum value?
Apparently, no one in the class knows the answer to this problem, maybe you can help them?
-----Input-----
The only line of the input contains a single integer $n$ ($1 \le n \le 10^6$) — the initial number.
-----Output-----
Print two integers: the minimum integer $n$ that can be achieved using the described operations and the minimum number of operations required.
-----Examples-----
Input
20
Output
10 2
Input
5184
Output
6 4
-----Note-----
In the first example, you can apply the operation mul $5$ to get $100$ and then sqrt to get $10$.
In the second example, you can first apply sqrt to get $72$, then mul $18$ to get $1296$ and finally two more sqrt and you get $6$.
Note, that even if the initial value of $n$ is less or equal $10^6$, it can still become greater than $10^6$ after applying one or more operations.
I tried it in Python, but could not do it. Can you solve it? | n = int(input())
fac = {}
nn = n
maxe = 1
while nn%2 == 0:
fac[2] = fac.get(2, 0) + 1
nn >>= 1
for i in range(3, nn+1, 2):
if i*i > nn:
break
while nn%i == 0:
fac[i] = fac.get(i, 0) + 1
nn //= i
if nn > 1:
fac[nn] = 1
# print(nn)
# print(fac)
maxe = 1
mine = n
prod = 1
for f in fac:
if fac[f] > maxe:
maxe = fac[f]
if fac[f] < mine:
mine = fac[f]
prod *= f
ops = 0
t = 1
while t < maxe:
t <<= 1
ops += 1
if mine < t:
ops += 1
print(prod, ops) | python | test | abovesol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/1183/A:
Polycarp knows that if the sum of the digits of a number is divisible by $3$, then the number itself is divisible by $3$. He assumes that the numbers, the sum of the digits of which is divisible by $4$, are also somewhat interesting. Thus, he considers a positive integer $n$ interesting if its sum of digits is divisible by $4$.
Help Polycarp find the nearest larger or equal interesting number for the given number $a$. That is, find the interesting number $n$ such that $n \ge a$ and $n$ is minimal.
-----Input-----
The only line in the input contains an integer $a$ ($1 \le a \le 1000$).
-----Output-----
Print the nearest greater or equal interesting number for the given number $a$. In other words, print the interesting number $n$ such that $n \ge a$ and $n$ is minimal.
-----Examples-----
Input
432
Output
435
Input
99
Output
103
Input
237
Output
237
Input
42
Output
44
I tried it in Python, but could not do it. Can you solve it? | n = int(input())
def s(n):
k = 0
for i in str(n):
k += int(i)
return k
while s(n) % 4 != 0:
n += 1
print(n) | python | test | abovesol | codeparrot/apps | all |
I found an interesting problem on https://www.codechef.com/NEWB2020/problems/CNFCT:
Oliver and Nova are true lovers. Inspite of knowing that Nova will die Oliver married her at the lake where they met. But they had a conflict about even and odd numbers. Nova likes the odd numbers and Oliver prefers even. One day they went to a fair where Oliver bought some square shaped marshmallows and Nova bought some round shaped. Then they decided to play a game. They will pick a natural number N . Nova will sum up the odd numbers from 1 to N and and she will notedown LCM of R(R is defined in the picture) and the sum she calculated before. And Oliver will sum up the even numbers from 1 to N and and he will notedown LCM of S(S is defined in the picture) and the sum he calculated before. You must use the ceil value of R and S.
Now whose LCM is strictly greater than the other will win.If both of their LCM is equal Nova will win because Oliver is afraid of Nova.
$N.B.$ define the value of pi with $acos(-1)$.
$N.B.$ Sum of all odd number and sum of all even number will not exceed 10^18.
-----Input:-----
The first line contains an integer $T$ — the number of test cases in the input. Next, T test cases are given, one per line.
Each test case is a positive integer $N$ .
-----Output:-----
Print T answers to the test cases.
In each test cases,
If Oliver wins the game, print "Nova's gonna kill me" (without quotes) .
If Nova wins the game, print "YESS(sunglass emo)" (without quotes) .
-----Constraints-----
- $1 \leq T \leq 2000$
- $1 \leq N \leq 1845271$
-----Sample Input:-----
1
111
-----Sample Output:-----
YESS(sunglass emo)
I tried it in Python, but could not do it. Can you solve it? | import math
def lcm(a, b):
return (a*b)//gcd(a, b)
def gcd(a, b):
if b == 0:
return a
return gcd(b, a%b)
for _ in range(int(input())):
n = int(input())
na = math.ceil((2*n)/math.acos(-1))
nb = ((n+1)//2)**2
nlcm = lcm(na, nb)
oa = math.ceil(n/2)
ob = (n//2)*(n//2+1)
olcm = lcm(oa, ob)
if olcm > nlcm:
print("Nova's gonna kill me")
else:
print("YESS(sunglass emo)")
# cook your dish here | python | train | abovesol | codeparrot/apps | all |
I found an interesting problem on https://www.codechef.com/problems/MAXSC:
You are given N integer sequences A1, A2, ..., AN. Each of these sequences contains N elements. You should pick N elements, one from each sequence; let's denote the element picked from sequence Ai by Ei. For each i (2 ≤ i ≤ N), Ei should be strictly greater than Ei-1.
Compute the maximum possible value of E1 + E2 + ... + EN. If it's impossible to pick the elements E1, E2, ..., EN, print -1 instead.
-----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.
- N lines follow. For each valid i, the i-th of these lines contains N space-separated integers Ai1, Ai2, ..., AiN denoting the elements of the sequence Ai.
-----Output-----
For each test case, print a single line containing one integer — the maximum sum of picked elements.
-----Constraints-----
- 1 ≤ T ≤ 10
- 1 ≤ N ≤ 700
- 1 ≤ sum of N in all test-cases ≤ 3700
- 1 ≤ Aij ≤ 109 for each valid i, j
-----Subtasks-----
Subtask #1 (18 points): 1 ≤ Aij ≤ N for each valid i, j
Subtask #2 (82 points): original constraints
-----Example-----
Input:
1
3
1 2 3
4 5 6
7 8 9
Output:
18
-----Explanation-----
Example case 1: To maximise the score, pick 3 from the first row, 6 from the second row and 9 from the third row. The resulting sum is E1+E2+E3 = 3+6+9 = 18.
I tried it in Python, but could not do it. Can you solve it? | # cook your dish here
t=int(input())
for cases in range(t):
n=int(input())
lis=[]
for i in range(n):
lis1=sorted(list(map(int,input().split())))
lis.append(lis1)
summ=lis[-1][-1]
maxx=summ
c=1
for i in range(n-2,-1,-1):
for j in range(n-1,-1,-1):
if lis[i][j]<maxx:
maxx=lis[i][j]
c+=1
summ+=lis[i][j]
break
if c==n:
print(summ)
else:
print(-1)
print() | python | train | abovesol | codeparrot/apps | all |
Solve in Python:
Omkar is building a waterslide in his water park, and he needs your help to ensure that he does it as efficiently as possible.
Omkar currently has $n$ supports arranged in a line, the $i$-th of which has height $a_i$. Omkar wants to build his waterslide from the right to the left, so his supports must be nondecreasing in height in order to support the waterslide. In $1$ operation, Omkar can do the following: take any contiguous subsegment of supports which is nondecreasing by heights and add $1$ to each of their heights.
Help Omkar find the minimum number of operations he needs to perform to make his supports able to support his waterslide!
An array $b$ is a subsegment of an array $c$ if $b$ can be obtained from $c$ by deletion of several (possibly zero or all) elements from the beginning and several (possibly zero or all) elements from the end.
An array $b_1, b_2, \dots, b_n$ is called nondecreasing if $b_i\le b_{i+1}$ for every $i$ from $1$ to $n-1$.
-----Input-----
Each test contains multiple test cases. The first line contains the number of test cases $t$ ($1 \leq t \leq 100$). Description of the test cases follows.
The first line of each test case contains an integer $n$ ($1 \leq n \leq 2 \cdot 10^5$) — the number of supports Omkar has.
The second line of each test case contains $n$ integers $a_{1},a_{2},...,a_{n}$ $(0 \leq a_{i} \leq 10^9)$ — the heights of the supports.
It is guaranteed that the sum of $n$ over all test cases does not exceed $2 \cdot 10^5$.
-----Output-----
For each test case, output a single integer — the minimum number of operations Omkar needs to perform to make his supports able to support his waterslide.
-----Example-----
Input
3
4
5 3 2 5
5
1 2 3 5 3
3
1 1 1
Output
3
2
0
-----Note-----
The subarray with which Omkar performs the operation is bolded.
In the first test case:
First operation:
$[5, 3, \textbf{2}, 5] \to [5, 3, \textbf{3}, 5]$
Second operation:
$[5, \textbf{3}, \textbf{3}, 5] \to [5, \textbf{4}, \textbf{4}, 5]$
Third operation:
$[5,... | for _ in range(int(input())):
n=int(input())
a=list(map(int,input().split()))
ans=0
for i in range(1,n):
if a[i]<a[i-1]:
ans+=a[i-1]-a[i]
print(ans) | python | test | qsol | codeparrot/apps | all |
Solve in Python:
The chef was busy in solving algebra, he found some interesting results, that there are many numbers which can be formed by sum of some numbers which are prime. Chef wrote those numbers in dairy. Cheffina came and saw what the chef was doing. Cheffina immediately closed chef's dairy and for testing chef's memory, she starts asking numbers and chef needs to answer wheater given number N can be formed by the sum of K prime numbers if it yes then print 1 else print 0.
-----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, two integers $N, K$.
-----Output:-----
For each test case, output in a single line answer as 1 or 0.
-----Constraints-----
- $1 \leq T \leq 10^5$
- $2 \leq N \leq 10^5$
- $1 \leq K \leq 10^5$
-----Sample Input:-----
2
12 2
11 2
-----Sample Output:-----
1
0 | from math import sqrt
def isprime(n):
if (n % 2 == 0 and n > 2) or n == 1: return 0
else:
s = int(sqrt(n)) + 1
for i in range(3, s, 2):
if n % i == 0:
return 0
return 1
def find(N, K):
if (N < 2 * K):
return 0
if (K == 1):
return isprime(N)
if (K == 2):
if (N % 2 == 0):
return 1
return isprime(N - 2);
return 1
for _ in range(int(input())):
n, k = list(map(int, input().split()))
print(find(n, k)) | python | train | qsol | codeparrot/apps | all |
Solve in Python:
# Task
A noob programmer was given two simple tasks: sum and sort the elements of the given array `arr` = [a1, a2, ..., an].
He started with summing and did it easily, but decided to store the sum he found in some random position of the original array which was a bad idea. Now he needs to cope with the second task, sorting the original array arr, and it's giving him trouble since he modified it.
Given the array `shuffled`, consisting of elements a1, a2, ..., an, and their sumvalue in random order, return the sorted array of original elements a1, a2, ..., an.
# Example
For `shuffled = [1, 12, 3, 6, 2]`, the output should be `[1, 2, 3, 6]`.
`1 + 3 + 6 + 2 = 12`, which means that 1, 3, 6 and 2 are original elements of the array.
For `shuffled = [1, -3, -5, 7, 2]`, the output should be `[-5, -3, 2, 7]`.
# Input/Output
- `[input]` integer array `shuffled`
Array of at least two integers. It is guaranteed that there is an index i such that shuffled[i] = shuffled[0] + ... + shuffled[i - 1] + shuffled[i + 1] + ... + shuffled[n].
Constraints:
`2 ≤ shuffled.length ≤ 30,`
`-300 ≤ shuffled[i] ≤ 300.`
- `[output]` an integer array
A `sorted` array of shuffled.length - 1 elements. | def shuffled_array(a):
a.remove(sum(a) / 2)
return sorted(a) | python | train | qsol | codeparrot/apps | all |
I found an interesting problem on https://leetcode.com/problems/valid-anagram/:
Given two strings s and t , write a function to determine if t is an anagram of s.
Example 1:
Input: s = "anagram", t = "nagaram"
Output: true
Example 2:
Input: s = "rat", t = "car"
Output: false
Note:
You may assume the string contains only lowercase alphabets.
Follow up:
What if the inputs contain unicode characters? How would you adapt your solution to such case?
I tried it in Python, but could not do it. Can you solve it? | class Solution:
def isAnagram(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
if len(s)!=len(t):
return False
ssort=sorted(list(s))
tsort=sorted(list(t))
return ssort==tsort | python | train | abovesol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/702/A:
You are given array consisting of n integers. Your task is to find the maximum length of an increasing subarray of the given array.
A subarray is the sequence of consecutive elements of the array. Subarray is called increasing if each element of this subarray strictly greater than previous.
-----Input-----
The first line contains single positive integer n (1 ≤ n ≤ 10^5) — the number of integers.
The second line contains n positive integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10^9).
-----Output-----
Print the maximum length of an increasing subarray of the given array.
-----Examples-----
Input
5
1 7 2 11 15
Output
3
Input
6
100 100 100 100 100 100
Output
1
Input
3
1 2 3
Output
3
I tried it in Python, but could not do it. Can you solve it? | n=int(input())
l=input().split()
best=1
curr=1
for i in range (n-1):
if int(l[i])<int(l[i+1]):
curr+=1
else:
curr=1
best=max(best,curr)
print (best) | python | test | abovesol | codeparrot/apps | all |
Solve in Python:
PolandBall has such a convex polygon with n veritces that no three of its diagonals intersect at the same point. PolandBall decided to improve it and draw some red segments.
He chose a number k such that gcd(n, k) = 1. Vertices of the polygon are numbered from 1 to n in a clockwise way. PolandBall repeats the following process n times, starting from the vertex 1:
Assume you've ended last operation in vertex x (consider x = 1 if it is the first operation). Draw a new segment from vertex x to k-th next vertex in clockwise direction. This is a vertex x + k or x + k - n depending on which of these is a valid index of polygon's vertex.
Your task is to calculate number of polygon's sections after each drawing. A section is a clear area inside the polygon bounded with drawn diagonals or the polygon's sides.
-----Input-----
There are only two numbers in the input: n and k (5 ≤ n ≤ 10^6, 2 ≤ k ≤ n - 2, gcd(n, k) = 1).
-----Output-----
You should print n values separated by spaces. The i-th value should represent number of polygon's sections after drawing first i lines.
-----Examples-----
Input
5 2
Output
2 3 5 8 11
Input
10 3
Output
2 3 4 6 9 12 16 21 26 31
-----Note-----
The greatest common divisor (gcd) of two integers a and b is the largest positive integer that divides both a and b without a remainder.
For the first sample testcase, you should output "2 3 5 8 11". Pictures below correspond to situations after drawing lines. [Image] [Image] [Image] [Image] [Image] [Image] | def __starting_point():
n,k = list(map(int, input().strip().split()))
if k > n//2:
k = n - k
intersection = n * [0]
count = 1
done = False
i=0
result = []
for i in range(1,n+1):
nn = (i*k) // n
j = (i*k)%n
if j < k:
count += (2*nn )
else:
count += (2*nn +1)
result.append(count)
result[-1] -= 1
print(" ".join([str(r) for r in result]))
__starting_point() | python | test | qsol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/875/A:
Eighth-grader Vova is on duty today in the class. After classes, he went into the office to wash the board, and found on it the number n. He asked what is this number and the teacher of mathematics Inna Petrovna answered Vova that n is the answer to the arithmetic task for first-graders. In the textbook, a certain positive integer x was given. The task was to add x to the sum of the digits of the number x written in decimal numeral system.
Since the number n on the board was small, Vova quickly guessed which x could be in the textbook. Now he wants to get a program which will search for arbitrary values of the number n for all suitable values of x or determine that such x does not exist. Write such a program for Vova.
-----Input-----
The first line contains integer n (1 ≤ n ≤ 10^9).
-----Output-----
In the first line print one integer k — number of different values of x satisfying the condition.
In next k lines print these values in ascending order.
-----Examples-----
Input
21
Output
1
15
Input
20
Output
0
-----Note-----
In the first test case x = 15 there is only one variant: 15 + 1 + 5 = 21.
In the second test case there are no such x.
I tried it in Python, but could not do it. Can you solve it? | n=int(input())
m=[]
if n<=18:
a=0
else:
a=n-len(str(n))*9
for i in range(a,n):
x=i
for j in str(i):
x+=int(j)
if n==x:
m.append(i)
print(len(m))
[print(i) for i in m] | python | train | abovesol | codeparrot/apps | all |
Solve in Python:
Let's call an array $t$ dominated by value $v$ in the next situation.
At first, array $t$ should have at least $2$ elements. Now, let's calculate number of occurrences of each number $num$ in $t$ and define it as $occ(num)$. Then $t$ is dominated (by $v$) if (and only if) $occ(v) > occ(v')$ for any other number $v'$. For example, arrays $[1, 2, 3, 4, 5, 2]$, $[11, 11]$ and $[3, 2, 3, 2, 3]$ are dominated (by $2$, $11$ and $3$ respectevitely) but arrays $[3]$, $[1, 2]$ and $[3, 3, 2, 2, 1]$ are not.
Small remark: since any array can be dominated only by one number, we can not specify this number and just say that array is either dominated or not.
You are given array $a_1, a_2, \dots, a_n$. Calculate its shortest dominated subarray or say that there are no such subarrays.
The subarray of $a$ is a contiguous part of the array $a$, i. e. the array $a_i, a_{i + 1}, \dots, a_j$ for some $1 \le i \le j \le n$.
-----Input-----
The first line contains single integer $T$ ($1 \le T \le 1000$) — the number of test cases. Each test case consists of two lines.
The first line contains single integer $n$ ($1 \le n \le 2 \cdot 10^5$) — the length of the array $a$.
The second line contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le n$) — the corresponding values of the array $a$.
It's guaranteed that the total length of all arrays in one test doesn't exceed $2 \cdot 10^5$.
-----Output-----
Print $T$ integers — one per test case. For each test case print the only integer — the length of the shortest dominated subarray, or $-1$ if there are no such subarrays.
-----Example-----
Input
4
1
1
6
1 2 3 4 5 1
9
4 1 2 4 5 4 3 2 1
4
3 3 3 3
Output
-1
6
3
2
-----Note-----
In the first test case, there are no subarrays of length at least $2$, so the answer is $-1$.
In the second test case, the whole array is dominated (by $1$) and it's the only dominated subarray.
In the third test case, the subarray $a_4, a_5, a_6$ is the shortest dominated subarray.
In the fourth test case, all subarrays of length more... | import sys
T = int(sys.stdin.readline())
for i in range(T):
n = int(sys.stdin.readline())
array = sys.stdin.readline().split(" ")
lastSeen = [-10**6 for i in range(n + 1)]
best = 10**6
for j in range(len(array)):
if j - lastSeen[int(array[j])] < best:
best = j - lastSeen[int(array[j])]
lastSeen[int(array[j])] = j
if best == 10**6:
print(-1)
else:
print(best + 1) | python | test | qsol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/1081/A:
Chouti was doing a competitive programming competition. However, after having all the problems accepted, he got bored and decided to invent some small games.
He came up with the following game. The player has a positive integer $n$. Initially the value of $n$ equals to $v$ and the player is able to do the following operation as many times as the player want (possibly zero): choose a positive integer $x$ that $x<n$ and $x$ is not a divisor of $n$, then subtract $x$ from $n$. The goal of the player is to minimize the value of $n$ in the end.
Soon, Chouti found the game trivial. Can you also beat the game?
-----Input-----
The input contains only one integer in the first line: $v$ ($1 \le v \le 10^9$), the initial value of $n$.
-----Output-----
Output a single integer, the minimum value of $n$ the player can get.
-----Examples-----
Input
8
Output
1
Input
1
Output
1
-----Note-----
In the first example, the player can choose $x=3$ in the first turn, then $n$ becomes $5$. He can then choose $x=4$ in the second turn to get $n=1$ as the result. There are other ways to get this minimum. However, for example, he cannot choose $x=2$ in the first turn because $2$ is a divisor of $8$.
In the second example, since $n=1$ initially, the player can do nothing.
I tried it in Python, but could not do it. Can you solve it? | n = int(input())
if n == 2:
print(2)
else:
print(1) | python | test | abovesol | codeparrot/apps | all |
I found an interesting problem on https://www.codewars.com/kata/550cc572b9e7b563be00054f:
Scheduling is how the processor decides which jobs(processes) get to use the processor and for how long. This can cause a lot of problems. Like a really long process taking the entire CPU and freezing all the other processes. One solution is Shortest Job First(SJF), which today you will be implementing.
SJF works by, well, letting the shortest jobs take the CPU first. If the jobs are the same size then it is First In First Out (FIFO). The idea is that the shorter jobs will finish quicker, so theoretically jobs won't get frozen because of large jobs. (In practice they're frozen because of small jobs).
You will be implementing:
```python
def SJF(jobs, index)
```
It takes in:
1. "jobs" a non-empty array of positive integers. They represent the clock-cycles(cc) needed to finish the job.
2. "index" a positive integer. That represents the job we're interested in.
SJF returns:
1. A positive integer representing the cc it takes to complete the job at index.
Here's an example:
```
SJF([3, 10, 20, 1, 2], 0)
at 0cc [3, 10, 20, 1, 2] jobs[3] starts
at 1cc [3, 10, 20, 0, 2] jobs[3] finishes, jobs[4] starts
at 3cc [3, 10, 20, 0, 0] jobs[4] finishes, jobs[0] starts
at 6cc [0, 10, 20, 0, 0] jobs[0] finishes
```
so:
```
SJF([3,10,20,1,2], 0) == 6
```
I tried it in Python, but could not do it. Can you solve it? | def SJF(jobs, index):
return sum(n for i, n in enumerate(jobs) if n < jobs[index] + (i <= index)) | python | train | abovesol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/1152/D:
Neko is playing with his toys on the backyard of Aki's house. Aki decided to play a prank on him, by secretly putting catnip into Neko's toys. Unfortunately, he went overboard and put an entire bag of catnip into the toys...
It took Neko an entire day to turn back to normal. Neko reported to Aki that he saw a lot of weird things, including a trie of all correct bracket sequences of length $2n$.
The definition of correct bracket sequence is as follows: The empty sequence is a correct bracket sequence, If $s$ is a correct bracket sequence, then $(\,s\,)$ is a correct bracket sequence, If $s$ and $t$ are a correct bracket sequence, then $st$ is also a correct bracket sequence.
For example, the strings "(())", "()()" form a correct bracket sequence, while ")(" and "((" not.
Aki then came up with an interesting problem: What is the size of the maximum matching (the largest set of edges such that there are no two edges with a common vertex) in this trie? Since the answer can be quite large, print it modulo $10^9 + 7$.
-----Input-----
The only line contains a single integer $n$ ($1 \le n \le 1000$).
-----Output-----
Print exactly one integer — the size of the maximum matching in the trie. Since the answer can be quite large, print it modulo $10^9 + 7$.
-----Examples-----
Input
1
Output
1
Input
2
Output
3
Input
3
Output
9
-----Note-----
The pictures below illustrate tries in the first two examples (for clarity, the round brackets are replaced with angle brackets). The maximum matching is highlighted with blue. [Image] [Image]
I tried it in Python, but could not do it. Can you solve it? | ans = [... | python | test | abovesol | codeparrot/apps | all |
I found an interesting problem on https://www.codewars.com/kata/5a53a17bfd56cb9c14000003:
# Definition
**_Disarium number_** is the number that *The sum of its digits powered with their respective positions is equal to the number itself*.
____
# Task
**_Given_** a number, **_Find if it is Disarium or not_** .
____
# Warm-up (Highly recommended)
# [Playing With Numbers Series](https://www.codewars.com/collections/playing-with-numbers)
___
# Notes
* **_Number_** *passed is always* **_Positive_** .
* **_Return_** *the result as* **_String_**
___
# Input >> Output Examples
```
disariumNumber(89) ==> return "Disarium !!"
```
## **_Explanation_**:
* Since , **_8^(1) + 9^(2) = 89_** , thus *output* is `"Disarium !!"`
___
```
disariumNumber(564) ==> return "Not !!"
```
## **_Explanation_**:
Since , **_5^(1) + 6^(2) + 4^(3) = 105 != 564_** , thus *output* is `"Not !!"`
___
___
___
# [Playing with Numbers Series](https://www.codewars.com/collections/playing-with-numbers)
# [Playing With Lists/Arrays Series](https://www.codewars.com/collections/playing-with-lists-slash-arrays)
# [For More Enjoyable Katas](http://www.codewars.com/users/MrZizoScream/authored)
___
## ALL translations are welcomed
## Enjoy Learning !!
# Zizou
I tried it in Python, but could not do it. Can you solve it? | def disarium_number(number):
newNumber = 0
for index, value in enumerate(str(number)):
newNumber += int(value)**(int(index)+1)
if newNumber == number:
return "Disarium !!"
return "Not !!" | python | train | abovesol | codeparrot/apps | all |
I found an interesting problem on https://www.codewars.com/kata/5c46ea433dd41b19af1ca3b3:
### Description
As hex values can include letters `A` through to `F`, certain English words can be spelled out, such as `CAFE`, `BEEF`, or `FACADE`.
This vocabulary can be extended by using numbers to represent other letters, such as `5EAF00D`, or `DEC0DE5`.
Given a string, your task is to return the decimal sum of all words in the string that can be interpreted as such hex values.
### Example
Working with the string `BAG OF BEES`:
* `BAG` ==> `0` as it is not a valid hex value
* `OF` ==> `0F` ==> `15`
* `BEES` ==> `BEE5` ==> `48869`
So `hex_word_sum('BAG OF BEES')` returns the sum of these, `48884`.
### Notes
* Inputs are all uppercase and contain no punctuation
* `0` can be substituted for `O`
* `5` can be substituted for `S`
I tried it in Python, but could not do it. Can you solve it? | def hex_word_sum(string):
string = string.upper().replace('S', '5')
string = string.replace('O', '0')
sum = 0
for word in string.split(' '):
try:
sum += int(word.strip(), 16)
except:
pass
return sum | python | train | abovesol | codeparrot/apps | all |
Solve in Python:
You are given three positive integers $n$, $a$ and $b$. You have to construct a string $s$ of length $n$ consisting of lowercase Latin letters such that each substring of length $a$ has exactly $b$ distinct letters. It is guaranteed that the answer exists.
You have to answer $t$ independent test cases.
Recall that the substring $s[l \dots r]$ is the string $s_l, s_{l+1}, \dots, s_{r}$ and its length is $r - l + 1$. In this problem you are only interested in substrings of length $a$.
-----Input-----
The first line of the input contains one integer $t$ ($1 \le t \le 2000$) — the number of test cases. Then $t$ test cases follow.
The only line of a test case contains three space-separated integers $n$, $a$ and $b$ ($1 \le a \le n \le 2000, 1 \le b \le \min(26, a)$), where $n$ is the length of the required string, $a$ is the length of a substring and $b$ is the required number of distinct letters in each substring of length $a$.
It is guaranteed that the sum of $n$ over all test cases does not exceed $2000$ ($\sum n \le 2000$).
-----Output-----
For each test case, print the answer — such a string $s$ of length $n$ consisting of lowercase Latin letters that each substring of length $a$ has exactly $b$ distinct letters. If there are multiple valid answers, print any of them. It is guaranteed that the answer exists.
-----Example-----
Input
4
7 5 3
6 1 1
6 6 1
5 2 2
Output
tleelte
qwerty
vvvvvv
abcde
-----Note-----
In the first test case of the example, consider all the substrings of length $5$: "tleel": it contains $3$ distinct (unique) letters, "leelt": it contains $3$ distinct (unique) letters, "eelte": it contains $3$ distinct (unique) letters. | t = int(input(''))
c = []
for i in range(97,123,1):
c.append(chr(i))
for _ in range(t):
n,a,b = list(map(int,input('').split(' ')))
s = ''
for i in range(n):
s = s+c[i%b]
print(s) | python | test | qsol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/1313/B:
Nikolay has only recently started in competitive programming, but already qualified to the finals of one prestigious olympiad. There going to be $n$ participants, one of whom is Nikolay. Like any good olympiad, it consists of two rounds. Tired of the traditional rules, in which the participant who solved the largest number of problems wins, the organizers came up with different rules.
Suppose in the first round participant A took $x$-th place and in the second round — $y$-th place. Then the total score of the participant A is sum $x + y$. The overall place of the participant A is the number of participants (including A) having their total score less than or equal to the total score of A. Note, that some participants may end up having a common overall place. It is also important to note, that in both the first and the second round there were no two participants tying at a common place. In other words, for every $i$ from $1$ to $n$ exactly one participant took $i$-th place in first round and exactly one participant took $i$-th place in second round.
Right after the end of the Olympiad, Nikolay was informed that he got $x$-th place in first round and $y$-th place in the second round. Nikolay doesn't know the results of other participants, yet he wonders what is the minimum and maximum place he can take, if we consider the most favorable and unfavorable outcome for him. Please help Nikolay to find the answer to this question.
-----Input-----
The first line contains an integer $t$ ($1 \le t \le 100$) — the number of test cases to solve.
Each of the following $t$ lines contains integers $n$, $x$, $y$ ($1 \leq n \leq 10^9$, $1 \le x, y \le n$) — the number of participants in the olympiad, the place that Nikolay took in the first round and the place that Nikolay took in the second round.
-----Output-----
Print two integers — the minimum and maximum possible overall place Nikolay could take.
-----Examples-----
Input
1
5 1 3
Output
1 3
Input
1
6 3 4
Output
2 6
-----Note-----
Explanation for the first...
I tried it in Python, but could not do it. Can you solve it? | t = int(input())
for _ in range(t):
n, x, y = [int(item) for item in input().split()]
total = x + y
maximum = min(x + y - 1, n)
minimum = min(n - min((2 * n - total), n) + 1, n)
print(minimum, maximum) | python | test | abovesol | codeparrot/apps | all |
Solve in Python:
Mike and Joe are fratboys that love beer and games that involve drinking. They play the following game: Mike chugs one beer, then Joe chugs 2 beers, then Mike chugs 3 beers, then Joe chugs 4 beers, and so on. Once someone can't drink what he is supposed to drink, he loses.
Mike can chug at most A beers in total (otherwise he would pass out), while Joe can chug at most B beers in total. Who will win the game?
Write the function ```game(A,B)``` that returns the winner, ```"Mike"``` or ```"Joe"``` accordingly, for any given integer values of A and B.
Note: If either Mike or Joe cannot drink at least 1 beer, return the string ```"Non-drinkers can't play"```. | def game(a, b):
if a * b:
c = int(a ** 0.5)
return ('Mike', 'Joe')[c * (c + 1) <= b]
return "Non-drinkers can't play" | python | train | qsol | codeparrot/apps | all |
Solve in Python:
Consider the sequence `a(1) = 7, a(n) = a(n-1) + gcd(n, a(n-1)) for n >= 2`:
`7, 8, 9, 10, 15, 18, 19, 20, 21, 22, 33, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 69, 72, 73...`.
Let us take the differences between successive elements of the sequence and
get a second sequence `g: 1, 1, 1, 5, 3, 1, 1, 1, 1, 11, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 23, 3, 1...`.
For the sake of uniformity of the lengths of sequences **we add** a `1` at the head of g:
`g: 1, 1, 1, 1, 5, 3, 1, 1, 1, 1, 11, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 23, 3, 1...`
Removing the 1s gives a third sequence:
`p: 5, 3, 11, 3, 23, 3...`
where you can see prime numbers.
#Task:
Write functions:
```
1: an(n) with parameter n: returns the first n terms of the series a(n) (not tested)
2: gn(n) with parameter n: returns the first n terms of the series g(n) (not tested)
3: countOnes(n) with parameter n: returns the number of 1 in g(n)
(don't forget to add a `1` at the head) # (tested)
4: p(n) with parameter n: returns an array of n unique prime numbers (not tested)
5: maxp(n) with parameter n: returns the biggest prime number of the sequence pn(n) # (tested)
6: anOver(n) with parameter n: returns an array (n terms) of the a(i)/i for every i such g(i) != 1 (not tested but interesting result)
7: anOverAverage(n) with parameter n: returns as an *integer* the average of anOver(n) (tested)
```
#Note:
You can write directly functions `3:`, `5:` and `7:`. There is no need to write functions `1:`, `2:`, `4:` `6:`
except out of pure curiosity. | def count_ones(n):
a, ones = 7, 1
for i in range(2, n+1):
b = a + gcd(i, a)
if b == a + 1: ones += 1
a = b
return ones
def max_pn(n):
a, p, i = 7, {1}, 1
while len(p) < n + 1:
i += 1
b = a + gcd(i, a)
p.add(b - a)
a = b
return max(p)
def an_over_average(n):
return 3
def gcd(a, b):
while b:
a, b = b, a % b
return a | python | train | qsol | codeparrot/apps | all |
Solve in Python:
A palindrome is a word, phrase, number, or other sequence of characters which reads the same backward as forward. Examples of numerical palindromes are:
* 232
* 110011
* 54322345
Complete the function to test if the given number (`num`) **can be rearranged** to form a numerical palindrome or not. Return a boolean (`true` if it can be rearranged to a palindrome, and `false` if it cannot). Return `"Not valid"` if the input is not an integer or is less than 0.
For this kata, single digit numbers are **NOT** considered numerical palindromes.
## Examples
```
5 => false
2121 => true
1331 => true
3357665 => true
1294 => false
"109982" => "Not valid"
-42 => "Not valid"
``` | def palindrome(num):
s = str(num)
return "Not valid" if not isinstance(num, int) or num < 0 \
else num > 10 and sum(s.count(d) % 2 > 0 for d in set(s)) < 2 | python | train | qsol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/1183/E:
The only difference between the easy and the hard versions is constraints.
A subsequence is a string that can be derived from another string by deleting some or no symbols without changing the order of the remaining symbols. Characters to be deleted are not required to go successively, there can be any gaps between them. For example, for the string "abaca" the following strings are subsequences: "abaca", "aba", "aaa", "a" and "" (empty string). But the following strings are not subsequences: "aabaca", "cb" and "bcaa".
You are given a string $s$ consisting of $n$ lowercase Latin letters.
In one move you can take any subsequence $t$ of the given string and add it to the set $S$. The set $S$ can't contain duplicates. This move costs $n - |t|$, where $|t|$ is the length of the added subsequence (i.e. the price equals to the number of the deleted characters).
Your task is to find out the minimum possible total cost to obtain a set $S$ of size $k$ or report that it is impossible to do so.
-----Input-----
The first line of the input contains two integers $n$ and $k$ ($1 \le n, k \le 100$) — the length of the string and the size of the set, correspondingly.
The second line of the input contains a string $s$ consisting of $n$ lowercase Latin letters.
-----Output-----
Print one integer — if it is impossible to obtain the set $S$ of size $k$, print -1. Otherwise, print the minimum possible total cost to do it.
-----Examples-----
Input
4 5
asdf
Output
4
Input
5 6
aaaaa
Output
15
Input
5 7
aaaaa
Output
-1
Input
10 100
ajihiushda
Output
233
-----Note-----
In the first example we can generate $S$ = { "asdf", "asd", "adf", "asf", "sdf" }. The cost of the first element in $S$ is $0$ and the cost of the others is $1$. So the total cost of $S$ is $4$.
I tried it in Python, but could not do it. Can you solve it? | import sys
input = sys.stdin.readline
n,W=list(map(int,input().split()))
s=input().strip()
NEXTLIST=[[n]*26 for i in range(n+1)]
for i in range(n-1,-1,-1):
for j in range(26):
NEXTLIST[i][j]=NEXTLIST[i+1][j]
NEXTLIST[i][ord(s[i])-97]=i
DP=[[0]*(n+1) for i in range(n+1)]
DP[0][0]=1
for i in range(n):
for j in range(26):
if NEXTLIST[i][j]!=n:
for k in range(n):
DP[NEXTLIST[i][j]+1][k+1]+=DP[i][k]
#print(DP)
HLIST=[0]*(n+1)
for i in range(n+1):
for j in range(n+1):
HLIST[j]+=DP[i][j]
#print(HLIST)
ANS=0
for i in range(n,-1,-1):
#print(i,W)
if W>HLIST[i]:
ANS+=(n-i)*HLIST[i]
W-=HLIST[i]
else:
ANS+=W*(n-i)
print(ANS)
return
else:
print(-1) | python | test | abovesol | codeparrot/apps | all |
Solve in Python:
Helen works in Metropolis airport. She is responsible for creating a departure schedule. There are n flights that must depart today, the i-th of them is planned to depart at the i-th minute of the day.
Metropolis airport is the main transport hub of Metropolia, so it is difficult to keep the schedule intact. This is exactly the case today: because of technical issues, no flights were able to depart during the first k minutes of the day, so now the new departure schedule must be created.
All n scheduled flights must now depart at different minutes between (k + 1)-th and (k + n)-th, inclusive. However, it's not mandatory for the flights to depart in the same order they were initially scheduled to do so — their order in the new schedule can be different. There is only one restriction: no flight is allowed to depart earlier than it was supposed to depart in the initial schedule.
Helen knows that each minute of delay of the i-th flight costs airport c_{i} burles. Help her find the order for flights to depart in the new schedule that minimizes the total cost for the airport.
-----Input-----
The first line contains two integers n and k (1 ≤ k ≤ n ≤ 300 000), here n is the number of flights, and k is the number of minutes in the beginning of the day that the flights did not depart.
The second line contains n integers c_1, c_2, ..., c_{n} (1 ≤ c_{i} ≤ 10^7), here c_{i} is the cost of delaying the i-th flight for one minute.
-----Output-----
The first line must contain the minimum possible total cost of delaying the flights.
The second line must contain n different integers t_1, t_2, ..., t_{n} (k + 1 ≤ t_{i} ≤ k + n), here t_{i} is the minute when the i-th flight must depart. If there are several optimal schedules, print any of them.
-----Example-----
Input
5 2
4 2 1 10 2
Output
20
3 6 7 4 5
-----Note-----
Let us consider sample test. If Helen just moves all flights 2 minutes later preserving the order, the total cost of delaying the flights would be (3 - 1)·4 + (4 - 2)·2 + (5 - 3)·1 + (6 - 4)·10 +... | from heapq import heappush,heappop,heapify
n,k=list(map(int,input().split()))
*l,=list(map(int,input().split()))
q=[(-l[i],i)for i in range(k)]
heapify(q)
a=[0]*n
s=0
for i in range(k,n) :
heappush(q,(-l[i],i))
x,j=heappop(q)
s-=x*(i-j)
a[j]=i+1
for i in range(n,n+k) :
x,j=heappop(q)
s-=x*(i-j)
a[j]=i+1
print(s)
print(' '.join(map(str,a))) | python | train | qsol | codeparrot/apps | all |
Solve in Python:
You are given an array A of strings.
A move onto S consists of swapping any two even indexed characters of S, or any two odd indexed characters of S.
Two strings S and T are special-equivalent if after any number of moves onto S, S == T.
For example, S = "zzxy" and T = "xyzz" are special-equivalent because we may make the moves "zzxy" -> "xzzy" -> "xyzz" that swap S[0] and S[2], then S[1] and S[3].
Now, a group of special-equivalent strings from A is a non-empty subset of A such that:
Every pair of strings in the group are special equivalent, and;
The group is the largest size possible (ie., there isn't a string S not in the group such that S is special equivalent to every string in the group)
Return the number of groups of special-equivalent strings from A.
Example 1:
Input: ["abcd","cdab","cbad","xyzz","zzxy","zzyx"]
Output: 3
Explanation:
One group is ["abcd", "cdab", "cbad"], since they are all pairwise special equivalent, and none of the other strings are all pairwise special equivalent to these.
The other two groups are ["xyzz", "zzxy"] and ["zzyx"]. Note that in particular, "zzxy" is not special equivalent to "zzyx".
Example 2:
Input: ["abc","acb","bac","bca","cab","cba"]
Output: 3
Note:
1 <= A.length <= 1000
1 <= A[i].length <= 20
All A[i] have the same length.
All A[i] consist of only lowercase letters. | class Solution:
def numSpecialEquivGroups(self, A: List[str]) -> int:
# set1 = set()
even_set = []
odd_set = []
for i in A:
even = []
odd = []
for j in range(len(i)):
if j %2 == 0:
even.append(i[j])
else:
odd.append(i[j])
even.sort()
odd.sort()
if even in even_set:
k = []
for p,values in enumerate(even_set):
if even == values:
k += [p]
flag = 0
for p in k:
if odd_set[p] == odd:
flag = 1
break
if flag == 0:
even_set.append(even)
odd_set.append(odd)
else:
even_set.append(even)
odd_set.append(odd)
return len(even_set) | python | train | qsol | codeparrot/apps | all |
Solve in Python:
Mobile Display Keystrokes
Do you remember the old mobile display keyboards? Do you also remember how inconvenient it was to write on it?
Well, here you have to calculate how much keystrokes you have to do for a specific word.
This is the layout:
Return the amount of keystrokes of input str (! only letters, digits and special characters in lowercase included in layout without whitespaces !)
e.g:
mobileKeyboard("123") => 3 (1+1+1)
mobileKeyboard("abc") => 9 (2+3+4)
mobileKeyboard("codewars") => 26 (4+4+2+3+2+2+4+5) | def mobile_keyboard(s):
a = "12abc3def4ghi5jkl6mno7pqrs8tuv9wxyz*0#"
b = "11234123412341234123412345123412345111"
d = {x: int(y) for x, y in zip(a, b)}
return sum(d[x] for x in s) | python | train | qsol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/1417/B:
RedDreamer has an array $a$ consisting of $n$ non-negative integers, and an unlucky integer $T$.
Let's denote the misfortune of array $b$ having length $m$ as $f(b)$ — the number of pairs of integers $(i, j)$ such that $1 \le i < j \le m$ and $b_i + b_j = T$. RedDreamer has to paint each element of $a$ into one of two colors, white and black (for each element, the color is chosen independently), and then create two arrays $c$ and $d$ so that all white elements belong to $c$, and all black elements belong to $d$ (it is possible that one of these two arrays becomes empty). RedDreamer wants to paint the elements in such a way that $f(c) + f(d)$ is minimum possible.
For example:
if $n = 6$, $T = 7$ and $a = [1, 2, 3, 4, 5, 6]$, it is possible to paint the $1$-st, the $4$-th and the $5$-th elements white, and all other elements black. So $c = [1, 4, 5]$, $d = [2, 3, 6]$, and $f(c) + f(d) = 0 + 0 = 0$; if $n = 3$, $T = 6$ and $a = [3, 3, 3]$, it is possible to paint the $1$-st element white, and all other elements black. So $c = [3]$, $d = [3, 3]$, and $f(c) + f(d) = 0 + 1 = 1$.
Help RedDreamer to paint the array optimally!
-----Input-----
The first line contains one integer $t$ ($1 \le t \le 1000$) — the number of test cases. Then $t$ test cases follow.
The first line of each test case contains two integers $n$ and $T$ ($1 \le n \le 10^5$, $0 \le T \le 10^9$) — the number of elements in the array and the unlucky integer, respectively.
The second line contains $n$ integers $a_1$, $a_2$, ..., $a_n$ ($0 \le a_i \le 10^9$) — the elements of the array.
The sum of $n$ over all test cases does not exceed $10^5$.
-----Output-----
For each test case print $n$ integers: $p_1$, $p_2$, ..., $p_n$ (each $p_i$ is either $0$ or $1$) denoting the colors. If $p_i$ is $0$, then $a_i$ is white and belongs to the array $c$, otherwise it is black and belongs to the array $d$.
If there are multiple answers that minimize the value of $f(c) + f(d)$, print any of them.
-----Example-----
Input
2
6 7
1 2 3 4 5 6
3 6
3...
I tried it in Python, but could not do it. Can you solve it? | import sys
import math
input = sys.stdin.readline
t = int(input())
for _ in range(t):
n,k = list(map(int, input().split()))
arr = list(map(int, input().split()))
alt = 0
ans = []
for i in range(len(arr)):
if k%2==1:
if arr[i] < k/2:
ans.append(0)
else:
ans.append(1)
else:
if arr[i] == k//2:
ans.append(alt%2)
alt += 1
elif arr[i] < k//2:
ans.append(0)
else:
ans.append(1)
print(*ans) | python | train | abovesol | codeparrot/apps | all |
I found an interesting problem on https://www.codewars.com/kata/57f4ccf0ab9a91c3d5000054:
Lot of junior developer can be stuck when they need to change the access permission to a file or a directory in an Unix-like operating systems.
To do that they can use the `chmod` command and with some magic trick they can change the permissionof a file or a directory. For more information about the `chmod` command you can take a look at the [wikipedia page](https://en.wikipedia.org/wiki/Chmod).
`chmod` provides two types of syntax that can be used for changing permissions. An absolute form using octal to denote which permissions bits are set e.g: 766.
Your goal in this kata is to define the octal you need to use in order to set yout permission correctly.
Here is the list of the permission you can set with the octal representation of this one.
- User
- read (4)
- write (2)
- execute (1)
- Group
- read (4)
- write (2)
- execute (1)
- Other
- read (4)
- write (2)
- execute (1)
The method take a hash in argument this one can have a maximum of 3 keys (`owner`,`group`,`other`). Each key will have a 3 chars string to represent the permission, for example the string `rw-` say that the user want the permission `read`, `write` without the `execute`.
If a key is missing set the permission to `---`
**Note**: `chmod` allow you to set some special flags too (`setuid`, `setgid`, `sticky bit`) but to keep some simplicity for this kata we will ignore this one.
I tried it in Python, but could not do it. Can you solve it? | def chmod_calculator(perm):
return str(sum([wbin(perm[k]) * {"user":100, "group":10, "other":1}[k] for k in perm])).zfill(3)
def wbin(w):
return int(w.translate(str.maketrans('rwx-', '1110')), 2) | python | train | abovesol | codeparrot/apps | all |
Solve in Python:
One of Arkady's friends works at a huge radio telescope. A few decades ago the telescope has sent a signal $s$ towards a faraway galaxy. Recently they've received a response $t$ which they believe to be a response from aliens! The scientists now want to check if the signal $t$ is similar to $s$.
The original signal $s$ was a sequence of zeros and ones (everyone knows that binary code is the universe-wide language). The returned signal $t$, however, does not look as easy as $s$, but the scientists don't give up! They represented $t$ as a sequence of English letters and say that $t$ is similar to $s$ if you can replace all zeros in $s$ with some string $r_0$ and all ones in $s$ with some other string $r_1$ and obtain $t$. The strings $r_0$ and $r_1$ must be different and non-empty.
Please help Arkady's friend and find the number of possible replacements for zeros and ones (the number of pairs of strings $r_0$ and $r_1$) that transform $s$ to $t$.
-----Input-----
The first line contains a string $s$ ($2 \le |s| \le 10^5$) consisting of zeros and ones — the original signal.
The second line contains a string $t$ ($1 \le |t| \le 10^6$) consisting of lowercase English letters only — the received signal.
It is guaranteed, that the string $s$ contains at least one '0' and at least one '1'.
-----Output-----
Print a single integer — the number of pairs of strings $r_0$ and $r_1$ that transform $s$ to $t$.
In case there are no such pairs, print $0$.
-----Examples-----
Input
01
aaaaaa
Output
4
Input
001
kokokokotlin
Output
2
-----Note-----
In the first example, the possible pairs $(r_0, r_1)$ are as follows: "a", "aaaaa" "aa", "aaaa" "aaaa", "aa" "aaaaa", "a"
The pair "aaa", "aaa" is not allowed, since $r_0$ and $r_1$ must be different.
In the second example, the following pairs are possible: "ko", "kokotlin" "koko", "tlin" | import sys
from math import *
def minp():
return sys.stdin.readline().strip()
def mint():
return int(minp())
def mints():
return map(int, minp().split())
def add(a,b):
return (a+b)%1000000007
def sub(a,b):
return (a+1000000007-b)%1000000007
def mul(a,b):
return (a*b)%1000000007
p = 102367
s = list(map(int,minp()))
t = list(map(ord,minp()))
h = [0]*(len(t)+1)
pp = [1]*(len(t)+1)
for i in range(len(t)):
h[i+1] = add(mul(h[i], p), t[i])
pp[i+1] = mul(pp[i], p)
def cmp(a, b, l):
if a > b:
a, b = b, a
h1 = sub(h[a+l], mul(h[a], pp[l]))
h2 = sub(h[b+l], mul(h[b], pp[l]))
return h2 == h1
c = [0,0]
idx = [-1,-1]
for i in range(len(s)):
c[s[i]] += 1
if idx[s[i]] < 0:
idx[s[i]] = i
Mv = max(c)
mv = min(c)
Mi = c.index(Mv)
mi = (Mi^1)
lt = len(t)
sp = [0,0]
res = 0
for k in range(1,lt//Mv+1):
l = [0,0]
x = (lt-k*Mv)//mv
if x > 0 and x*mv + k*Mv == lt:
l[Mi] = k
l[mi] = x
if idx[0] < idx[1]:
sp[0] = 0
sp[1] = idx[1]*l[0]
else:
sp[1] = 0
sp[0] = idx[0]*l[1]
ok = True
j = 0
for i in range(len(s)):
if not cmp(sp[s[i]], j, l[s[i]]):
ok = False
break
j += l[s[i]]
if l[0] == l[1] and cmp(sp[0], sp[1], l[0]):
ok = False
if ok:
res += 1
print(res) | python | test | qsol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/979/C:
Kuro is living in a country called Uberland, consisting of $n$ towns, numbered from $1$ to $n$, and $n - 1$ bidirectional roads connecting these towns. It is possible to reach each town from any other. Each road connects two towns $a$ and $b$. Kuro loves walking and he is planning to take a walking marathon, in which he will choose a pair of towns $(u, v)$ ($u \neq v$) and walk from $u$ using the shortest path to $v$ (note that $(u, v)$ is considered to be different from $(v, u)$).
Oddly, there are 2 special towns in Uberland named Flowrisa (denoted with the index $x$) and Beetopia (denoted with the index $y$). Flowrisa is a town where there are many strong-scent flowers, and Beetopia is another town where many bees live. In particular, Kuro will avoid any pair of towns $(u, v)$ if on the path from $u$ to $v$, he reaches Beetopia after he reached Flowrisa, since the bees will be attracted with the flower smell on Kuro’s body and sting him.
Kuro wants to know how many pair of city $(u, v)$ he can take as his route. Since he’s not really bright, he asked you to help him with this problem.
-----Input-----
The first line contains three integers $n$, $x$ and $y$ ($1 \leq n \leq 3 \cdot 10^5$, $1 \leq x, y \leq n$, $x \ne y$) - the number of towns, index of the town Flowrisa and index of the town Beetopia, respectively.
$n - 1$ lines follow, each line contains two integers $a$ and $b$ ($1 \leq a, b \leq n$, $a \ne b$), describes a road connecting two towns $a$ and $b$.
It is guaranteed that from each town, we can reach every other town in the city using the given roads. That is, the given map of towns and roads is a tree.
-----Output-----
A single integer resembles the number of pair of towns $(u, v)$ that Kuro can use as his walking route.
-----Examples-----
Input
3 1 3
1 2
2 3
Output
5
Input
3 1 3
1 2
1 3
Output
4
-----Note-----
On the first example, Kuro can choose these pairs: $(1, 2)$: his route would be $1 \rightarrow 2$, $(2, 3)$: his route would be $2 \rightarrow 3$, $(3, 2)$: his route...
I tried it in Python, but could not do it. Can you solve it? | from collections import defaultdict
n,x,y = list(map(int,input().split()))
graph = defaultdict(list)
vis = [False for i in range(n+1)]
mat = [False for i in range(n+1)]
subtree = [0 for i in range(n+1)]
for i in range(n-1):
u,v = list(map(int,input().split()))
graph[u].append(v)
graph[v].append(u)
q = []
cur = 0
for v in graph[x]:
if v!=y:
q.append([v,v])
else:
cur = v
vis[x] = 1
while q!=[]:
temp = q.pop()
u,v = temp
vis[u] = True
subtree[v]+=1
for node in graph[u]:
if vis[node]==False:
if node!=y:
q.append([node,v])
else:
cur = v
val = sum(subtree)
val1 = (val+1-subtree[cur])
val2 = n-(sum(subtree)+1)
val = val1*val2
print(n*(n-1)-val) | python | test | abovesol | codeparrot/apps | all |
Solve in Python:
Vasya has a sequence $a$ consisting of $n$ integers $a_1, a_2, \dots, a_n$. Vasya may pefrom the following operation: choose some number from the sequence and swap any pair of bits in its binary representation. For example, Vasya can transform number $6$ $(\dots 00000000110_2)$ into $3$ $(\dots 00000000011_2)$, $12$ $(\dots 000000001100_2)$, $1026$ $(\dots 10000000010_2)$ and many others. Vasya can use this operation any (possibly zero) number of times on any number from the sequence.
Vasya names a sequence as good one, if, using operation mentioned above, he can obtain the sequence with bitwise exclusive or of all elements equal to $0$.
For the given sequence $a_1, a_2, \ldots, a_n$ Vasya'd like to calculate number of integer pairs $(l, r)$ such that $1 \le l \le r \le n$ and sequence $a_l, a_{l + 1}, \dots, a_r$ is good.
-----Input-----
The first line contains a single integer $n$ ($1 \le n \le 3 \cdot 10^5$) — length of the sequence.
The second line contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 10^{18}$) — the sequence $a$.
-----Output-----
Print one integer — the number of pairs $(l, r)$ such that $1 \le l \le r \le n$ and the sequence $a_l, a_{l + 1}, \dots, a_r$ is good.
-----Examples-----
Input
3
6 7 14
Output
2
Input
4
1 2 1 16
Output
4
-----Note-----
In the first example pairs $(2, 3)$ and $(1, 3)$ are valid. Pair $(2, 3)$ is valid since $a_2 = 7 \rightarrow 11$, $a_3 = 14 \rightarrow 11$ and $11 \oplus 11 = 0$, where $\oplus$ — bitwise exclusive or. Pair $(1, 3)$ is valid since $a_1 = 6 \rightarrow 3$, $a_2 = 7 \rightarrow 13$, $a_3 = 14 \rightarrow 14$ and $3 \oplus 13 \oplus 14 = 0$.
In the second example pairs $(1, 2)$, $(2, 3)$, $(3, 4)$ and $(1, 4)$ are valid. | #!/usr/bin/env python3
import sys
def rint():
return list(map(int, sys.stdin.readline().split()))
#lines = stdin.readlines()
def get_num1(i):
cnt = 0
while i:
if i%2:
cnt +=1
i //=2
return cnt
n = int(input())
a = list(rint())
b = [get_num1(aa) for aa in a]
ans = 0
#S0[i] : 1 if sum of 1s in ragne (0, i) is odd, else 0
S0 = [0]*n
S0[0] = b[0]%2
for i in range(1, n):
S0[i] = (S0[i-1] + b[i])%2
#total even pairs in (0, n)
even_cnt = S0.count(0)
ans = even_cnt
# check total even pairs in (i, n)
for i in range(1, n):
if b[i-1] %2:
even_cnt = n - i - even_cnt
else:
even_cnt -= 1
ans += even_cnt
for i in range(n):
max_value = 0
sum_value = 0
for j in range(1, 62):
if i + j > n:
break
sum_value += b[i+j-1]
max_value = max(max_value, b[i+j-1])
if 2 * max_value > sum_value and sum_value%2 == 0:
ans -= 1
print(ans) | python | test | qsol | codeparrot/apps | all |
Solve in Python:
You are given an n × m rectangular table consisting of lower case English letters. In one operation you can completely remove one column from the table. The remaining parts are combined forming a new table. For example, after removing the second column from the table
abcd
edfg
hijk
we obtain the table:
acd
efg
hjk
A table is called good if its rows are ordered from top to bottom lexicographically, i.e. each row is lexicographically no larger than the following one. Determine the minimum number of operations of removing a column needed to make a given table good.
-----Input-----
The first line contains two integers — n and m (1 ≤ n, m ≤ 100).
Next n lines contain m small English letters each — the characters of the table.
-----Output-----
Print a single number — the minimum number of columns that you need to remove in order to make the table good.
-----Examples-----
Input
1 10
codeforces
Output
0
Input
4 4
case
care
test
code
Output
2
Input
5 4
code
forc
esco
defo
rces
Output
4
-----Note-----
In the first sample the table is already good.
In the second sample you may remove the first and third column.
In the third sample you have to remove all the columns (note that the table where all rows are empty is considered good by definition).
Let strings s and t have equal length. Then, s is lexicographically larger than t if they are not equal and the character following the largest common prefix of s and t (the prefix may be empty) in s is alphabetically larger than the corresponding character of t. | import sys
n, m = [int(i) for i in input().split()]
a = [[0] * n for i in range(m)]
for i in range(n):
temp = input()
for j in range(m):
a[j][i] = temp[j]
c = 0
def blatant(a):
for i in range(1,len(a)):
if a[i] < a[i-1]:
return True
return False
match = []
while True:
if len(a) == 0:
print(m)
return
elif blatant(a[0]):
del a[0]
c += 1
else:
break
for i in range(1,n):
if a[0][i] == a[0][i-1]:
match.append(i)
def rm(a,match):
c = 0
for m in match:
i = 1
while i < len(a):
if a[i][m] < a[i][m-1]:
del a[i]
c += 1
elif a[i][m] == a[i][m-1]:
i += 1
else:
break
return c
while True:
temp = rm(a,match)
if temp == 0:
break
c += temp
print(c) | python | test | qsol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/1328/F:
You are given the array $a$ consisting of $n$ elements and the integer $k \le n$.
You want to obtain at least $k$ equal elements in the array $a$. In one move, you can make one of the following two operations:
Take one of the minimum elements of the array and increase its value by one (more formally, if the minimum value of $a$ is $mn$ then you choose such index $i$ that $a_i = mn$ and set $a_i := a_i + 1$); take one of the maximum elements of the array and decrease its value by one (more formally, if the maximum value of $a$ is $mx$ then you choose such index $i$ that $a_i = mx$ and set $a_i := a_i - 1$).
Your task is to calculate the minimum number of moves required to obtain at least $k$ equal elements in the array.
-----Input-----
The first line of the input contains two integers $n$ and $k$ ($1 \le k \le n \le 2 \cdot 10^5$) — the number of elements in $a$ and the required number of equal elements.
The second line of the input contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 10^9$), where $a_i$ is the $i$-th element of $a$.
-----Output-----
Print one integer — the minimum number of moves required to obtain at least $k$ equal elements in the array.
-----Examples-----
Input
6 5
1 2 2 4 2 3
Output
3
Input
7 5
3 3 2 1 1 1 3
Output
4
I tried it in Python, but could not do it. Can you solve it? | #!usr/bin/env python3
from collections import defaultdict, deque
from heapq import heappush, heappop
from itertools import permutations, accumulate
import sys
import math
import bisect
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def I(): return int(sys.stdin.readline())
def LS():return [list(x) for x in sys.stdin.readline().split()]
def S():
res = list(sys.stdin.readline())
if res[-1] == "\n":
return res[:-1]
return res
def IR(n):
return [I() for i in range(n)]
def LIR(n):
return [LI() for i in range(n)]
def SR(n):
return [S() for i in range(n)]
def LSR(n):
return [LS() for i in range(n)]
sys.setrecursionlimit(1000000)
mod = 1000000007
def solve():
n,k = LI()
a = LI()
a.sort()
d = defaultdict(lambda : 0)
c = defaultdict(lambda : 0)
s = [0]
for i in a:
d[i] += i
c[i] += 1
s.append(s[-1]+i)
ans = float("inf")
p = -1
for i in a:
if i == p:
continue
if k <= c[i]:
ans = 0
break
l,r = bisect.bisect_left(a,i),bisect.bisect_right(a,i)
m = r
if m >= k:
ns = l*(i-1)-s[l]
su = ns+k-c[i]
if su < ans:
ans = su
m = n-l
if m >= k:
ns = s[n]-s[r]-(n-r)*(i+1)
su = ns+k-c[i]
if su < ans:
ans = su
ns = s[n]-s[r]-(n-r)*(i+1)+l*(i-1)-s[l]
su = ns+k-c[i]
if su < ans:
ans = su
p = i
print(ans)
return
#Solve
def __starting_point():
solve()
__starting_point() | python | test | abovesol | codeparrot/apps | all |
Solve in Python:
Let's denote a function
$d(x, y) = \left\{\begin{array}{ll}{y - x,} & {\text{if}|x - y|> 1} \\{0,} & {\text{if}|x - y|\leq 1} \end{array} \right.$
You are given an array a consisting of n integers. You have to calculate the sum of d(a_{i}, a_{j}) over all pairs (i, j) such that 1 ≤ i ≤ j ≤ n.
-----Input-----
The first line contains one integer n (1 ≤ n ≤ 200000) — the number of elements in a.
The second line contains n integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10^9) — elements of the array.
-----Output-----
Print one integer — the sum of d(a_{i}, a_{j}) over all pairs (i, j) such that 1 ≤ i ≤ j ≤ n.
-----Examples-----
Input
5
1 2 3 1 3
Output
4
Input
4
6 6 5 5
Output
0
Input
4
6 6 4 4
Output
-8
-----Note-----
In the first example:
d(a_1, a_2) = 0; d(a_1, a_3) = 2; d(a_1, a_4) = 0; d(a_1, a_5) = 2; d(a_2, a_3) = 0; d(a_2, a_4) = 0; d(a_2, a_5) = 0; d(a_3, a_4) = - 2; d(a_3, a_5) = 0; d(a_4, a_5) = 2. | N = 2 * 10**5 + 3
n = int(input())
A, cnt = list(map(int,input().split(' '))), {}
s, a = 0, 0
for i in range(n-1,-1,-1):
a += s
if (A[i]-1) in cnt:
a += cnt[A[i]-1]
if (A[i]+1) in cnt:
a -= cnt[A[i]+1]
a -= (n-(i+1))*A[i]
s += A[i]
if A[i] not in cnt:
cnt[A[i]]=0
cnt[A[i]] += 1
print(a) | python | test | qsol | codeparrot/apps | all |
Solve in Python:
*** No Loops Allowed ***
You will be given an array (a) and a value (x). All you need to do is check whether the provided array contains the value, without using a loop.
Array can contain numbers or strings. X can be either. Return true if the array contains the value, false if not. With strings you will need to account for case.
Looking for more, loop-restrained fun? Check out the other kata in the series:
https://www.codewars.com/kata/no-loops-1-small-enough
https://www.codewars.com/kata/no-loops-3-copy-within | def check(a, x):
test = a.count(x)
if test >= 1:
return True
else:
return False | python | train | qsol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/327/A:
Iahub got bored, so he invented a game to be played on paper.
He writes n integers a_1, a_2, ..., a_{n}. Each of those integers can be either 0 or 1. He's allowed to do exactly one move: he chooses two indices i and j (1 ≤ i ≤ j ≤ n) and flips all values a_{k} for which their positions are in range [i, j] (that is i ≤ k ≤ j). Flip the value of x means to apply operation x = 1 - x.
The goal of the game is that after exactly one move to obtain the maximum number of ones. Write a program to solve the little game of Iahub.
-----Input-----
The first line of the input contains an integer n (1 ≤ n ≤ 100). In the second line of the input there are n integers: a_1, a_2, ..., a_{n}. It is guaranteed that each of those n values is either 0 or 1.
-----Output-----
Print an integer — the maximal number of 1s that can be obtained after exactly one move.
-----Examples-----
Input
5
1 0 0 1 0
Output
4
Input
4
1 0 0 1
Output
4
-----Note-----
In the first case, flip the segment from 2 to 5 (i = 2, j = 5). That flip changes the sequence, it becomes: [1 1 1 0 1]. So, it contains four ones. There is no way to make the whole sequence equal to [1 1 1 1 1].
In the second case, flipping only the second and the third element (i = 2, j = 3) will turn all numbers into 1.
I tried it in Python, but could not do it. Can you solve it? | n = int(input())
I = list(map(int, input().split()))
d = []
for val in I:
d.append(val)
res = 0;
for i in range (0, n):
for j in range (i, n):
cnt = 0;
for k in range (0, n):
if k >= i and k <= j:
cnt = cnt + 1 - d[k];
else:
cnt = cnt + d[k];
if cnt > res:
res = cnt;
print (res) | python | test | abovesol | codeparrot/apps | all |
Solve in Python:
Someone give a strange birthday present to Ivan. It is hedgehog — connected undirected graph in which one vertex has degree at least $3$ (we will call it center) and all other vertices has degree 1. Ivan thought that hedgehog is too boring and decided to make himself $k$-multihedgehog.
Let us define $k$-multihedgehog as follows: $1$-multihedgehog is hedgehog: it has one vertex of degree at least $3$ and some vertices of degree 1. For all $k \ge 2$, $k$-multihedgehog is $(k-1)$-multihedgehog in which the following changes has been made for each vertex $v$ with degree 1: let $u$ be its only neighbor; remove vertex $v$, create a new hedgehog with center at vertex $w$ and connect vertices $u$ and $w$ with an edge. New hedgehogs can differ from each other and the initial gift.
Thereby $k$-multihedgehog is a tree. Ivan made $k$-multihedgehog but he is not sure that he did not make any mistakes. That is why he asked you to check if his tree is indeed $k$-multihedgehog.
-----Input-----
First line of input contains $2$ integers $n$, $k$ ($1 \le n \le 10^{5}$, $1 \le k \le 10^{9}$) — number of vertices and hedgehog parameter.
Next $n-1$ lines contains two integers $u$ $v$ ($1 \le u, \,\, v \le n; \,\, u \ne v$) — indices of vertices connected by edge.
It is guaranteed that given graph is a tree.
-----Output-----
Print "Yes" (without quotes), if given graph is $k$-multihedgehog, and "No" (without quotes) otherwise.
-----Examples-----
Input
14 2
1 4
2 4
3 4
4 13
10 5
11 5
12 5
14 5
5 13
6 7
8 6
13 6
9 6
Output
Yes
Input
3 1
1 3
2 3
Output
No
-----Note-----
2-multihedgehog from the first example looks like this:
[Image]
Its center is vertex $13$. Hedgehogs created on last step are: [4 (center), 1, 2, 3], [6 (center), 7, 8, 9], [5 (center), 10, 11, 12, 13].
Tree from second example is not a hedgehog because degree of center should be at least $3$. | n,k = list(map(int,input().split(" ")))
degrees = [0] * n
neighbors = [list() for x in range(n)]
for i in range(n-1):
first,second = list(map(int,input().split(" ")))
degrees[first-1] += 1
degrees[second-1] += 1
neighbors[first-1] += [second]
neighbors[second-1] += [first]
# start at a leaf
curr = 0
for i in range(n):
if degrees[i] == 1:
curr = i+1
break
if curr == 0 or len(neighbors[curr-1]) == 0:
print("No")
return
curr = neighbors[curr-1][0]
def check(prev,parent,curr,level,degrees,neighbors,k):
#print("curr: ",curr)
#print("level: ",level)
if level == 0:
return len(parent) == 1 and degrees[curr-1] == 1,[]
checked = []
for neighbor in neighbors[curr-1]:
#print("neighbor: ",neighbor)
#print("checked: ",checked)
#print("parent: ",parent)
if len(prev) != 0 and prev[0] == neighbor:
checked += [neighbor]
continue
if len(parent) != 0 and parent[0] == neighbor:
continue
result,garbage = check([],[curr],neighbor,level-1,degrees,neighbors,k)
if result:
checked += [neighbor]
else:
#print("adding the parent")
if len(parent) == 0:
parent += [neighbor]
else:
return False,[]
if len(checked) > 2 and len(parent) == 0 and level == k:
#print("first check")
return True,[]
elif len(checked) > 2 and len(parent) == 1 and level != k:
#print("second check")
return True,parent
else:
#print("len(checked): ",len(checked))
#print("len(parent): ",len(parent))
#print("level: ",level)
#print("the end fail statement")
return False,[]
prev = []
parent = []
counter = 1
while(counter <= k):
result,parent = check(prev,[],curr,counter,degrees,neighbors,k)
if not(result):
print("No")
return
if counter == k:
print("Yes")
return
prev = [curr]
curr = parent[0]
counter += 1 | python | test | qsol | codeparrot/apps | all |
Solve in Python:
On Children's Day, the child got a toy from Delayyy as a present. However, the child is so naughty that he can't wait to destroy the toy.
The toy consists of n parts and m ropes. Each rope links two parts, but every pair of parts is linked by at most one rope. To split the toy, the child must remove all its parts. The child can remove a single part at a time, and each remove consume an energy. Let's define an energy value of part i as v_{i}. The child spend v_{f}_1 + v_{f}_2 + ... + v_{f}_{k} energy for removing part i where f_1, f_2, ..., f_{k} are the parts that are directly connected to the i-th and haven't been removed.
Help the child to find out, what is the minimum total energy he should spend to remove all n parts.
-----Input-----
The first line contains two integers n and m (1 ≤ n ≤ 1000; 0 ≤ m ≤ 2000). The second line contains n integers: v_1, v_2, ..., v_{n} (0 ≤ v_{i} ≤ 10^5). Then followed m lines, each line contains two integers x_{i} and y_{i}, representing a rope from part x_{i} to part y_{i} (1 ≤ x_{i}, y_{i} ≤ n; x_{i} ≠ y_{i}).
Consider all the parts are numbered from 1 to n.
-----Output-----
Output the minimum total energy the child should spend to remove all n parts of the toy.
-----Examples-----
Input
4 3
10 20 30 40
1 4
1 2
2 3
Output
40
Input
4 4
100 100 100 100
1 2
2 3
2 4
3 4
Output
400
Input
7 10
40 10 20 10 20 80 40
1 5
4 7
4 5
5 2
5 7
6 4
1 6
1 3
4 3
1 4
Output
160
-----Note-----
One of the optimal sequence of actions in the first sample is: First, remove part 3, cost of the action is 20. Then, remove part 2, cost of the action is 10. Next, remove part 4, cost of the action is 10. At last, remove part 1, cost of the action is 0.
So the total energy the child paid is 20 + 10 + 10 + 0 = 40, which is the minimum.
In the second sample, the child will spend 400 no matter in what order he will remove the parts. | (n, m), f, s = list(map(int, input().split())), [int(x) for x in input().split()], 0
for i in range(m):
(a, b) = list(map(int, input().split()))
s = s + min(f[a - 1], f[b - 1])
print( s ) | python | test | qsol | codeparrot/apps | all |
I found an interesting problem on https://www.codewars.com/kata/559e5b717dd758a3eb00005a:
DropCaps means that the first letter of the starting word of the paragraph should be in caps and the remaining lowercase, just like you see in the newspaper.
But for a change, let's do that for each and every word of the given String. Your task is to capitalize every word that has length greater than 2, leaving smaller words as they are.
*should work also on Leading and Trailing Spaces and caps.
```python
drop_cap('apple') => "Apple"
drop_cap('apple of banana'); => "Apple of Banana"
drop_cap('one space'); => "One Space"
drop_cap(' space WALK '); => " Space Walk "
```
**Note:** you will be provided atleast one word and should take string as input and return string as output.
I tried it in Python, but could not do it. Can you solve it? | import re
def drop_cap(s):
return re.sub(r'\S{3,}', lambda m: m.group(0).title(), s) | python | train | abovesol | codeparrot/apps | all |
Solve in Python:
#It's show time!
Archers have gathered from all around the world to participate in the Arrow Function Faire. But the faire will only start if there are archers signed and if they all have enough arrows in their quivers - at least 5 is the requirement! Are all the archers ready?
#Reference
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions
#Argument
`archers` is an array of integers, in which each element corresponds to the number of arrows each archer has.
#Return
Your function must return `true` if the requirements are met or `false` otherwise.
#Examples
`archersReady([1, 2, 3, 4, 5, 6, 7, 8])` returns `false` because there are archers with not enough arrows.
`archersReady([5, 6, 7, 8])` returns `true`. | def archers_ready(archers):
if not archers:
return False
for arrows in archers:
if arrows < 5:
return False
return True | python | train | qsol | codeparrot/apps | all |
I found an interesting problem on https://www.codewars.com/kata/5750699bcac40b3ed80001ca:
It is 2050 and romance has long gone, relationships exist solely for practicality.
MatchMyHusband is a website that matches busy working women with perfect house husbands. You have been employed by MatchMyHusband to write a function that determines who matches!!
The rules are... a match occurs providing the husband's "usefulness" rating is greater than or equal to the woman's "needs".
The husband's "usefulness" is the SUM of his cooking, cleaning and childcare abilities and takes the form of an array .
usefulness example --> [15, 26, 19] (15 + 26 + 19) = 60
Every woman that signs up, begins with a "needs" rating of 100. However, it's realised that the longer women wait for their husbands, the more dissatisfied they become with our service. They also become less picky, therefore their needs are subject to exponential decay of 15% per month. https://en.wikipedia.org/wiki/Exponential_decay
Given the number of months since sign up, write a function that returns "Match!" if the husband is useful enough, or "No match!" if he's not.
I tried it in Python, but could not do it. Can you solve it? | def match(a, n):
return "Match!" if sum(a) >= 100 * 0.85**n else "No match!" | python | train | abovesol | codeparrot/apps | all |
Solve in Python:
Complete the function which returns the weekday according to the input number:
* `1` returns `"Sunday"`
* `2` returns `"Monday"`
* `3` returns `"Tuesday"`
* `4` returns `"Wednesday"`
* `5` returns `"Thursday"`
* `6` returns `"Friday"`
* `7` returns `"Saturday"`
* Otherwise returns `"Wrong, please enter a number between 1 and 7"` | def whatday(num):
dict={
2:"Monday",
3:"Tuesday",
4:"Wednesday",
5:"Thursday",
6:"Friday",
7:"Saturday",
1:"Sunday"
}
return dict.get(num,'Wrong, please enter a number between 1 and 7') | python | train | qsol | codeparrot/apps | all |
Solve in Python:
Bizon the Champion isn't just attentive, he also is very hardworking.
Bizon the Champion decided to paint his old fence his favorite color, orange. The fence is represented as n vertical planks, put in a row. Adjacent planks have no gap between them. The planks are numbered from the left to the right starting from one, the i-th plank has the width of 1 meter and the height of a_{i} meters.
Bizon the Champion bought a brush in the shop, the brush's width is 1 meter. He can make vertical and horizontal strokes with the brush. During a stroke the brush's full surface must touch the fence at all the time (see the samples for the better understanding). What minimum number of strokes should Bizon the Champion do to fully paint the fence? Note that you are allowed to paint the same area of the fence multiple times.
-----Input-----
The first line contains integer n (1 ≤ n ≤ 5000) — the number of fence planks. The second line contains n space-separated integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10^9).
-----Output-----
Print a single integer — the minimum number of strokes needed to paint the whole fence.
-----Examples-----
Input
5
2 2 1 2 1
Output
3
Input
2
2 2
Output
2
Input
1
5
Output
1
-----Note-----
In the first sample you need to paint the fence in three strokes with the brush: the first stroke goes on height 1 horizontally along all the planks. The second stroke goes on height 2 horizontally and paints the first and second planks and the third stroke (it can be horizontal and vertical) finishes painting the fourth plank.
In the second sample you can paint the fence with two strokes, either two horizontal or two vertical strokes.
In the third sample there is only one plank that can be painted using a single vertical stroke. | import sys
oo=1000000000000
ar=[]
def solve(l, r, val):
if(r<l): return 0
indx=l+ar[l:r+1].index(min(ar[l:r+1]))
tot=r-l+1
cur=ar[indx]-val+solve(l, indx-1, ar[indx])+solve(indx+1, r, ar[indx])
return min(tot, cur)
sys.setrecursionlimit(10000)
n=int(input())
ar=list(map(int, input().split()))
print(solve(0, n-1, 0)) | python | test | qsol | codeparrot/apps | all |
I found an interesting problem on https://www.codechef.com/APRIL14/problems/BINTREE:
Consider an infinite full binary tree (each node has two children except the leaf nodes) defined as follows. For a node labelled v its left child will be labelled 2*v and its right child will be labelled 2*v+1. The root is labelled as 1.
You are given N queries of the form i j. For each query, you have to print the length of the shortest path between node labelled i and node labelled j.
-----Input-----
First line contains N, the number of queries. Each query consists of two space separated integers i and j in one line.
-----Output-----
For each query, print the required answer in one line.
-----Constraints-----
- 1 ≤ N ≤ 105
- 1 ≤ i,j ≤ 109
-----Example-----
Input:
3
1 2
2 3
4 3
Output:
1
2
3
-----Explanation-----
For first query, 1 is directly connected to 2 by an edge. Hence distance 1.
I tried it in Python, but could not do it. Can you solve it? | import math
import sys
import time
def getLevel(number):
_level = math.floor(math.log(number,2))
return int(_level)
def isPair(number):
return (number%2 == 0)
def getInterval(a,b, max):
_max = max
_loop = -1
_apart = 0
while (_apart == 0) and (_max != 1):
_loop += 1
_max = _max >> 1
if (a < _max) and (b >= _max):
_apart = 1
elif (a >= _max):
a = a - _max
b = b - _max
return _loop
def resolve2(nodes):
if nodes[0] == nodes[1]:
return 0
l = 0
k = 0
while (nodes[0] != nodes[1]) :
if (nodes[1] < nodes[0]) :
if (nodes[0] > 1):
nodes[0] = nodes[0]/2 if isPair(nodes[0]) else (nodes[0] -1)/2
l += 1
else:
if (nodes[1] > 1):
nodes[1] = nodes[1]/2 if isPair(nodes[1]) else (nodes[1] -1)/2
k += 1
return (l + k)
def __starting_point():
step = 0
for line in sys.stdin:
if (step==0):
step = 1
continue
nodes =[int(nums) for nums in line.strip().split()]
if nodes[0] == nodes[1]:
print(0)
continue
_temp = nodes[0]
if nodes[0] < nodes[1] :
nodes[0] = nodes[1]
nodes[1] = _temp
_max_level = getLevel(nodes[0])
if (nodes[1] == 1):
print(_max_level)
continue
_min_level = getLevel(nodes[1])
substract = _max_level - _min_level
if (substract != 0):
nodes[0] = nodes[0] >> substract
_temp = nodes[0]
if nodes[0] < nodes[1] :
nodes[0] = nodes[1]
nodes[1] = _temp
if (nodes[1] == nodes[0]):
print( substract)
continue
_max = 2**_min_level
apart = getInterval(nodes[1] - _max, nodes[0] - _max,_max)
print( 2*(_min_level - apart) + substract)
#print( resolve2(nodes) )
__starting_point() | python | train | abovesol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/1105/A:
Salem gave you $n$ sticks with integer positive lengths $a_1, a_2, \ldots, a_n$.
For every stick, you can change its length to any other positive integer length (that is, either shrink or stretch it). The cost of changing the stick's length from $a$ to $b$ is $|a - b|$, where $|x|$ means the absolute value of $x$.
A stick length $a_i$ is called almost good for some integer $t$ if $|a_i - t| \le 1$.
Salem asks you to change the lengths of some sticks (possibly all or none), such that all sticks' lengths are almost good for some positive integer $t$ and the total cost of changing is minimum possible. The value of $t$ is not fixed in advance and you can choose it as any positive integer.
As an answer, print the value of $t$ and the minimum cost. If there are multiple optimal choices for $t$, print any of them.
-----Input-----
The first line contains a single integer $n$ ($1 \le n \le 1000$) — the number of sticks.
The second line contains $n$ integers $a_i$ ($1 \le a_i \le 100$) — the lengths of the sticks.
-----Output-----
Print the value of $t$ and the minimum possible cost. If there are multiple optimal choices for $t$, print any of them.
-----Examples-----
Input
3
10 1 4
Output
3 7
Input
5
1 1 2 2 3
Output
2 0
-----Note-----
In the first example, we can change $1$ into $2$ and $10$ into $4$ with cost $|1 - 2| + |10 - 4| = 1 + 6 = 7$ and the resulting lengths $[2, 4, 4]$ are almost good for $t = 3$.
In the second example, the sticks lengths are already almost good for $t = 2$, so we don't have to do anything.
I tried it in Python, but could not do it. Can you solve it? | n = int(input())
arr = list(map(int, input().split()))
arr.sort()
a = []
for t in range(1, 101):
tot = 0
for item in arr:
if (abs(item - t) >= 1):
tot += abs(item - t) - 1
a.append((tot, t))
a.sort()
print(a[0][1], a[0][0]) | python | test | abovesol | codeparrot/apps | all |
Solve in Python:
You are given a set $S$ and $Q$ queries. Initially, $S$ is empty. In each query:
- You are given a positive integer $X$.
- You should insert $X$ into $S$.
- For each $y \in S$ before this query such that $y \neq X$, you should also insert $y \oplus X$ into $S$ ($\oplus$ denotes the XOR operation).
- Then, you should find two values $E$ and $O$: the number of elements of $S$ with an even number of $1$-s and with an odd number of $1$-s in the binary representation, respectively.
Note that a set cannot have duplicate elements, so if you try to insert into $S$ an element that is already present in $S$, then nothing happens.
-----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 $Q$.
- Each of the next $Q$ lines contains a single integer $X$ describing a query.
-----Output-----
For each query, print a single line containing two space-separated integers $E$ and $O$.
-----Constraints-----
- $1 \le T \le 5$
- $1 \le Q, X \le 10^5$
-----Subtasks-----
Subtask #1 (30 points):
- $1 \le Q \le 1,000$
- $1 \le X \le 128$
Subtask #2 (70 points): original constraints
-----Example Input-----
1
3
4
2
7
-----Example Output-----
0 1
1 2
3 4
-----Explanation-----
Example case 1:
- Initially, the set is empty: $S = \{\}$.
- After the first query, $S = \{4\}$, so there is only one element with an odd number of $1$-s in the binary representation ("100").
- After the second query, $S = \{4,2,6\}$, there is one element with an even number of $1$-s in the binary representation ($6$ is "110") and the other two elements have an odd number of $1$-s.
- After the third query, $S = \{4,2,6,7,3,5,1\}$. | import collections
def bits(x):
return bin(x).count('1')
t=int(input())
for _ in range(t):
q=int(input())
s=[]
d=collections.defaultdict(lambda:-1)
e=0
o=0
p=-1
for i in range(q):
x=int(input())
# print(d)
if d[x]!=-1:
print(e,o)
continue
s.append(x)
d[x]=1
#z=len(s)
for j in s:
if j!=x:
l=j^x
if d[l]!=-1:
continue
s.append(l)
d[l]=1
for j in range(p+1,len(s)):
p=j
if bits(s[j])%2==0:
e=e+1
elif bits(s[j])%2!=0:
o=o+1
print(e,o) | python | train | qsol | codeparrot/apps | all |
I found an interesting problem on https://www.codechef.com/IGNS2012/problems/IG04:
In a fictitious city of CODASLAM there were many skyscrapers. The mayor of the city decided to make the city beautiful and for this he decided to arrange the skyscrapers in descending order of their height, and the order must be strictly decreasing but he also didn’t want to waste much money so he decided to get the minimum cuts possible. Your job is to output the minimum value of cut that is possible to arrange the skyscrapers in descending order.
-----Input-----
*First line of input is the number of sky-scrappers in the city
*Second line of input is the height of the respective sky-scrappers
-----Output-----
* Your output should be the minimum value of cut required to arrange these sky-scrappers in descending order.
-----Example-----
Input:
5
1 2 3 4 5
Output:
8
By:
Chintan,Asad,Ashayam,Akanksha
I tried it in Python, but could not do it. Can you solve it? | import sys
num=int(sys.stdin.readline())
s=sys.stdin.readline().split()
sky=list(map(int,s))
sky.reverse()
cuts=0
change=0
t=False
i=1
while i<len(sky):
if sky[i]<=sky[i-1]:
for j in range(i-1,-1,-1):
if sky[j]<=sky[i]-(i-j):
break
else:
change+=sky[j]-(sky[i]-(i-j))
if change>=sky[i]:
change=sky[i]
t=True
break
cuts+=change
if t:
del sky[i]
t=False
i-=1
else:
for j in range(i-1,-1,-1):
if sky[j]<sky[i]-(i-j):
break
else:
sky[j]=sky[i]-(i-j)
i+=1
change=0
print(cuts) | python | train | abovesol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/1205/A:
You are given integer $n$. You have to arrange numbers from $1$ to $2n$, using each of them exactly once, on the circle, so that the following condition would be satisfied:
For every $n$ consecutive numbers on the circle write their sum on the blackboard. Then any two of written on the blackboard $2n$ numbers differ not more than by $1$.
For example, choose $n = 3$. On the left you can see an example of a valid arrangement: $1 + 4 + 5 = 10$, $4 + 5 + 2 = 11$, $5 + 2 + 3 = 10$, $2 + 3 + 6 = 11$, $3 + 6 + 1 = 10$, $6 + 1 + 4 = 11$, any two numbers differ by at most $1$. On the right you can see an invalid arrangement: for example, $5 + 1 + 6 = 12$, and $3 + 2 + 4 = 9$, $9$ and $12$ differ more than by $1$.
[Image]
-----Input-----
The first and the only line contain one integer $n$ ($1 \le n \le 10^5$).
-----Output-----
If there is no solution, output "NO" in the first line.
If there is a solution, output "YES" in the first line. In the second line output $2n$ numbers — numbers from $1$ to $2n$ in the order they will stay in the circle. Each number should appear only once. If there are several solutions, you can output any of them.
-----Examples-----
Input
3
Output
YES
1 4 5 2 3 6
Input
4
Output
NO
-----Note-----
Example from the statement is shown for the first example.
It can be proved that there is no solution in the second example.
I tried it in Python, but could not do it. Can you solve it? | # 1205A Almost Equal
n = int(input())
if n % 2 == 0:
print("NO")
else:
print("YES")
d = 1
for i in range(n):
print(d, end=' ')
d += 3 if i % 2 == 0 else 1
d = 2
for i in range(n):
print(d, end=' ')
d += 1 if i % 2 == 0 else 3 | python | train | abovesol | codeparrot/apps | all |
I found an interesting problem on https://atcoder.jp/contests/abc077/tasks/abc077_a:
You are given a grid with 2 rows and 3 columns of squares.
The color of the square at the i-th row and j-th column is represented by the character C_{ij}.
Write a program that prints YES if this grid remains the same when rotated 180 degrees, and prints NO otherwise.
-----Constraints-----
- C_{i,j}(1 \leq i \leq 2, 1 \leq j \leq 3) is a lowercase English letter.
-----Input-----
Input is given from Standard Input in the following format:
C_{11}C_{12}C_{13}
C_{21}C_{22}C_{23}
-----Output-----
Print YES if this grid remains the same when rotated 180 degrees; print NO otherwise.
-----Sample Input-----
pot
top
-----Sample Output-----
YES
This grid remains the same when rotated 180 degrees.
I tried it in Python, but could not do it. Can you solve it? | c1 = input()
c2 = input()
print("YES" if c1 == c2[::-1] else "NO") | python | test | abovesol | codeparrot/apps | all |
Solve in Python:
Chef bought a huge (effectively infinite) planar island and built $N$ restaurants (numbered $1$ through $N$) on it. For each valid $i$, the Cartesian coordinates of restaurant $i$ are $(X_i, Y_i)$.
Now, Chef wants to build $N-1$ straight narrow roads (line segments) on the island. The roads may have arbitrary lengths; restaurants do not have to lie on the roads. The slope of each road must be $1$ or $-1$, i.e. for any two points $(x_1, y_1)$ and $(x_2, y_2)$ on the same road, $|x_1-x_2| = |y_1-y_2|$ must hold.
Let's denote the minimum distance Chef has to walk from restaurant $i$ to reach a road by $D_i$. Then, let's denote $a = \mathrm{max}\,(D_1, D_2, \ldots, D_N)$; Chef wants this distance to be minimum possible.
Chef is a busy person, so he decided to give you the job of building the roads. You should find a way to build them that minimises $a$ and compute $a \cdot \sqrt{2}$.
-----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$.
- $N$ lines follow. For each valid $i$, the $i$-th of these lines contains two space-separated integers $X_i$ and $Y_i$.
-----Output-----
For each test case, print a single line containing one real number — the minimum distance $a$ multiplied by $\sqrt{2}$. Your answer will be considered correct if its absolute or relative error does not exceed $10^{-6}$.
-----Constraints-----
- $1 \le T \le 100$
- $2 \le N \le 10^4$
- $|X_i|, |Y_i| \le 10^9$ for each valid $i$
-----Subtasks-----
Subtask #1 (10 points):
- $1 \le T \le 10$
- $2 \le N \le 5$
- $|X_i|, |Y_i| \le 10$ for each valid $i$
- $a \cdot \sqrt{2}$ is an integer
Subtask #2 (90 points): original constraints
-----Example Input-----
2
3
0 0
0 1
0 -1
3
0 1
1 0
-1 0
-----Example Output-----
0.5
0
-----Explanation-----
Example case 1: We should build roads described by equations $y-x+0.5 = 0$ and $y-x-0.5 = 0$.
Example case 2: We should build roads described by... | t=int(input())
for i in range(t):
n=int(input())
x=[]
y=[]
dx=[]
dy=[]
for j in range(n):
c=list(map(int,input().split()))
x.append(c[0]-c[1])
y.append(c[0]+c[1])
x.sort()
y.sort()
for j in range(1,n):
dx.append(x[j]-x[j-1])
dy.append(y[j]-y[j-1])
a=min(dx)
b=min(dy)
print('{0:.6f}'.format(min(a,b)/2)) | python | train | qsol | codeparrot/apps | all |
Solve in Python:
*** No Loops Allowed ***
You will be given an array (a) and a limit value (limit). You must check that all values in the array are below or equal to the limit value. If they are, return true. Else, return false.
You can assume all values in the array are numbers.
Do not use loops. Do not modify input array.
Looking for more, loop-restrained fun? Check out the other kata in the series:
https://www.codewars.com/kata/no-loops-2-you-only-need-one
https://www.codewars.com/kata/no-loops-3-copy-within | small_enough = lambda a, x: False not in map(lambda i: i <= x, a) | python | train | qsol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/758/D:
Alexander is learning how to convert numbers from the decimal system to any other, however, he doesn't know English letters, so he writes any number only as a decimal number, it means that instead of the letter A he will write the number 10. Thus, by converting the number 475 from decimal to hexadecimal system, he gets 11311 (475 = 1·16^2 + 13·16^1 + 11·16^0). Alexander lived calmly until he tried to convert the number back to the decimal number system.
Alexander remembers that he worked with little numbers so he asks to find the minimum decimal number so that by converting it to the system with the base n he will get the number k.
-----Input-----
The first line contains the integer n (2 ≤ n ≤ 10^9). The second line contains the integer k (0 ≤ k < 10^60), it is guaranteed that the number k contains no more than 60 symbols. All digits in the second line are strictly less than n.
Alexander guarantees that the answer exists and does not exceed 10^18.
The number k doesn't contain leading zeros.
-----Output-----
Print the number x (0 ≤ x ≤ 10^18) — the answer to the problem.
-----Examples-----
Input
13
12
Output
12
Input
16
11311
Output
475
Input
20
999
Output
3789
Input
17
2016
Output
594
-----Note-----
In the first example 12 could be obtained by converting two numbers to the system with base 13: 12 = 12·13^0 or 15 = 1·13^1 + 2·13^0.
I tried it in Python, but could not do it. Can you solve it? | n=int(input())
#print(n)
d=input()
l=len(d)
dp=[[0,0] for i in range(0,l+1)]
dp[l-1]=[ord(d[l-1])-ord('0'),1]
for i in range(1,l):
w=l-1-i;
m=(ord(d[w])-ord('0'))*(n**i)+dp[w+1][0]
dp[w]=[m,i+1];
if (d[w]=='0'):
dp[w][0]=dp[w+1][0]
dp[w][1]=dp[w+1][1]+1
continue
for j in range(w,l):
subs=int(d[w:j+1])
u=dp[j+1]
if subs<n:
re=subs*(n**u[1])+u[0]
if re<dp[w][0] or (re==dp[w][0] and 1+u[1]<dp[w][1]):
dp[w][0]=re
dp[w][1]=1+u[1]
else:
break
print(dp[0][0]) | python | test | abovesol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/526/C:
A sweet little monster Om Nom loves candies very much. One day he found himself in a rather tricky situation that required him to think a bit in order to enjoy candies the most. Would you succeed with the same task if you were on his place? [Image]
One day, when he came to his friend Evan, Om Nom didn't find him at home but he found two bags with candies. The first was full of blue candies and the second bag was full of red candies. Om Nom knows that each red candy weighs W_{r} grams and each blue candy weighs W_{b} grams. Eating a single red candy gives Om Nom H_{r} joy units and eating a single blue candy gives Om Nom H_{b} joy units.
Candies are the most important thing in the world, but on the other hand overeating is not good. Om Nom knows if he eats more than C grams of candies, he will get sick. Om Nom thinks that it isn't proper to leave candy leftovers, so he can only eat a whole candy. Om Nom is a great mathematician and he quickly determined how many candies of what type he should eat in order to get the maximum number of joy units. Can you repeat his achievement? You can assume that each bag contains more candies that Om Nom can eat.
-----Input-----
The single line contains five integers C, H_{r}, H_{b}, W_{r}, W_{b} (1 ≤ C, H_{r}, H_{b}, W_{r}, W_{b} ≤ 10^9).
-----Output-----
Print a single integer — the maximum number of joy units that Om Nom can get.
-----Examples-----
Input
10 3 5 2 3
Output
16
-----Note-----
In the sample test Om Nom can eat two candies of each type and thus get 16 joy units.
I tried it in Python, but could not do it. Can you solve it? | import sys
f = sys.stdin
C, Hr, Hb, Wr, Wb = map(int, f.readline().strip().split())
if Hr/Wr < Hb/Wb:
Hr, Hb, Wr, Wb = Hb, Hr, Wb, Wr
if (C % Wr) == 0 and (C // Wr) > 0:
print((C // Wr)*Hr)
elif (C // Wr) == 0:
print((C // Wb)*Hb)
else:
nmax = (C // Wr)
pmax = nmax*Hr + ((C - nmax*Wr) // Wb) * Hb
dmax = ((C - (nmax-0)*Wr) % Wb)
#print(0, pmax, dmax)
#
#pm1 = (nmax-1)*Hr + ((C - (nmax-1)*Wr) // Wb) * Hb
#if pm1>pmax:
# pmax = pm1
if Hr/Wr > Hb/Wb:
dx = dmax * (Hb/Wb) / (Hr/Wr - Hb/Wb)
elif Hr/Wr < Hb/Wb:
dx = 0
else:
dx = Wb * Wr
if Wr<Wb:
nmax = (C // Wb)
pmax = nmax*Hb + ((C - nmax*Wb) // Wr) * Hr
if Wr>Wb:
nmax = (C // Wr)
pmax = nmax*Hr + ((C - nmax*Wr) // Wb) * Hb
if Wr>Wb and dx>0:
for k in range(1, C//Wr):
if k*Wr > dx:
break
pk = (nmax-k)*Hr + ((C - (nmax-k)*Wr) // Wb) * Hb
dk = ((C - (nmax-k)*Wr) % Wb)
#print(k, pmax, pk, dk)
if pk>pmax:
pmax = pk
if dk==0 :
break
elif Wr<Wb and dx>0:
for j in range(1, C//Wb+1):
k = nmax - (C-j*Wb)//Wr
if k*Wr > dx:
break
pk = (nmax-k)*Hr + ((C - (nmax-k)*Wr) // Wb) * Hb
dk = ((C - (nmax-k)*Wr) % Wb)
#print(j, k, pmax, pk, dk, (nmax-k), ((C - (nmax-k)*Wr) // Wb) )
if pk>pmax:
pmax = pk
#dmax = dk
if dk==0 :
break
# elif Wr<Wb and dx>0:
# for j in range(1, C//Wb+1):
# k = (j*Wb - dmax)//Wr
# if k*Wr > dx:
# break
# pk = (nmax-k)*Hr + ((C - (nmax-k)*Wr) // Wb) * Hb
# dk = ((C - (nmax-k)*Wr) % Wb)
# print(j, k, pmax, pk, dk, (nmax-k), ((C - (nmax-k)*Wr) // Wb) )
# ... | python | test | abovesol | codeparrot/apps | all |
Solve in Python:
Ashish has an array $a$ of size $n$.
A subsequence of $a$ is defined as a sequence that can be obtained from $a$ by deleting some elements (possibly none), without changing the order of the remaining elements.
Consider a subsequence $s$ of $a$. He defines the cost of $s$ as the minimum between: The maximum among all elements at odd indices of $s$. The maximum among all elements at even indices of $s$.
Note that the index of an element is its index in $s$, rather than its index in $a$. The positions are numbered from $1$. So, the cost of $s$ is equal to $min(max(s_1, s_3, s_5, \ldots), max(s_2, s_4, s_6, \ldots))$.
For example, the cost of $\{7, 5, 6\}$ is $min( max(7, 6), max(5) ) = min(7, 5) = 5$.
Help him find the minimum cost of a subsequence of size $k$.
-----Input-----
The first line contains two integers $n$ and $k$ ($2 \leq k \leq n \leq 2 \cdot 10^5$) — the size of the array $a$ and the size of the subsequence.
The next line contains $n$ integers $a_1, a_2, \ldots, a_n$ ($1 \leq a_i \leq 10^9$) — the elements of the array $a$.
-----Output-----
Output a single integer — the minimum cost of a subsequence of size $k$.
-----Examples-----
Input
4 2
1 2 3 4
Output
1
Input
4 3
1 2 3 4
Output
2
Input
5 3
5 3 4 2 6
Output
2
Input
6 4
5 3 50 2 4 5
Output
3
-----Note-----
In the first test, consider the subsequence $s$ = $\{1, 3\}$. Here the cost is equal to $min(max(1), max(3)) = 1$.
In the second test, consider the subsequence $s$ = $\{1, 2, 4\}$. Here the cost is equal to $min(max(1, 4), max(2)) = 2$.
In the fourth test, consider the subsequence $s$ = $\{3, 50, 2, 4\}$. Here the cost is equal to $min(max(3, 2), max(50, 4)) = 3$. | def check(num):
count = 0
flag = -1
s = 0
for i in range(n):
if a[i]<=num:
count += 1
s += 1
else:
if flag == -1:
flag = s%2
count += 1
s += 1
else:
if (s+1)%2!=flag:
count += 1
s += 1
if count==k:
return True
return False
n,k = map(int,input().split())
a = list(map(int,input().split()))
if n==k:
m1 = 0
m2 = 0
for i in range(0,n,2):
m1 = max(m1,a[i])
for i in range(1,n,2):
m2 = max(m2,a[i])
print (min(m1,m2))
return
s = set(a)
minn,maxx = min(a),max(a)
low = minn
high = maxx
while low<high:
mid = (low+high)//2
if check(mid):
high = mid-1
else:
low = mid+1
if check(low):
print (low)
else:
print (low+1) | python | test | qsol | codeparrot/apps | all |
I found an interesting problem on https://www.hackerrank.com/challenges/word-order/problem:
=====Problem Statement=====
You are given n words. Some words may repeat. For each word, output its number of occurrences. The output order should correspond with the input order of appearance of the word. See the sample input/output for clarification.
Note: Each input line ends with a "\n" character.
=====Constraints=====
1≤n≤10^5
The sum of the lengths of all the words do not exceed 10^6
All the words are composed of lowercase English letters only.
=====Input Format=====
The first line contains the integer, n.
The next n lines each contain a word.
=====Output Format=====
Output 2 lines.
On the first line, output the number of distinct words from the input.
On the second line, output the number of occurrences for each distinct word according to their appearance in the input.
I tried it in Python, but could not do it. Can you solve it? | #!/usr/bin/env python3
from collections import OrderedDict
def __starting_point():
num = int(input().strip())
history = OrderedDict()
for _ in range(num):
word = str(input().strip().split())
if word not in list(history.keys()):
history[word] = 1
else:
history[word] += 1
print((len(list(history.keys()))))
print((" ".join(map(str, list(history.values())))))
__starting_point() | python | train | abovesol | codeparrot/apps | all |
Solve in Python:
Limak is a little polar bear. He plays by building towers from blocks. Every block is a cube with positive integer length of side. Limak has infinitely many blocks of each side length.
A block with side a has volume a^3. A tower consisting of blocks with sides a_1, a_2, ..., a_{k} has the total volume a_1^3 + a_2^3 + ... + a_{k}^3.
Limak is going to build a tower. First, he asks you to tell him a positive integer X — the required total volume of the tower. Then, Limak adds new blocks greedily, one by one. Each time he adds the biggest block such that the total volume doesn't exceed X.
Limak asks you to choose X not greater than m. Also, he wants to maximize the number of blocks in the tower at the end (however, he still behaves greedily). Secondarily, he wants to maximize X.
Can you help Limak? Find the maximum number of blocks his tower can have and the maximum X ≤ m that results this number of blocks.
-----Input-----
The only line of the input contains one integer m (1 ≤ m ≤ 10^15), meaning that Limak wants you to choose X between 1 and m, inclusive.
-----Output-----
Print two integers — the maximum number of blocks in the tower and the maximum required total volume X, resulting in the maximum number of blocks.
-----Examples-----
Input
48
Output
9 42
Input
6
Output
6 6
-----Note-----
In the first sample test, there will be 9 blocks if you choose X = 23 or X = 42. Limak wants to maximize X secondarily so you should choose 42.
In more detail, after choosing X = 42 the process of building a tower is: Limak takes a block with side 3 because it's the biggest block with volume not greater than 42. The remaining volume is 42 - 27 = 15. The second added block has side 2, so the remaining volume is 15 - 8 = 7. Finally, Limak adds 7 blocks with side 1, one by one.
So, there are 9 blocks in the tower. The total volume is is 3^3 + 2^3 + 7·1^3 = 27 + 8 + 7 = 42. | def g(m, s, n):
k = int(m ** (1 / 3))
if m == 0 or k == 1: return s + m, n + m
x, y = k ** 3, (k - 1) ** 3
a = g(m - x, s + x, n + 1)
b = g(x - y - 1, s + y, n + 1)
return b if a[1] < b[1] else a
s, n = g(int(input()), 0, 0)
print(n, s) | python | test | qsol | codeparrot/apps | all |
Solve in Python:
Task
======
Make a custom esolang interpreter for the language [InfiniTick](https://esolangs.org/wiki/InfiniTick). InfiniTick is a descendant of [Tick](https://esolangs.org/wiki/tick) but also very different. Unlike Tick, InfiniTick has 8 commands instead of 4. It also runs infinitely, stopping the program only when an error occurs. You may choose to do the [Tick](https://www.codewars.com/kata/esolang-tick) kata first.
Syntax/Info
======
InfiniTick runs in an infinite loop. This makes it both harder and easier to program in. It has an infinite memory of bytes and an infinite output amount. The program only stops when an error is reached. The program is also supposed to ignore non-commands.
Commands
======
`>`: Move data selector right.
`<`: Move data selector left.
`+`: Increment amount of memory cell. Truncate overflow: 255+1=0.
`-`: Decrement amount of memory cell. Truncate overflow: 0-1=255.
`*`: Add ascii value of memory cell to the output tape.
`&`: Raise an error, ie stop the program.
`/`: Skip next command if cell value is zero.
`\`: Skip next command if cell value is nonzero.
Examples
======
**Hello world!**
The following is a valid hello world program in... | from collections import defaultdict
from itertools import cycle
def interpreter(tape):
i, skip, D, res = 0, False, defaultdict(int), []
for c in cycle(tape):
if skip: skip = False
elif c == '>': i += 1
elif c == '<': i -= 1
elif c == '+': D[i] = (D[i] + 1)%256
elif c == '-': D[i] = (D[i] - 1)%256
elif c == '*': res.append(chr(D[i]))
elif c == '&': break
elif c == '/': skip = not D[i]
elif c == '\\': skip = D[i]
return ''.join(res) | python | train | qsol | codeparrot/apps | all |
I found an interesting problem on https://www.codewars.com/kata/5a32526ae1ce0ec0f10000b2:
Given an integer, take the (mean) average of each pair of consecutive digits. Repeat this process until you have a single integer, then return that integer. e.g.
Note: if the average of two digits is not an integer, round the result **up** (e.g. the average of 8 and 9 will be 9)
## Examples
```
digitsAverage(246) ==> 4
original: 2 4 6
\ / \ /
1st iter: 3 5
\ /
2nd iter: 4
digitsAverage(89) ==> 9
original: 8 9
\ /
1st iter: 9
```
p.s. for a bigger challenge, check out the [one line version](https://www.codewars.com/kata/one-line-task-digits-average) of this kata by myjinxin2015!
I tried it in Python, but could not do it. Can you solve it? | import math
def digits_average(input):
m = str(input)
for i in range(len(str(input))-1):
m = ''.join(str(math.ceil(int(m[i])/2 + int(m[i+1])/2)) for i in range(len(m) - 1))
return int(m) | python | train | abovesol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/641/D:
Little Artyom decided to study probability theory. He found a book with a lot of nice exercises and now wants you to help him with one of them.
Consider two dices. When thrown each dice shows some integer from 1 to n inclusive. For each dice the probability of each outcome is given (of course, their sum is 1), and different dices may have different probability distributions.
We throw both dices simultaneously and then calculate values max(a, b) and min(a, b), where a is equal to the outcome of the first dice, while b is equal to the outcome of the second dice. You don't know the probability distributions for particular values on each dice, but you know the probability distributions for max(a, b) and min(a, b). That is, for each x from 1 to n you know the probability that max(a, b) would be equal to x and the probability that min(a, b) would be equal to x. Find any valid probability distribution for values on the dices. It's guaranteed that the input data is consistent, that is, at least one solution exists.
-----Input-----
First line contains the integer n (1 ≤ n ≤ 100 000) — the number of different values for both dices.
Second line contains an array consisting of n real values with up to 8 digits after the decimal point — probability distribution for max(a, b), the i-th of these values equals to the probability that max(a, b) = i. It's guaranteed that the sum of these values for one dice is 1. The third line contains the description of the distribution min(a, b) in the same format.
-----Output-----
Output two descriptions of the probability distribution for a on the first line and for b on the second line.
The answer will be considered correct if each value of max(a, b) and min(a, b) probability distribution values does not differ by more than 10^{ - 6} from ones given in input. Also, probabilities should be non-negative and their sums should differ from 1 by no more than 10^{ - 6}.
-----Examples-----
Input
2
0.25 0.75
0.75 0.25
Output
0.5 0.5
0.5 0.5
Input
3
0.125 0.25 0.625
0.625 0.25...
I tried it in Python, but could not do it. Can you solve it? | def tle():
k=0
while (k>=0):
k+=1
def quad(a, b, c):
disc = (b**2-4*a*c)
if disc<0:
disc=0
disc = (disc)**0.5
return ((-b+disc)/2/a, (-b-disc)/2/a)
x = int(input())
y = list(map(float, input().strip().split(' ')))
z = list(map(float, input().strip().split(' ')))
py = [0, y[0]]
for i in range(1, x):
py.append(py[-1]+y[i])
z.reverse()
pz = [0, z[0]]
for i in range(1, x):
pz.append(pz[-1]+z[i])
pz.reverse()
k = []
for i in range(0, x+1):
k.append(py[i]+1-pz[i])
l = [0]
for i in range(x):
l.append(k[i+1]-k[i])
#a[i]+b[i]
s1 = 0
s2 = 0
avals = []
bvals = []
for i in range(1, x+1):
a, b = (quad(-1, s1+l[i]-s2, (s1+l[i])*s2-py[i]))
if b<0 or l[i]-b<0:
a, b = b, a
if a<0 and b<0:
a=0
b=0
bvals.append(b)
avals.append(l[i]-b)
s1+=avals[-1]
s2+=bvals[-1]
for i in range(len(avals)):
if abs(avals[i])<=10**(-10):
avals[i] = 0
if abs(bvals[i])<=10**(-10):
bvals[i] = 0
print(' '.join([str(i) for i in avals]))
print(' '.join([str(i) for i in bvals])) | python | test | abovesol | codeparrot/apps | all |
I found an interesting problem on https://www.codewars.com/kata/5ecc1d68c6029000017d8aaf:
In this kata, your task is to find the maximum sum of any straight "beam" on a hexagonal grid, where its cell values are determined by a finite integer sequence seq.
In this context, a beam is a linear sequence of cells in any of the 3 pairs of opposing sides of a hexagon. We'll refer to the sum of a beam's integer values as the "beam value".Refer to the example below for further clarification.
Input
Your function will receive two arguments:
n : the length of each side of the hexagonal grid, where 2 <= n < 100
seq : a finite sequence of (positive and/or nonpositive) integers with a length >= 1The sequence is used to populate the cells of the grid and should be repeated as necessary.The sequence type will be dependent on the language (e.g. array for JavaScript, tuple for Python, etc.).
Output
Your function should return the largest beam value as an integer.
Test Example
In our test example, we have the following arguments:
n = 4
seq = [2, 4, 6, 8]
Below is the hexagonal grid determined by our example arguments;
the sequence repeats itself from left to right, then top to bottom.
2 4 6 8
2 4 6 8 2
4 6 8 2 4 6
8 2 4 6 8 2 4
6 8 2 4 6 8
2 4 6 8 2
4 6 8 2
The three diagrams below illustrate the "beams" in the hexagonal grid above.
In the grid on the left, the horizontal beams are highlighted by their likewise colors,
and the value of each beam is given to its right.
In the center grid, the beams highlighted go from upper-right to bottom-left (and vice-versa).
In the grid on the right, the beams highlighted go from upper-left to bottom-right (and vice-versa).
2 4 6 8 -> 20 2 4 6 8 2 4 6 8
2 4 6 8 2 -> 22 2 4 6 8 2 2 4 6 8 2
4 6 8 2 4 6 -> 30 4 6 8 2 4 6 4 6 8 2 4 6
8 2 4 6 8 2 4 -> 34 8 2 4 6 8 2 4 8 2 4 6 8 2 4
6 8 2 4 6 8 -> 34 6 8 2 4 6 8 6 8 2 4 6 8
2 4 6 8 2 -> 22 2 4 6 8 2 2 4 6 8 2
4 6 8 2 -> 20 4 6 8 2 4 6 8 2
The maximum beam value in our example is 34.
Test...
I tried it in Python, but could not do it. Can you solve it? | from itertools import cycle
def max_hexagon_beam(n: int,seq: tuple):
l=n*2-1 #the number of rows of the hexagon
ll =[l-abs(n-i-1) for i in range(l)] #the lengths of each row
c=cycle(seq)
hex = [[next(c) for i in range(j)] for j in ll] # the hexagon
sums = [sum(i)for i in hex] # the straight lines
for index, i in enumerate(ll):
start_row = [0, index%n + 1][index>=n]
hex_row=[]
hex_row2=[]
for j in range(i):
y=j+start_row #the y-axis or the row used
x=index-[0, y%n + 1][y>=n] # the x-axis or the position in the row.
hex_row.append(hex[y][x]) # the line going right-up
hex_row2.append(hex[y][-1-x]) # the line going right-down
sums +=[sum(hex_row), sum(hex_row2)]
sums.sort()
return sums[-1]
# I also considered extending the hexagon with edges of zeros so the x and y would have less possibility to go out of the list. | python | train | abovesol | codeparrot/apps | all |
Solve in Python:
# Task
IONU Satellite Imaging, Inc. records and stores very large images using run length encoding. You are to write a program that reads a compressed image, finds the edges in the image, as described below, and outputs another compressed image of the detected edges.
A simple edge detection algorithm sets an output pixel's value to be the maximum absolute value of the differences between it and all its surrounding pixels in the input image. Consider the input image below:
![](http://media.openjudge.cn/images/1009_1.jpg)
The upper left pixel in the output image is the maximum of the values |15-15|,|15-100|, and |15-100|, which is 85. The pixel in the 4th row, 2nd column is computed as the maximum of |175-100|, |175-100|, |175-100|, |175-175|, |175-25|, |175-175|,|175-175|, and |175-25|, which is 150.
Images contain 2 to 1,000,000,000 (10^9) pixels. All images are encoded using run length encoding (RLE). This is a sequence of pairs, containing pixel value (0-255) and run length (1-10^9). Input images have at most 1,000 of these pairs. Successive pairs have different pixel values. All lines in an image contain the same number of pixels.
For the iamge as the example above, the RLE encoding string is `"7 15 4 100 15 25 2 175 2 25 5 175 2 25 5"`
```
Each image starts with the width, in pixels(means the first number 7)
This is followed by the RLE pairs(two number is a pair).
7 ----> image width
15 4 ----> a pair(color value + number of pixel)
100 15 ...........ALL.......................
25 2 ..........THESE......................
175 2 ...........ARE.......................
25 5 ..........PAIRS......................
175 2 ...........LIKE......................
25 5 ..........ABOVE......................
```
Your task is to calculate the result by using the edge detection algorithm above. Returns a encoding string in the same format as the input string.
# Exaple
`Please see examples in the example test block.`
# Input/Output
-... | from itertools import chain
def parse_ascii(image_ascii):
""" Parses the input string
Returns a 3-tuple:
- :width: - the width in pixels of the image
- :height: - the height in pixels of the image
- List of pairs (pixel_value, run_length)
run_length is the number of successive pixels with the same value when scanning
the row, including the following rows
Assumes with no check:
:run_length: > 0 for all cases
Successive pairs have different :pixel_value:
The sum of all pixels is a multiple of :width:
>>> parse_ascii("3 43 4 24 2")
(3, 2, [(43, 4), (24, 2)])
"""
values = [int(v) for v in image_ascii.split()]
width = values[0]
pixel_runs = list(zip(values[1::2], values[2::2]))
height = sum(values[2::2]) // width
return width, height, pixel_runs
def get_intervals(pixel_runs):
""" Denominates the pixel runs with an absolute position
Given the pairs (pixel_value, run_length), returns triplets (start, end, pixel_value)
The pixel positions are numbered successively starting with the first row from left
to right and then the following rows. :start: and :end: are given as such positions.
:start: points to the first pixel of the run with :pixel_value:
:end: points to the position after the the pixel ending the run
>>> list(get_intervals([(34,4),(98,5),(12,40)]))
[(0, 4, 34), (4, 9, 98), (9, 49, 12)]
"""
pos = 0
for (pixel_value, run_length) in pixel_runs:
yield (pos, pos + run_length, pixel_value)
pos += run_length
def get_shifted_intervals(intervals, offset, width, height):
""" Shifts the intervals, and corrects for end of row
Returns the intervals (start, end, pixel_value) with the variables :start: and :end:
shifted :offset: positions.
If :offset: is positive, fills the first positions with a new (0, :offset:, None) interval,
and removes the intervals and interval parts correspoding to the last :offset:... | python | train | qsol | codeparrot/apps | all |
Solve in Python:
Well, those numbers were right and we're going to feed their ego.
Write a function, isNarcissistic, that takes in any amount of numbers and returns true if all the numbers are narcissistic. Return false for invalid arguments (numbers passed in as strings are ok).
For more information about narcissistic numbers (and believe me, they love it when you read about them) follow this link: https://en.wikipedia.org/wiki/Narcissistic_number | is_narcissistic=lambda*a:all(n.isdigit()and int(n)==sum(int(d)**len(n)for d in n)for n in map(str,a)) | python | train | qsol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/1144/E:
You are given two strings $s$ and $t$, both consisting of exactly $k$ lowercase Latin letters, $s$ is lexicographically less than $t$.
Let's consider list of all strings consisting of exactly $k$ lowercase Latin letters, lexicographically not less than $s$ and not greater than $t$ (including $s$ and $t$) in lexicographical order. For example, for $k=2$, $s=$"az" and $t=$"bf" the list will be ["az", "ba", "bb", "bc", "bd", "be", "bf"].
Your task is to print the median (the middle element) of this list. For the example above this will be "bc".
It is guaranteed that there is an odd number of strings lexicographically not less than $s$ and not greater than $t$.
-----Input-----
The first line of the input contains one integer $k$ ($1 \le k \le 2 \cdot 10^5$) — the length of strings.
The second line of the input contains one string $s$ consisting of exactly $k$ lowercase Latin letters.
The third line of the input contains one string $t$ consisting of exactly $k$ lowercase Latin letters.
It is guaranteed that $s$ is lexicographically less than $t$.
It is guaranteed that there is an odd number of strings lexicographically not less than $s$ and not greater than $t$.
-----Output-----
Print one string consisting exactly of $k$ lowercase Latin letters — the median (the middle element) of list of strings of length $k$ lexicographically not less than $s$ and not greater than $t$.
-----Examples-----
Input
2
az
bf
Output
bc
Input
5
afogk
asdji
Output
alvuw
Input
6
nijfvj
tvqhwp
Output
qoztvz
I tried it in Python, but could not do it. Can you solve it? | import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,copy,functools
sys.setrecursionlimit(10**7)
inf = 10**20
eps = 1.0 / 10**10
mod = 10**9+7
dd = [(-1,0),(0,1),(1,0),(0,-1)]
ddn = [(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)]
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return input()
def pf(s): return print(s, flush=True)
def main():
n = I()
s = [ord(c)-ord('a') for c in S()]
t = [ord(c)-ord('a') for c in S()]
r = [s[i]+t[i] for i in range(n)]
for i in range(n-1,0,-1):
if r[i] >= 26:
r[i] -= 26
r[i-1] += 1
k = 0
rs = []
for i in range(n):
b = r[i] + k
rs.append(chr(b // 2 + ord('a')))
if b % 2 == 0:
k = 0
else:
k = 26
return ''.join(rs)
print(main()) | python | test | abovesol | codeparrot/apps | all |
Solve in Python:
In some other world, today is Christmas Eve.
There are N trees planted in Mr. Takaha's garden. The height of the i-th tree (1 \leq i \leq 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 h_{max} meters, and the height of the shortest decorated tree be h_{min} meters. The smaller the value h_{max} - h_{min} is, the better. What is the minimum possible value of h_{max} - h_{min}?
-----Constraints-----
- 2 \leq K < N \leq 10^5
- 1 \leq h_i \leq 10^9
- h_i is an integer.
-----Input-----
Input is given from Standard Input in the following format:
N K
h_1
h_2
:
h_N
-----Output-----
Print the minimum possible value of h_{max} - h_{min}.
-----Sample Input-----
5 3
10
15
11
14
12
-----Sample Output-----
2
If we decorate the first, third and fifth trees, h_{max} = 12, h_{min} = 10 so h_{max} - h_{min} = 2. This is optimal. | n,k = map(int,input().split())
s = []
for i in range(n):
s.append(int(input()))
s.sort()
s.reverse()
ans = s[0]-s[-1]
for i in range(n-k+1):
ans = min(ans,s[i]-s[i+k-1])
print(ans) | python | test | qsol | codeparrot/apps | all |
I found an interesting problem on https://leetcode.com/problems/maximum-width-of-binary-tree/:
Given a binary tree, write a function to get the maximum width of the given tree. The width of a tree is the maximum width among all levels. The binary tree has the same structure as a full binary tree, but some nodes are null.
The width of one level is defined as the length between the end-nodes (the leftmost and right most non-null nodes in the level, where the null nodes between the end-nodes are also counted into the length calculation.
Example 1:
Input:
1
/ \
3 2
/ \ \
5 3 9
Output: 4
Explanation: The maximum width existing in the third level with the length 4 (5,3,null,9).
Example 2:
Input:
1
/
3
/ \
5 3
Output: 2
Explanation: The maximum width existing in the third level with the length 2 (5,3).
Example 3:
Input:
1
/ \
3 2
/
5
Output: 2
Explanation: The maximum width existing in the second level with the length 2 (3,2).
Example 4:
Input:
1
/ \
3 2
/ \
5 9
/ \
6 7
Output: 8
Explanation:The maximum width existing in the fourth level with the length 8 (6,null,null,null,null,null,null,7).
Note:
Answer will in the range of 32-bit signed integer.
I tried it in Python, but could not do it. Can you solve it? | class Solution:
def widthOfBinaryTree(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if not root: return 0
maxlen=1
start=1
end=1
tlen=1
l=[[root,1]]
while tlen:
llen=tlen
tlen=0
while llen:
cur=l.pop(0)
llen-=1
if cur[0]:
l.append([cur[0].left,2*cur[1]-1])
l.append([cur[0].right,2*cur[1]])
tlen+=2
if len(l)>0:
for item in reversed(l):
if item[0]:
end=item[1]
break
if end != item[1]: return maxlen
for item in l:
if item[0]:
start=item[1]
break;
end = end - start + 1
if(end > maxlen): maxlen=end
start=end=-1;
return maxlen | python | train | abovesol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/621/B:
Today, Wet Shark is given n bishops on a 1000 by 1000 grid. Both rows and columns of the grid are numbered from 1 to 1000. Rows are numbered from top to bottom, while columns are numbered from left to right.
Wet Shark thinks that two bishops attack each other if they share the same diagonal. Note, that this is the only criteria, so two bishops may attack each other (according to Wet Shark) even if there is another bishop located between them. Now Wet Shark wants to count the number of pairs of bishops that attack each other.
-----Input-----
The first line of the input contains n (1 ≤ n ≤ 200 000) — the number of bishops.
Each of next n lines contains two space separated integers x_{i} and y_{i} (1 ≤ x_{i}, y_{i} ≤ 1000) — the number of row and the number of column where i-th bishop is positioned. It's guaranteed that no two bishops share the same position.
-----Output-----
Output one integer — the number of pairs of bishops which attack each other.
-----Examples-----
Input
5
1 1
1 5
3 3
5 1
5 5
Output
6
Input
3
1 1
2 3
3 5
Output
0
-----Note-----
In the first sample following pairs of bishops attack each other: (1, 3), (1, 5), (2, 3), (2, 4), (3, 4) and (3, 5). Pairs (1, 2), (1, 4), (2, 5) and (4, 5) do not attack each other because they do not share the same diagonal.
I tried it in Python, but could not do it. Can you solve it? | def nC2(n):
return n * (n - 1) // 2
SIZE = 1000
N = int(input())
a = [[0] * SIZE for i in range(SIZE)]
for i in range(N):
x, y = map(int, input().split())
a[x-1][y-1] = 1
ans = 0
#1
for sx in range(SIZE):
t_cnt = 0
x = sx; y = 0;
while x >= 0:
t_cnt += a[x][y]
x -= 1; y += 1
ans += nC2(t_cnt)
#2
for sy in range(1, SIZE):
t_cnt = 0
x = SIZE - 1; y = sy;
while y < SIZE:
t_cnt += a[x][y]
x -= 1; y += 1
ans += nC2(t_cnt)
#3
for sx in range(SIZE):
t_cnt = 0
x = sx; y = 0;
while x < SIZE:
t_cnt += a[x][y]
x += 1; y += 1
ans += nC2(t_cnt)
#4
for sy in range(1, SIZE):
t_cnt = 0
x = 0; y = sy;
while y < SIZE:
t_cnt += a[x][y]
x += 1; y += 1
ans += nC2(t_cnt)
print(ans) | python | test | abovesol | codeparrot/apps | all |
Solve in Python:
Given an array of integers nums sorted in ascending order, find the starting and ending position of a given target value.
Your algorithm's runtime complexity must be in the order of O(log n).
If the target is not found in the array, return [-1, -1].
Example 1:
Input: nums = [5,7,7,8,8,10], target = 8
Output: [3,4]
Example 2:
Input: nums = [5,7,7,8,8,10], target = 6
Output: [-1,-1] | class Solution:
def searchRange(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
#m = int(len(nums)/2)
#upper, lower = nums[:m], nums[m:]
s, e = -1, -1
l, u = 0, len(nums)-1
if not nums or target > nums[u] or target < nums[l]:
return [s, e]
m = int((l+u)/2)
while u >= l:
if nums[m] > target:
if m == u:
break
u = m
#if int((l+u)/2) == u:
# break
m = int((l+u)/2)
elif nums[m] < target:
l = m
if int((l+u)/2) == l:
m = l+1
else:
m = int((l+u)/2)
else:
s = e = m
while 0 < s and nums[s-1] == nums[s]:
s-=1
while e < len(nums)-1 and nums[e+1] == nums[e]:
e+=1
break
return [s, e] | python | test | qsol | codeparrot/apps | all |
I found an interesting problem on https://www.codewars.com/kata/5ac69d572f317bdfc3000124:
In mathematics, a **pandigital number** is a number that in a given base has among its significant digits each digit used in the base at least once. For example, 1234567890 is a pandigital number in base 10.
For simplification, in this kata, we will consider pandigital numbers in *base 10* and with all digits used *exactly once*. The challenge is to calculate a sorted sequence of pandigital numbers, starting at a certain `offset` and with a specified `size`.
Example:
```python
> get_sequence(0, 5)
[1023456789, 1023456798, 1023456879, 1023456897, 1023456978]
```
Rules:
- We are looking for positive pandigital numbers in base 10.
- Each digit should occur `exactly once`.
- A pandigital number can't start with digit zero.
- The offset is an integer (negative, zero or positive number) (long in Java)
- The size is a positive integer number (int in Java)
- Return the `size` pandigital numbers which are not smaller than the `offset`. If there is not enough `size` pandigital numbers, just return all of them.
- Return an empty array if nothing is found.
I tried it in Python, but could not do it. Can you solve it? | from itertools import permutations as perms
def is_pand(n):
return len(set(list(str(n)))) == len(str(n))
def next_pan(n):
while True:
if is_pand(n):yield n
n += 1
def get_sequence(n, k):
if n < 1023456789: n = 1023456789
elif n >= 9999999999: return []
if not is_pand(n): n = next(next_pan(n))
res = []
for i in next_pan(n):
res.append(i)
if len(res)== k: break
return res | python | train | abovesol | codeparrot/apps | all |
Solve in Python:
Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.
Example 1:
Input: 1->2->3->3->4->4->5
Output: 1->2->5
Example 2:
Input: 1->1->1->2->3
Output: 2->3 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
from collections import OrderedDict
class Solution:
def deleteDuplicates(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
lookup = OrderedDict()
while head:
if head.val in lookup:
lookup[head.val] += 1
else:
lookup[head.val] = 1
head = head.next
previous = None
head = None
for key in lookup:
if (lookup[key] != 1):
continue
node = ListNode(key)
if previous:
previous.next = node
else:
head = node
previous = node
return(head) | python | train | qsol | codeparrot/apps | all |
I found an interesting problem on https://www.codewars.com/kata/53c93982689f84e321000d62:
~~~if-not:java
You have to code a function **getAllPrimeFactors** wich take an integer as parameter and return an array containing its prime decomposition by ascending factors, if a factors appears multiple time in the decomposition it should appear as many time in the array.
exemple: `getAllPrimeFactors(100)` returns `[2,2,5,5]` in this order.
This decomposition may not be the most practical.
You should also write **getUniquePrimeFactorsWithCount**, a function which will return an array containing two arrays: one with prime numbers appearing in the decomposition and the other containing their respective power.
exemple: `getUniquePrimeFactorsWithCount(100)` returns `[[2,5],[2,2]]`
You should also write **getUniquePrimeFactorsWithProducts** an array containing the prime factors to their respective powers.
exemple: `getUniquePrimeFactorsWithProducts(100)` returns `[4,25]`
~~~
~~~if:java
You have to code a function **getAllPrimeFactors** wich take an integer as parameter and return an array containing its prime decomposition by ascending factors, if a factors appears multiple time in the decomposition it should appear as many time in the array.
exemple: `getAllPrimeFactors(100)` returns `[2,2,5,5]` in this order.
This decomposition may not be the most practical.
You should also write **getUniquePrimeFactorsWithCount**, a function which will return an array containing two arrays: one with prime numbers appearing in the decomposition and the other containing their respective power.
exemple: `getUniquePrimeFactorsWithCount(100)` returns `[[2,5],[2,2]]`
You should also write **getPrimeFactorPotencies** an array containing the prime factors to their respective powers.
exemple: `getPrimeFactorPotencies(100)` returns `[4,25]`
~~~
Errors, if:
* `n` is not a number
* `n` not an integer
* `n` is negative or 0
The three functions should respectively return `[]`, `[[],[]]` and `[]`.
Edge cases:
* if `n=0`, the function should respectively return `[]`, `[[],[]]` and `[]`.
* if `n=1`, the...
I tried it in Python, but could not do it. Can you solve it? | def getAllPrimeFactors(n):
if n == 0: return []
elif n == 1: return [1]
elif type(n) != int: return errora
elif n < 0: return errora
allfacts = []
current = 2
n_copy = n
while current <= n:
if n_copy % current == 0:
allfacts.append(current)
n_copy /= current
else:
current += 1
return allfacts
def getUniquePrimeFactorsWithCount(n):
if type(n) != int: return errorb
elif n < 0: return errorb
primes = []
power = []
listA = getAllPrimeFactors(n)
for i in range(len(listA)):
if listA[i] not in primes:
primes.append(listA[i])
power.append(1)
else:
power[-1] += 1
return [primes, power]
def getUniquePrimeFactorsWithProducts(n):
if type(n) != int: return errorc
elif n < 0: return errorc
listlist = getUniquePrimeFactorsWithCount(n)
listc = []
for i in range(len(listlist[0])):
listc.append(listlist[0][i] ** listlist[1][i])
return listc
errora = []
errorb = [[], []]
errorc = [] | python | train | abovesol | codeparrot/apps | all |
Solve in Python:
Given an array A of positive lengths, return the largest perimeter of a triangle with non-zero area, formed from 3 of these lengths.
If it is impossible to form any triangle of non-zero area, return 0.
Example 1:
Input: [2,1,2]
Output: 5
Example 2:
Input: [1,2,1]
Output: 0
Example 3:
Input: [3,2,3,4]
Output: 10
Example 4:
Input: [3,6,2,3]
Output: 8
Note:
3 <= A.length <= 10000
1 <= A[i] <= 10^6 | class Solution:
def largestPerimeter(self, A: List[int]) -> int:
if len(A)<3:
return 0
A.sort(reverse=True)
while len(A)>2:
max_num = A.pop(0)
if max_num >= A[0] + A[1]:
continue
else:
return max_num+A[0]+A[1]
return 0 | python | train | qsol | codeparrot/apps | all |
I found an interesting problem on https://atcoder.jp/contests/abc086/tasks/abc086_a:
AtCoDeer the deer found two positive integers, a and b.
Determine whether the product of a and b is even or odd.
-----Constraints-----
- 1 ≤ a,b ≤ 10000
- a and b are integers.
-----Input-----
Input is given from Standard Input in the following format:
a b
-----Output-----
If the product is odd, print Odd; if it is even, print Even.
-----Sample Input-----
3 4
-----Sample Output-----
Even
As 3 × 4 = 12 is even, print Even.
I tried it in Python, but could not do it. Can you solve it? | a,b=list(map(int,input().split()))
if(a*b)%2==0:
print('Even')
else:
print('Odd') | python | test | abovesol | codeparrot/apps | all |
Solve in Python:
An array is called `centered-N` if some `consecutive sequence` of elements of the array sum to `N` and this sequence is preceded and followed by the same number of elements.
Example:
```
[3,2,10,4,1,6,9] is centered-15
because the sequence 10,4,1 sums to 15 and the sequence
is preceded by two elements [3,2] and followed by two elements [6,9]
```
Write a method called `isCenteredN` that returns :
- `true` if its array argument is `not empty` and `centered-N` or empty and centered-0
- otherwise returns `false`. | def is_centered(arr,n):
for i in range(len(arr)):
for j in range(len(arr)+1):
if j>i:
if sum(arr[i:j]) == n and i == len(arr)-j:
return True
return True if n==0 and arr!=arr[::-1] else False | python | train | qsol | codeparrot/apps | all |
I found an interesting problem on https://www.codewars.com/kata/5897cdc26551af891c000124:
Hofstadter sequences are a family of related integer sequences, among which the first ones were described by an American professor Douglas Hofstadter in his book Gödel, Escher, Bach.
### Task
Today we will be implementing the rather chaotic recursive sequence of integers called Hofstadter Q.
The Hofstadter Q is defined as:
As the author states in the aforementioned book:It is reminiscent of the Fibonacci definition in that each new value is a sum of two
previous values-but not of the immediately previous two values. Instead, the two
immediately previous values tell how far to count back to obtain the numbers to be added
to make the new value.
The function produces the starting sequence:
`1, 1, 2, 3, 3, 4, 5, 5, 6 . . .`
Test info: 100 random tests, n is always positive
Good luck!
I tried it in Python, but could not do it. Can you solve it? | import sys; sys.setrecursionlimit(10000)
from functools import lru_cache
@lru_cache(maxsize=None)
def Q(n):
if n <= 2:
return 1
return Q(n - Q(n-1)) + Q(n - Q(n-2))
def hofstadter_Q(n):
return Q(n) | python | train | abovesol | codeparrot/apps | all |
I found an interesting problem on https://www.codechef.com/problems/PRFYIT:
We say that a binary string (a string containing only characters '0' and '1') is pure if it does not contain either of the strings "0101" or "1010" as a subsequence.
Recall that string T is a subsequence of string S if we can delete some of the letters of S (possibly none) such that the resulting string will become T.
You are given a binary string $S$ with length $N$. We want to make this string pure by deleting some (possibly zero) characters from it. What is the minimum number of characters we have to delete?
-----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$ with length $N$.
-----Output-----
For each test case, print a single line containing one integer — the minimum number of characters we have to delete from $S$.
-----Constraints-----
- $1 \le T \le 40$
- $1 \le N \le 1,000$
- $S$ contains only characters '0' and '1'
-----Example Input-----
4
010111101
1011100001011101
0110
111111
-----Example Output-----
2
3
0
0
-----Explanation-----
Example case 1: We can delete the first and third character of our string. There is no way to make the string pure by deleting only one character.
Example case 3: The given string is already pure, so the answer is zero.
I tried it in Python, but could not do it. Can you solve it? | for _ in range(int(input())):
bi = input().strip()
dp = [0 if i < 2 else len(bi) for i in range(6)]
for c in bi:
if c == '1':
dp[3] = min(dp[3], dp[0])
dp[0] += 1
dp[5] = min(dp[5], dp[2])
dp[2] += 1
dp[4] += 1
else:
dp[2] = min(dp[2], dp[1])
dp[1] += 1
dp[4] = min(dp[4], dp[3])
dp[3] += 1
dp[5] += 1
print(min(dp)) | python | train | abovesol | codeparrot/apps | all |
Solve in Python:
We have A cards, each of which has an integer 1 written on it. Similarly, we also have B cards with 0s and C cards with -1s.
We will pick up K among these cards. What is the maximum possible sum of the numbers written on the cards chosen?
-----Constraints-----
- All values in input are integers.
- 0 \leq A, B, C
- 1 \leq K \leq A + B + C \leq 2 \times 10^9
-----Input-----
Input is given from Standard Input in the following format:
A B C K
-----Output-----
Print the maximum possible sum of the numbers written on the cards chosen.
-----Sample Input-----
2 1 1 3
-----Sample Output-----
2
Consider picking up two cards with 1s and one card with a 0.
In this case, the sum of the numbers written on the cards is 2, which is the maximum possible value. | A, B, C, K = list(map(int, input().split()))
a, c = min(A, K), max(0, min(C, K - A - B))
print((a - c)) | python | test | qsol | codeparrot/apps | all |
Solve in Python:
There are $n$ warriors in a row. The power of the $i$-th warrior is $a_i$. All powers are pairwise distinct.
You have two types of spells which you may cast: Fireball: you spend $x$ mana and destroy exactly $k$ consecutive warriors; Berserk: you spend $y$ mana, choose two consecutive warriors, and the warrior with greater power destroys the warrior with smaller power.
For example, let the powers of warriors be $[2, 3, 7, 8, 11, 5, 4]$, and $k = 3$. If you cast Berserk on warriors with powers $8$ and $11$, the resulting sequence of powers becomes $[2, 3, 7, 11, 5, 4]$. Then, for example, if you cast Fireball on consecutive warriors with powers $[7, 11, 5]$, the resulting sequence of powers becomes $[2, 3, 4]$.
You want to turn the current sequence of warriors powers $a_1, a_2, \dots, a_n$ into $b_1, b_2, \dots, b_m$. Calculate the minimum amount of mana you need to spend on it.
-----Input-----
The first line contains two integers $n$ and $m$ ($1 \le n, m \le 2 \cdot 10^5$) — the length of sequence $a$ and the length of sequence $b$ respectively.
The second line contains three integers $x, k, y$ ($1 \le x, y, \le 10^9; 1 \le k \le n$) — the cost of fireball, the range of fireball and the cost of berserk respectively.
The third line contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le n$). It is guaranteed that all integers $a_i$ are pairwise distinct.
The fourth line contains $m$ integers $b_1, b_2, \dots, b_m$ ($1 \le b_i \le n$). It is guaranteed that all integers $b_i$ are pairwise distinct.
-----Output-----
Print the minimum amount of mana for turning the sequnce $a_1, a_2, \dots, a_n$ into $b_1, b_2, \dots, b_m$, or $-1$ if it is impossible.
-----Examples-----
Input
5 2
5 2 3
3 1 4 5 2
3 5
Output
8
Input
4 4
5 1 4
4 3 1 2
2 4 3 1
Output
-1
Input
4 4
2 1 11
1 3 2 4
1 3 2 4
Output
0 | n, m = list(map(int, input().split()))
x, k, y= list(map(int, input().split()))
start_ls = list(map(int, input().split()))
end_ls = list(map(int, input().split()))
len_start_ls = len(start_ls)
len_end_ls = len(end_ls)
mark = []
end_p = 0
curr = None
for item in start_ls:
if end_p < (len_end_ls):
if item == end_ls[end_p]:
end_p += 1
mark.append(0)
curr = item
else:
if curr is not None:
if item > curr:
mark.append(1)
else:
mark.append(2)
else:
mark.append(1)
else:
if curr is not None:
if item > curr:
mark.append(1)
else:
mark.append(2)
else:
mark.append(1)
if end_p < (len_end_ls):
print(-1)
else:
end_p = 0
curr = None
end_ls = end_ls[::-1]
mark = mark[::-1]
for idx, item in enumerate(start_ls[::-1]):
if end_p < (len_end_ls):
if item == end_ls[end_p]:
end_p += 1
curr = item
else:
if curr is not None:
if item < curr:
mark[idx] = 2
else:
if curr is not None:
if item < curr:
mark[idx] = 2
mark = mark[::-1]
if y*k >= x:
smite = True
else:
smite = False
segments = []
segment = [0,True]
for idx, item in enumerate(mark):
if item != 0:
segment[0] += 1
if item == 1:
segment[1] = False
elif item == 0:
if segment[0] != 0:
segments.append(segment)
segment = [0,True]
if segment[0] != 0:
segments.append(segment)
poss = True
res = 0
for segment in segments:
if segment[0] < k and not segment[1]:
poss = False
break
elif segment[0] < k and segment[1]:
... | python | test | qsol | codeparrot/apps | all |
Solve in Python:
n passengers board an airplane with exactly n seats. The first passenger has lost the ticket and picks a seat randomly. But after that, the rest of passengers will:
Take their own seat if it is still available,
Pick other seats randomly when they find their seat occupied
What is the probability that the n-th person can get his own seat?
Example 1:
Input: n = 1
Output: 1.00000
Explanation: The first person can only get the first seat.
Example 2:
Input: n = 2
Output: 0.50000
Explanation: The second person has a probability of 0.5 to get the second seat (when first person gets the first seat).
Constraints:
1 <= n <= 10^5 | class Solution:
def nthPersonGetsNthSeat(self, n: int) -> float:
# if n == 1:
# return 1.0
# else:
# return 0.5
if n == 1:
return 1.0
sum_results = 0.0
for i in range(2, n+1):
p = 1/i * (1 + sum_results)
sum_results += p
return p | python | train | qsol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/276/C:
The little girl loves the problems on array queries very much.
One day she came across a rather well-known problem: you've got an array of n elements (the elements of the array are indexed starting from 1); also, there are q queries, each one is defined by a pair of integers l_{i}, r_{i} (1 ≤ l_{i} ≤ r_{i} ≤ n). You need to find for each query the sum of elements of the array with indexes from l_{i} to r_{i}, inclusive.
The little girl found the problem rather boring. She decided to reorder the array elements before replying to the queries in a way that makes the sum of query replies maximum possible. Your task is to find the value of this maximum sum.
-----Input-----
The first line contains two space-separated integers n (1 ≤ n ≤ 2·10^5) and q (1 ≤ q ≤ 2·10^5) — the number of elements in the array and the number of queries, correspondingly.
The next line contains n space-separated integers a_{i} (1 ≤ a_{i} ≤ 2·10^5) — the array elements.
Each of the following q lines contains two space-separated integers l_{i} and r_{i} (1 ≤ l_{i} ≤ r_{i} ≤ n) — the i-th query.
-----Output-----
In a single line print a single integer — the maximum sum of query replies after the array elements are reordered.
Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
-----Examples-----
Input
3 3
5 3 2
1 2
2 3
1 3
Output
25
Input
5 3
5 2 4 1 3
1 5
2 3
2 3
Output
33
I tried it in Python, but could not do it. Can you solve it? | n, q = map(int, input().split())
t = [0] + list(map(int, input().split()))
p = [0] * (n + 1)
for i in range(q):
l, r = map(int, input().split())
p[l - 1] += 1
p[r] -= 1
for i in range(1, n + 1):
p[i] += p[i - 1]
t.sort()
p.sort()
j = 0
while p[j] == 0: j += 1
print(sum(p[i] * t[i] for i in range(j, n + 1))) | python | test | abovesol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/448/D:
Bizon the Champion isn't just charming, he also is very smart.
While some of us were learning the multiplication table, Bizon the Champion had fun in his own manner. Bizon the Champion painted an n × m multiplication table, where the element on the intersection of the i-th row and j-th column equals i·j (the rows and columns of the table are numbered starting from 1). Then he was asked: what number in the table is the k-th largest number? Bizon the Champion always answered correctly and immediately. Can you repeat his success?
Consider the given multiplication table. If you write out all n·m numbers from the table in the non-decreasing order, then the k-th number you write out is called the k-th largest number.
-----Input-----
The single line contains integers n, m and k (1 ≤ n, m ≤ 5·10^5; 1 ≤ k ≤ n·m).
-----Output-----
Print the k-th largest number in a n × m multiplication table.
-----Examples-----
Input
2 2 2
Output
2
Input
2 3 4
Output
3
Input
1 10 5
Output
5
-----Note-----
A 2 × 3 multiplication table looks like this:
1 2 3
2 4 6
I tried it in Python, but could not do it. Can you solve it? | from sys import stdin
n, m, k = [int(x) for x in stdin.readline().split()]
be, en = 1, k + 1
while be < en:
mid = (be + en + 1) >> 1
be1, cur = (mid + m - 1) // m, 0
for i in range(1, be1):
cur += m
for i in range(be1, n + 1):
cur += (mid - 1) // i
if cur <= k - 1:
be = mid
else:
en = mid - 1
print(be) | python | test | abovesol | codeparrot/apps | all |
Solve in Python:
Binod and his family live in Codingland. They have a festival called N-Halloween.
The festival is celebrated for N consecutive days. On each day Binod gets some candies from his mother. He may or may not take them. On a given day , Binod will be sad if he collected candies on that day and he does not have at least X candies remaining from the candies he collected that day at the end of that day . His friend Pelu who is very fond of candies asks for X candies from Binod on a day if Binod collects any candy on that day. He does so immediately after Binod collects them. Binod being a good friend never denies him.
Given a list a where ai denotes the number of candies Binod may take on the ith day and Q queries having a number X , find the maximum number of candies Binod can collect so that he won't be sad after the festival ends.
Input format:
First-line contains two integers N and Q denoting the number of festival days and number of queries respectively.
The second line is the array whose ith element is the maximum number of candies Binod may
collect on that day.
Each of the next Q lines contains the number X i.e the minimum number of candies Binod wants to have at the end of every day on which he collects any candy.
Output format:
For every query output, a single integer denoting the max number of candies Binod may
collect (for the given X ) to be happy after the festival ends.
Constraints:
1<=N,Q<=105
1<=Q<=105
0<=ai<=109
0<=X<=109
Sample Input :
5 2
4 6 5 8 7
1
2
Sample Output :
30
30
Sample Input:
6 3
20 10 12 3 30 5
2
6
13
Sample Output
77
62
30
Explanation:
In the first query of sample input 1, Binod can collect the maximum number of given chocolates for a given day each day as after the end of every day Binod will have a number of collected
chocolates on that day greater than equal to 1 even after giving 1 chocolate to Pelu. So the
the answer is 4+6+5+8+7=30. | # cook your dish here
import copy
import bisect
n,q=list(map(int,input().split()))
a=list(map(int,input().split()))
a.sort()
b=copy.copy(a)
for i in range(1,len(b)):
b[i]+=b[i-1]
##print(b)
for i in range(q):
x=int(input())
ans=bisect.bisect_left(a,x*2)
if ans==0:
ans1=b[n-1]
else:
ans1=b[n-1]-b[ans-1]
print(ans1) | python | test | qsol | codeparrot/apps | all |
I found an interesting problem on https://www.codewars.com/kata/56445cc2e5747d513c000033:
In Russia, there is an army-purposed station named UVB-76 or "Buzzer" (see also https://en.wikipedia.org/wiki/UVB-76). Most of time specific "buzz" noise is being broadcasted, but on very rare occasions, the buzzer signal is interrupted and a voice transmission in Russian takes place. Transmitted messages have always the same format like this:
MDZHB 01 213 SKIF 38 87 23 95
or:
MDZHB 80 516 GANOMATIT 21 23 86 25
Message format consists of following parts:
Initial keyword "MDZHB";
Two groups of digits, 2 digits in first and 3 in second ones;
Some keyword of arbitrary length consisting only of uppercase letters;
Final 4 groups of digits with 2 digits in each group.
Your task is to write a function that can validate the correct UVB-76 message. Function should return "True" if message is in correct format and "False" otherwise.
I tried it in Python, but could not do it. Can you solve it? | import re
def validate(message):
return bool(re.fullmatch(r'MDZHB \d{2} \d{3} [A-Z]+ \d{2} \d{2} \d{2} \d{2}', message)) | python | train | abovesol | codeparrot/apps | all |
I found an interesting problem on https://www.codewars.com/kata/5899f1df27926b7d000000eb:
The Tower of Hanoi problem involves 3 towers. A number of rings decreasing in size are placed on one tower. All rings must then be moved to another tower, but at no point can a larger ring be placed on a smaller ring.
Your task: Given a number of rings, return the MINIMUM number of moves needed to move all the rings from one tower to another.
Reference: Tower of Hanoi, Courtesy of Coolmath Games
NB: This problem may seem very complex, but in reality there is an amazingly simple formula to calculate the minimum number. Just Learn how to solve the problem via the above link (if you are not familiar with it), and then think hard. Your solution should be in no way extraordinarily long and complex. The Kata ranking is for figuring out the solution, but the coding skills required are minimal.
I tried it in Python, but could not do it. Can you solve it? | def tower_of_hanoi(rings):
moves = 0
for r in range(rings):
moves *= 2
moves += 1
return moves | python | train | abovesol | codeparrot/apps | all |
I found an interesting problem on https://www.codewars.com/kata/596c26187bd547f3a6000050:
# Task
A newspaper is published in Walrusland. Its heading is `s1` , it consists of lowercase Latin letters.
Fangy the little walrus wants to buy several such newspapers, cut out their headings, glue them one to another in order to get one big string.
After that walrus erase several letters from this string in order to get a new word `s2`.
It is considered that when Fangy erases some letter, there's no whitespace formed instead of the letter. That is, the string remains unbroken and it still only consists of lowercase Latin letters.
For example, the heading is `"abc"`. If we take two such headings and glue them one to the other one, we get `"abcabc"`. If we erase the 1st letter("a") and 5th letter("b"), we get a word `"bcac"`.
Given two string `s1` and `s2`, return the least number of newspaper headings `s1`, which Fangy will need to receive the word `s2`. If it is impossible to get the word `s2` in the above-described manner, return `-1`.
# Example
For `s1="abc", s2="bcac"`, the output should be `2`.
```
"abcabc" --> "bcac"
x x
```
For `s1="abc", s2="xyz"`, the output should be `-1`.
It's impossible to get the word `s2`.
I tried it in Python, but could not do it. Can you solve it? | import re
def buy_newspaper(s1, s2):
if not set(s2) <= set(s1):
return -1
regex = ''.join(c + '?' for c in s1)
return len([match for match in re.findall(regex, s2) if match]) | python | train | abovesol | codeparrot/apps | all |
Solve in Python:
Bob has ladder. He wants to climb this ladder, but being a precocious child, he wonders about exactly how many ways he could to climb this `n` size ladder using jumps of up to distance `k`.
Consider this example...
n = 5\
k = 3
Here, Bob has ladder of length 5, and with each jump, he can ascend up to 3 steps (he can either jump step 1 or 2 or 3). This gives the below possibilities
```
1 1 1 1 1
1 1 1 2
1 1 2 1
1 2 1 1
2 1 1 1
1 2 2
2 2 1
2 1 2
1 1 3
1 3 1
3 1 1
2 3
3 2
```
Your task to calculate number of ways to climb ladder of length `n` with upto `k` steps for Bob. (13 in above case)
Constraints:
```python
1<=n<=50
1<=k<=15
```
_Tip: try fibonacci._ | def count_ways(n, k):
steps = [1] * (n + 1)
for i in range(1, n + 1):
if i <= k:
steps[i] = sum(steps[j] for j in range(0, i))
else:
steps[i] = sum(steps[i - j] for j in range(1, k + 1))
return steps[-1] | python | train | qsol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/485/A:
One industrial factory is reforming working plan. The director suggested to set a mythical detail production norm. If at the beginning of the day there were x details in the factory storage, then by the end of the day the factory has to produce $x \operatorname{mod} m$ (remainder after dividing x by m) more details. Unfortunately, no customer has ever bought any mythical detail, so all the details produced stay on the factory.
The board of directors are worried that the production by the given plan may eventually stop (that means that there will be а moment when the current number of details on the factory is divisible by m).
Given the number of details a on the first day and number m check if the production stops at some moment.
-----Input-----
The first line contains two integers a and m (1 ≤ a, m ≤ 10^5).
-----Output-----
Print "Yes" (without quotes) if the production will eventually stop, otherwise print "No".
-----Examples-----
Input
1 5
Output
No
Input
3 6
Output
Yes
I tried it in Python, but could not do it. Can you solve it? | a,m = map(int,input().split())
for i in range(100000):
if a%m==0:
print("Yes")
quit()
else:
a+=a%m
print("No") | python | test | abovesol | codeparrot/apps | all |
Solve in Python:
We have a board with a 2 \times N grid.
Snuke covered the board with N dominoes without overlaps.
Here, a domino can cover a 1 \times 2 or 2 \times 1 square.
Then, Snuke decided to paint these dominoes using three colors: red, cyan and green.
Two dominoes that are adjacent by side should be painted by different colors.
Here, it is not always necessary to use all three colors.
Find the number of such ways to paint the dominoes, modulo 1000000007.
The arrangement of the dominoes is given to you as two strings S_1 and S_2 in the following manner:
- Each domino is represented by a different English letter (lowercase or uppercase).
- The j-th character in S_i represents the domino that occupies the square at the i-th row from the top and j-th column from the left.
-----Constraints-----
- 1 \leq N \leq 52
- |S_1| = |S_2| = N
- S_1 and S_2 consist of lowercase and uppercase English letters.
- S_1 and S_2 represent a valid arrangement of dominoes.
-----Input-----
Input is given from Standard Input in the following format:
N
S_1
S_2
-----Output-----
Print the number of such ways to paint the dominoes, modulo 1000000007.
-----Sample Input-----
3
aab
ccb
-----Sample Output-----
6
There are six ways as shown below: | #template
def inputlist(): return [int(j) for j in input().split()]
#template
mod = 10**9+7
N = int(input())
if N == 1:
print((3))
return
S1 = list(input())
S2 = list(input())
blocks = []
s = S1[0]
for i in range(1,N):
if S1[i] == S1[i-1]:
s += S1[i]
else:
blocks.append(s)
s = S1[i]
if i == N-1:
blocks.append(s)
n = len(blocks)
last_blocks = [0]*n
for i in range(1,n):
last_blocks[i] = len(blocks[i-1])
ans = 1
for i in range(n):
tmp = blocks[i]
last_block = last_blocks[i]
if last_block == 0:
if len(tmp) == 1:
ans *= 3
else:
ans*=6
if last_block == 1:
ans *= 2
if last_block == 2:
if len(tmp) == 1:
ans*=1
if len(tmp) == 2:
ans*=3
ans %= mod
print((ans%mod)) | python | test | qsol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/509/B:
There are n piles of pebbles on the table, the i-th pile contains a_{i} pebbles. Your task is to paint each pebble using one of the k given colors so that for each color c and any two piles i and j the difference between the number of pebbles of color c in pile i and number of pebbles of color c in pile j is at most one.
In other words, let's say that b_{i}, c is the number of pebbles of color c in the i-th pile. Then for any 1 ≤ c ≤ k, 1 ≤ i, j ≤ n the following condition must be satisfied |b_{i}, c - b_{j}, c| ≤ 1. It isn't necessary to use all k colors: if color c hasn't been used in pile i, then b_{i}, c is considered to be zero.
-----Input-----
The first line of the input contains positive integers n and k (1 ≤ n, k ≤ 100), separated by a space — the number of piles and the number of colors respectively.
The second line contains n positive integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 100) denoting number of pebbles in each of the piles.
-----Output-----
If there is no way to paint the pebbles satisfying the given condition, output "NO" (without quotes) .
Otherwise in the first line output "YES" (without quotes). Then n lines should follow, the i-th of them should contain a_{i} space-separated integers. j-th (1 ≤ j ≤ a_{i}) of these integers should be equal to the color of the j-th pebble in the i-th pile. If there are several possible answers, you may output any of them.
-----Examples-----
Input
4 4
1 2 3 4
Output
YES
1
1 4
1 2 4
1 2 3 4
Input
5 2
3 2 4 1 3
Output
NO
Input
5 4
3 2 4 3 5
Output
YES
1 2 3
1 3
1 2 3 4
1 3 4
1 1 2 3 4
I tried it in Python, but could not do it. Can you solve it? | n, colors = map(int, input().split())
lens = list(map(int, input().split()))
q = [[] for i in range(n)]
def end():
for i in range(n):
if lens[i] != len(q[i]):
return False
return True
mi = min(lens)
for i in range(n):
while len(q[i]) < min(lens[i], 1 + mi):
q[i].append(1)
k = 1
while not end():
k += 1
for i in range(n):
if len(q[i]) < lens[i]:
q[i].append(k)
ma = max(map(max, q))
if ma <= colors:
print('YES')
for w in q:
for i in w:
print(i, end=' ')
print()
else:
print('NO') | python | test | abovesol | codeparrot/apps | all |
Solve in Python:
For every string, after every occurrence of `'and'` and `'but'`, insert the substring `'apparently'` directly after the occurrence.
If input does not contain 'and' or 'but', return the original string. If a blank string, return `''`.
If substring `'apparently'` is already directly after an `'and'` and/or `'but'`, do not add another. (Do not add duplicates).
# Examples:
Input 1
'It was great and I've never been on live television before but sometimes I don't watch this.'
Output 1
'It was great and apparently I've never been on live television before but apparently sometimes I don't watch this.'
Input 2
'but apparently'
Output 2
'but apparently'
(no changes because `'apparently'` is already directly after `'but'` and there should not be a duplicate.)
An occurrence of `'and'` and/or `'but'` only counts when it is at least one space separated. For example `'andd'` and `'bbut'` do not count as occurrences, whereas `'b but'` and `'and d'` does count.
reference that may help:
https://www.youtube.com/watch?v=rz5TGN7eUcM | def apparently(string):
a, r = string.split(), []
for i in range(len(a)):
if a[i] in ('and', 'but') and i == len(a)-1: r.append(a[i]+' apparently')
elif a[i] in ('and', 'but') and a[i+1] != 'apparently': r.append(a[i]+' apparently')
else: r.append(a[i])
return ' '.join(r) | python | train | qsol | codeparrot/apps | all |
I found an interesting problem on https://www.codewars.com/kata/5ae43ed6252e666a6b0000a4:
Welcome
This kata is inspired by This Kata
We have a string s
We have a number n
Here is a function that takes your string, concatenates the even-indexed chars to the front, odd-indexed chars to the back.
Examples
s = "Wow Example!"
result = "WwEapeo xml!"
s = "I'm JomoPipi"
result = "ImJm ii' ooPp"
The Task:
return the result of the string after applying the function to it n times.
example where s = "qwertyuio" and n = 2:
after 1 iteration s = "qetuowryi"
after 2 iterations s = "qtorieuwy"
return "qtorieuwy"
Note
there's a lot of tests, big strings,
and n is greater than a billion
so be ready to optimize.
after doing this: do it's best friend!
# Check out my other kata!
Matrix Diagonal Sort OMG
String -> N iterations -> String
String -> X iterations -> String
ANTISTRING
Array - squareUp b!
Matrix - squareUp b!
Infinitely Nested Radical Expressions
pipi Numbers!
I tried it in Python, but could not do it. Can you solve it? | def jumbled_string(s, n):
idx = list(range(0,len(s),2)) + list(range(1,len(s),2))
lst = []
while not lst or s != lst[0]:
lst.append(s)
s = ''.join(s[i] for i in idx)
if len(lst) == n: return s
return lst[ n%len(lst) ] | python | train | abovesol | codeparrot/apps | all |
Solve in Python:
=====Function Descriptions=====
Basic mathematical functions operate element-wise on arrays. They are available both as operator overloads and as functions in the NumPy module.
import numpy
a = numpy.array([1,2,3,4], float)
b = numpy.array([5,6,7,8], float)
print a + b #[ 6. 8. 10. 12.]
print numpy.add(a, b) #[ 6. 8. 10. 12.]
print a - b #[-4. -4. -4. -4.]
print numpy.subtract(a, b) #[-4. -4. -4. -4.]
print a * b #[ 5. 12. 21. 32.]
print numpy.multiply(a, b) #[ 5. 12. 21. 32.]
print a / b #[ 0.2 0.33333333 0.42857143 0.5 ]
print numpy.divide(a, b) #[ 0.2 0.33333333 0.42857143 0.5 ]
print a % b #[ 1. 2. 3. 4.]
print numpy.mod(a, b) #[ 1. 2. 3. 4.]
print a**b #[ 1.00000000e+00 6.40000000e+01 2.18700000e+03 6.55360000e+04]
print numpy.power(a, b) #[ 1.00000000e+00 6.40000000e+01 2.18700000e+03 6.55360000e+04]
=====Problem Statement=====
You are given two integer arrays, A and B of dimensions NXM.
Your task is to perform the following operations:
1. Add (A + B)
2. Subtract (A - B)
3. Multiply (A * B)
4. Integer Division (A / B)
5. Mod (A % B)
6. Power (A ** B)
=====Input Format=====
The first line contains two space separated integers, N and M.
The next N lines contains M space separated integers of array A.
The following N lines contains M space separated integers of array B.
=====Output Format=====
Print the result of each operation in the given order under Task. | import numpy
n,m = list(map(int,input().split()))
ar1 = []
ar2 = []
for i in range(n):
tmp = list(map(int,input().split()))
ar1.append(tmp)
for i in range(n):
tmp = list(map(int,input().split()))
ar2.append(tmp)
np_ar1 = numpy.array(ar1)
np_ar2 = numpy.array(ar2)
print((np_ar1 + np_ar2))
print((np_ar1 - np_ar2))
print((np_ar1 * np_ar2))
print((np_ar1 // np_ar2))
print((np_ar1 % np_ar2))
print((np_ar1 ** np_ar2)) | python | train | qsol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/691/C:
You are given a positive decimal number x.
Your task is to convert it to the "simple exponential notation".
Let x = a·10^{b}, where 1 ≤ a < 10, then in general case the "simple exponential notation" looks like "aEb". If b equals to zero, the part "Eb" should be skipped. If a is an integer, it should be written without decimal point. Also there should not be extra zeroes in a and b.
-----Input-----
The only line contains the positive decimal number x. The length of the line will not exceed 10^6. Note that you are given too large number, so you can't use standard built-in data types "float", "double" and other.
-----Output-----
Print the only line — the "simple exponential notation" of the given number x.
-----Examples-----
Input
16
Output
1.6E1
Input
01.23400
Output
1.234
Input
.100
Output
1E-1
Input
100.
Output
1E2
I tried it in Python, but could not do it. Can you solve it? | string_list = input().split(sep='.')
integer = string_list[0].lstrip('0')
if len(string_list) == 1:
fractional = ''
else:
fractional = string_list[1].rstrip('0')
if integer:
if fractional:
a = "{}.{}{}".format(integer[0], integer[1:], fractional)
else:
a = "{}.{}".format(integer[0], integer[1:].rstrip('0'))
b = len(integer) - 1
if a[-1] == '.':
a = a[:-1]
if b > 0:
print("E".join((a, str(b))))
else:
print(a)
else:
old_len = len(fractional)
fractional = fractional.lstrip('0')
zero_count = old_len - len(fractional)
a = "{}.{}".format(fractional[0], fractional[1:])
b = -zero_count - 1
if a[-1] == '.':
a = a[:-1]
print("E".join((a, str(b)))) | python | test | abovesol | codeparrot/apps | all |
I found an interesting problem on https://www.codechef.com/LTIME40/problems/LTM40CD:
Chef likes problems on geometry a lot. Please help him to solve one such problem.
Find all possible triangles with integer sides which has the radius of inscribed circle (also known as incircle) equal to R.
Two triangles are said to be different if they have at least one different side lengths. Formally, let there be two triangles T1, T2. Let a, b, c denote the sides of triangle T1, such that a ≤ b ≤ c. Similarly, Let d, e, f denote the sides of triangle T2, such that d ≤ e ≤ f. Then T1 will said to be different from T2 if either a ≠ d, or b ≠ e or c ≠ f.
-----Input-----
There is a single test case per test file.
The only line of input contains an integer R.
-----Output-----
Output in first line single number - number of triangles satisfying statement.
Order the sides of triangles in non-decreasing order. Output all triangles in non-decreasing order, i.e. order first by smallest sides, otherwise by second smallest sides, if first and second sides equal, then by third.
-----Constraints-----
- 1 ≤ R ≤ 100
-----Subtasks-----
- Subtask #1: (20 points) 1 ≤ R ≤ 3
- Subtask #2: (30 points) 1 ≤ R ≤ 20
- Subtask #3: (50 points) Original constraints
-----Example-----
Input:2
Output:5
5 12 13
6 8 10
6 25 29
7 15 20
9 10 17
I tried it in Python, but could not do it. Can you solve it? | from math import sqrt
r = int(input())
cnt=0
rt=[]
for i in range(1,16*r):
for j in range(i, 460):
for k in range(j+1, j+i):
#print i,j,k
s = float((i+j+k))/2
#print s,i,j,k,s*(s-i)*(s-j)*(s-k)
area = sqrt(abs(s*(s-i)*(s-j)*(s-k)))
#print(float(2*area))/(i+j+k)
if (r==(float(2*area))/(i+j+k)):
cnt+=1
#print i,j,k,area
rt.append([i,j,k])
print(cnt)
for i in rt:
for j in i:
print(j, end=' ')
print() | python | train | abovesol | codeparrot/apps | all |
Solve in Python:
There are $n$ chips arranged in a circle, numbered from $1$ to $n$.
Initially each chip has black or white color. Then $k$ iterations occur. During each iteration the chips change their colors according to the following rules. For each chip $i$, three chips are considered: chip $i$ itself and two its neighbours. If the number of white chips among these three is greater than the number of black chips among these three chips, then the chip $i$ becomes white. Otherwise, the chip $i$ becomes black.
Note that for each $i$ from $2$ to $(n - 1)$ two neighbouring chips have numbers $(i - 1)$ and $(i + 1)$. The neighbours for the chip $i = 1$ are $n$ and $2$. The neighbours of $i = n$ are $(n - 1)$ and $1$.
The following picture describes one iteration with $n = 6$. The chips $1$, $3$ and $4$ are initially black, and the chips $2$, $5$ and $6$ are white. After the iteration $2$, $3$ and $4$ become black, and $1$, $5$ and $6$ become white.
[Image]
Your task is to determine the color of each chip after $k$ iterations.
-----Input-----
The first line contains two integers $n$ and $k$ $(3 \le n \le 200\,000, 1 \le k \le 10^{9})$ — the number of chips and the number of iterations, respectively.
The second line contains a string consisting of $n$ characters "W" and "B". If the $i$-th character is "W", then the $i$-th chip is white initially. If the $i$-th character is "B", then the $i$-th chip is black initially.
-----Output-----
Print a string consisting of $n$ characters "W" and "B". If after $k$ iterations the $i$-th chip is white, then the $i$-th character should be "W". Otherwise the $i$-th character should be "B".
-----Examples-----
Input
6 1
BWBBWW
Output
WBBBWW
Input
7 3
WBWBWBW
Output
WWWWWWW
Input
6 4
BWBWBW
Output
BWBWBW
-----Note-----
The first example is described in the statement.
The second example: "WBWBWBW" $\rightarrow$ "WWBWBWW" $\rightarrow$ "WWWBWWW" $\rightarrow$ "WWWWWWW". So all chips become white.
The third example: "BWBWBW" $\rightarrow$ "WBWBWB" $\rightarrow$ "BWBWBW"... | import sys
input = sys.stdin.readline
n,k=list(map(int,input().split()))
S=input().strip()
ANS=["?"]*n
for i in range(n-1):
if S[i]=="B":
if S[i-1]=="B" or S[i+1]=="B":
ANS[i]="B"
else:
if S[i-1]=="W" or S[i+1]=="W":
ANS[i]="W"
if S[n-1]=="B":
if S[n-2]=="B" or S[0]=="B":
ANS[n-1]="B"
else:
if S[n-2]=="W" or S[0]=="W":
ANS[n-1]="W"
COMP=[]
count=1
now=ANS[0]
for i in range(1,n):
if ANS[i]==ANS[i-1]:
count+=1
else:
COMP.append([now,count])
count=1
now=ANS[i]
COMP.append([now,count])
hosei=0
if len(COMP)==1:
if COMP[0][0]!="?":
print(S)
else:
if k%2==0:
print(S)
else:
ANS=[]
for s in S:
if s=="B":
ANS.append("W")
else:
ANS.append("B")
print("".join(ANS))
return
if COMP[0][0]=="?" and COMP[-1][0]=="?":
hosei=COMP[-1][1]
COMP.pop()
COMP[0][1]+=hosei
ANS2=[]
LEN=len(COMP)
if COMP[0][0]!="?":
COMP.append(COMP[0])
for i in range(LEN):
if COMP[i][0]!="?":
ANS2.append(COMP[i])
else:
x=COMP[i][1]
if x<=k*2:
if COMP[i-1][0]==COMP[i+1][0]:
ANS2.append([COMP[i-1][0],x])
else:
ANS2.append([COMP[i-1][0],x//2])
ANS2.append([COMP[i+1][0],x//2])
else:
ANS2.append([COMP[i-1][0],k])
ANS2.append(["?",x-2*k])
ANS2.append([COMP[i+1][0],k])
#print(ANS2)
GOAL=[]
for x,y in ANS2:
if x!="?":
GOAL+=[x]*y
else:
if GOAL!=[]:
if GOAL[-1]=="B":
t=0
else:
t=1
else:
if ANS2[-1][0]=="B":
t=0
else:
t=1
for j in range(y):
if j%2==0:
if t==0:
GOAL.append("W")
else:
... | python | test | qsol | codeparrot/apps | all |
Solve in Python:
Write a function that when given a number >= 0, returns an Array of ascending length subarrays.
```
pyramid(0) => [ ]
pyramid(1) => [ [1] ]
pyramid(2) => [ [1], [1, 1] ]
pyramid(3) => [ [1], [1, 1], [1, 1, 1] ]
```
**Note:** the subarrays should be filled with `1`s | def pyramid(n):
result = []
for i in range (1, n + 1):
result.append(i * [1])
return result | python | train | qsol | codeparrot/apps | all |
Solve in Python:
Inna and Dima decided to surprise Sereja. They brought a really huge candy matrix, it's big even for Sereja! Let's number the rows of the giant matrix from 1 to n from top to bottom and the columns — from 1 to m, from left to right. We'll represent the cell on the intersection of the i-th row and j-th column as (i, j). Just as is expected, some cells of the giant candy matrix contain candies. Overall the matrix has p candies: the k-th candy is at cell (x_{k}, y_{k}).
The time moved closer to dinner and Inna was already going to eat p of her favourite sweets from the matrix, when suddenly Sereja (for the reason he didn't share with anyone) rotated the matrix x times clockwise by 90 degrees. Then he performed the horizontal rotate of the matrix y times. And then he rotated the matrix z times counterclockwise by 90 degrees. The figure below shows how the rotates of the matrix looks like. [Image]
Inna got really upset, but Duma suddenly understood two things: the candies didn't get damaged and he remembered which cells contained Inna's favourite sweets before Sereja's strange actions. Help guys to find the new coordinates in the candy matrix after the transformation Sereja made!
-----Input-----
The first line of the input contains fix integers n, m, x, y, z, p (1 ≤ n, m ≤ 10^9; 0 ≤ x, y, z ≤ 10^9; 1 ≤ p ≤ 10^5).
Each of the following p lines contains two integers x_{k}, y_{k} (1 ≤ x_{k} ≤ n; 1 ≤ y_{k} ≤ m) — the initial coordinates of the k-th candy. Two candies can lie on the same cell.
-----Output-----
For each of the p candies, print on a single line its space-separated new coordinates.
-----Examples-----
Input
3 3 3 1 1 9
1 1
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3
Output
1 3
1 2
1 1
2 3
2 2
2 1
3 3
3 2
3 1
-----Note-----
Just for clarity. Horizontal rotating is like a mirroring of the matrix. For matrix:
QWER REWQ
ASDF -> FDSA
ZXCV VCXZ | n, m, x, y, z, p = list(map(int, input().split()))
n, m, x, y, z = n + 1, m + 1, x % 4, y % 2, (4 - z) % 4
def a(i, j, n, m, k):
if k == 0: return i, j, n, m
if k == 1: return j, n - i, m, n
if k == 2: return n - i, m - j, n, m
return m - j, i, m, n
def b(i, j, m, k):
if k == 0: return i, j
if k == 1: return i, m - j
for i in range(p):
u, v = list(map(int, input().split()))
u, v, q, p = a(u, v, n, m, x)
u, v = b(u, v, p, y)
u, v, q, p = a(u, v, q, p, z)
print(u, v) | python | test | qsol | codeparrot/apps | all |
Solve in Python:
Leonardo Fibonacci in a rare portrait of his younger days
I assume you are all familiar with the famous Fibonacci sequence, having to get each number as the sum of the previous two (and typically starting with either `[0,1]` or `[1,1]` as the first numbers).
While there are plenty of variation on it ([including](https://www.codewars.com/kata/tribonacci-sequence) [a few](https://www.codewars.com/kata/fibonacci-tribonacci-and-friends) [I wrote](https://www.codewars.com/kata/triple-shiftian-numbers/)), usually the catch is all the same: get a starting (signature) list of numbers, then proceed creating more with the given rules.
What if you were to get to get two parameters, one with the signature (starting value) and the other with the number you need to sum at each iteration to obtain the next one?
And there you have it, getting 3 parameters:
* a signature of length `length`
* a second parameter is a list/array of indexes of the last `length` elements you need to use to obtain the next item in the sequence (consider you can end up not using a few or summing the same number multiple times)' in other words, if you get a signature of length `5` and `[1,4,2]` as indexes, at each iteration you generate the next number by summing the 2nd, 5th and 3rd element (the ones with indexes `[1,4,2]`) of the last 5 numbers
* a third and final parameter is of course which sequence element you need to return (starting from zero, I don't want to bother you with adding/removing 1s or just coping with the fact that after years on CodeWars we all count as computers do):
```python
custom_fib([1,1],[0,1],2) == 2 #classical fibonacci!
custom_fib([1,1],[0,1],3) == 3 #classical fibonacci!
custom_fib([1,1],[0,1],4) == 5 #classical fibonacci!
custom_fib([3,5,2],[0,1,2],4) == 17 #similar to my Tribonacci
custom_fib([7,3,4,1],[1,1],6) == 2 #can you figure out how it worked ;)?
``` | from collections import deque
def custom_fib(signature,indexes,n):
s = deque(signature, maxlen=len(signature))
for i in range(n):
s.append(sum(s[i] for i in indexes))
return s[0] | python | train | qsol | codeparrot/apps | all |