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 |
---|---|---|---|---|---|---|
I found an interesting problem on https://codeforces.com/problemset/problem/392/A:
Imagine you have an infinite 2D plane with Cartesian coordinate system. Some of the integral points are blocked, and others are not. Two integral points A and B on the plane are 4-connected if and only if: the Euclidean distance between A and B is one unit and neither A nor B is blocked; or there is some integral point C, such that A is 4-connected with C, and C is 4-connected with B.
Let's assume that the plane doesn't contain blocked points. Consider all the integral points of the plane whose Euclidean distance from the origin is no more than n, we'll name these points special. Chubby Yang wants to get the following property: no special point is 4-connected to some non-special point. To get the property she can pick some integral points of the plane and make them blocked. What is the minimum number of points she needs to pick?
-----Input-----
The first line contains an integer n (0 ≤ n ≤ 4·10^7).
-----Output-----
Print a single integer — the minimum number of points that should be blocked.
-----Examples-----
Input
1
Output
4
Input
2
Output
8
Input
3
Output
16
I tried it in Python, but could not do it. Can you solve it? | print(max(1, 4 * int(int(input()) * 2 ** 0.5))) | python | test | abovesol | codeparrot/apps | all |
Solve in Python:
Leha like all kinds of strange things. Recently he liked the function F(n, k). Consider all possible k-element subsets of the set [1, 2, ..., n]. For subset find minimal element in it. F(n, k) — mathematical expectation of the minimal element among all k-element subsets.
But only function does not interest him. He wants to do interesting things with it. Mom brought him two arrays A and B, each consists of m integers. For all i, j such that 1 ≤ i, j ≤ m the condition A_{i} ≥ B_{j} holds. Help Leha rearrange the numbers in the array A so that the sum $\sum_{i = 1}^{m} F(A_{i}^{\prime}, B_{i})$ is maximally possible, where A' is already rearranged array.
-----Input-----
First line of input data contains single integer m (1 ≤ m ≤ 2·10^5) — length of arrays A and B.
Next line contains m integers a_1, a_2, ..., a_{m} (1 ≤ a_{i} ≤ 10^9) — array A.
Next line contains m integers b_1, b_2, ..., b_{m} (1 ≤ b_{i} ≤ 10^9) — array B.
-----Output-----
Output m integers a'_1, a'_2, ..., a'_{m} — array A' which is permutation of the array A.
-----Examples-----
Input
5
7 3 5 3 4
2 1 3 2 3
Output
4 7 3 5 3
Input
7
4 6 5 8 8 2 6
2 1 2 2 1 1 2
Output
2 6 4 5 8 8 6 | n = int(input())
A = list(map(int, input().split()))
B = list(map(int, input().split()))
A.sort(reverse=True)
B1 = sorted(enumerate(B), key=lambda x: x[1])
B2 = sorted(enumerate(B1), key=lambda x: x[1])
ans = [A[b[0]] for b in B2]
print(' '.join(map(str, ans))) | python | train | qsol | codeparrot/apps | all |
Solve in Python:
One day, $n$ people ($n$ is an even number) met on a plaza and made two round dances, each round dance consists of exactly $\frac{n}{2}$ people. Your task is to find the number of ways $n$ people can make two round dances if each round dance consists of exactly $\frac{n}{2}$ people. Each person should belong to exactly one of these two round dances.
Round dance is a dance circle consisting of $1$ or more people. Two round dances are indistinguishable (equal) if one can be transformed to another by choosing the first participant. For example, round dances $[1, 3, 4, 2]$, $[4, 2, 1, 3]$ and $[2, 1, 3, 4]$ are indistinguishable.
For example, if $n=2$ then the number of ways is $1$: one round dance consists of the first person and the second one of the second person.
For example, if $n=4$ then the number of ways is $3$. Possible options: one round dance — $[1,2]$, another — $[3,4]$; one round dance — $[2,4]$, another — $[3,1]$; one round dance — $[4,1]$, another — $[3,2]$.
Your task is to find the number of ways $n$ people can make two round dances if each round dance consists of exactly $\frac{n}{2}$ people.
-----Input-----
The input contains one integer $n$ ($2 \le n \le 20$), $n$ is an even number.
-----Output-----
Print one integer — the number of ways to make two round dances. It is guaranteed that the answer fits in the $64$-bit integer data type.
-----Examples-----
Input
2
Output
1
Input
4
Output
3
Input
8
Output
1260
Input
20
Output
12164510040883200 | import sys,math,itertools
from collections import Counter,deque,defaultdict
from bisect import bisect_left,bisect_right
mod = 10**9+7
INF = float('inf')
def inp(): return int(sys.stdin.readline())
def inpl(): return list(map(int, sys.stdin.readline().split()))
n = inp()
n //= 2;n-=1
print(math.factorial(2*n+1)//(n+1)) | python | test | qsol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/534/A:
An exam for n students will take place in a long and narrow room, so the students will sit in a line in some order. The teacher suspects that students with adjacent numbers (i and i + 1) always studied side by side and became friends and if they take an exam sitting next to each other, they will help each other for sure.
Your task is to choose the maximum number of students and make such an arrangement of students in the room that no two students with adjacent numbers sit side by side.
-----Input-----
A single line contains integer n (1 ≤ n ≤ 5000) — the number of students at an exam.
-----Output-----
In the first line print integer k — the maximum number of students who can be seated so that no two students with adjacent numbers sit next to each other.
In the second line print k distinct integers a_1, a_2, ..., a_{k} (1 ≤ a_{i} ≤ n), where a_{i} is the number of the student on the i-th position. The students on adjacent positions mustn't have adjacent numbers. Formally, the following should be true: |a_{i} - a_{i} + 1| ≠ 1 for all i from 1 to k - 1.
If there are several possible answers, output any of them.
-----Examples-----
Input
6
Output
6
1 5 3 6 2 4
Input
3
Output
2
1 3
I tried it in Python, but could not do it. Can you solve it? | l = [None, '1\n1', '1\n1', '2\n1 3', '4\n2 4 1 3']
n = int(input())
if n in range(len(l)):
print(l[n])
else:
print(n)
print(' '.join(map(str, range(1, n + 1, 2))), end=' ')
print(' '.join(map(str, range(2, n + 1, 2)))) | python | test | abovesol | codeparrot/apps | all |
Solve in Python:
Write a method named `getExponent(n,p)` that returns the largest integer exponent `x` such that p^(x) evenly divides `n`. if `p<=1` the method should return `null`/`None` (throw an `ArgumentOutOfRange` exception in C#). | def get_exponent(n, p):
return next(iter(i for i in range(int(abs(n) ** (1/p)), 0, -1) if (n / p**i) % 1 == 0), 0) if p > 1 else None | python | train | qsol | codeparrot/apps | all |
I found an interesting problem on https://www.codewars.com/kata/576a527ea25aae70b7000c77:
In the previous Kata we discussed the OR case.
We will now discuss the AND case, where rather than calculating the probablility for either of two (or more) possible results, we will calculate the probability of receiving all of the viewed outcomes.
For example, if we want to know the probability of receiving head OR tails in two tosses of a coin, as in the last Kata we add the two probabilities together. However if we want to know the probability of receiving head AND tails, in that order, we have to work differently.
The probability of an AND event is calculated by the following rule:
`P(A ∩ B) = P(A | B) * P(B)`
or
`P(B ∩ A) = P(B | A) * P(A)`
That is, the probability of A and B both occuring is equal to the probability of A given B occuring times the probability of B occuring or vice versa.
If the events are mutually exclusive like in the case of tossing a coin, the probability of A occuring if B has occured is equal to the probability of A occuring by itself. In this case, the probability can be written as the below:
`P(A ∩ B) = P(A) * P(B)`
or
`P(B ∩ A) = P(B) * P(A)`
Applying to the heads and tails case:
`P(H ∩ T) = P(0.5) * P(0.5)`
or
`P(H ∩ T) = P(0.5) * P(0.5)`
The task:
You are given a random bag of 10 balls containing 4 colours. `Red`, `Green`, `Yellow` and `Blue`. You will also be given a sequence of 2 balls of any colour e.g. `Green` and `Red` or `Yellow` and `Yellow`.
You have to return the probability of pulling a ball at random out of the bag and it matching the first colour and then pulling a ball at random out of the bag and it matching the second colour.
You will be given a boolean value of `true` or `false` which indicates whether the balls that is taken out in the first draw is replaced in to the bag for the second draw. Hint: this will determine whether the events are mutually exclusive or not.
You will receive two arrays and a boolean value. The first array contains the colours of the balls in the bag and the second contains the colour of the two balls you have to...
I tried it in Python, but could not do it. Can you solve it? | from collections import Counter
def ball_probability(balls):
c = Counter(balls[0])
b1, b2 = balls[1]
if balls[2]:
return round(c[b1]/len(balls[0]) * c[b2]/len(balls[0]), 3)
else:
return round(c[b1]/len(balls[0]) * (c[b2]-1 if b1==b2 else c[b2])/(len(balls[0]) - 1), 3) | python | train | abovesol | codeparrot/apps | all |
Solve in Python:
Chef likes inequalities. Please help him to solve next one.
Given four integers a, b, c, d. Find number of solutions x < y, where a ≤ x ≤ b and c ≤ y ≤ d and x, y integers.
-----Input-----
The first line contains an integer T denoting number of tests.
First line of each test case contains four positive integer numbers a, b, c and d.
-----Output-----
For each test case, output a single number each in separate line denoting number of integer solutions as asked in the problem.
-----Constraints-----
- 1 ≤ T ≤ 20
- 1 ≤ a, b, c, d ≤ 106
-----Subtasks-----
- Subtask #1: (30 points) 1 ≤ a, b, c, d ≤ 103.
- Subtask #2: (70 points) Original constraints.
-----Example-----
Input:1
2 3 3 4
Output:3
Input:1
2 999999 1 1000000
Output:499998500001 | # Akhilesh Ravi
# Codechef - Chef and Inequality
T = int(input())
l = []
for i in range(T):
l += [[int(j) for j in input().split()]]
l1 = []
for i in l:
a,b,c,d = tuple(i)
if a >= d:
l1 += [0]
elif b < c:
l1 += [(b-a+1)*(d-c+1)]
elif c <= a <= d <= b:
n = d-a
l1 += [n*(n+1)/2]
elif c <= a <= b <= d:
l1 += [(d-a) * (d-a+1)/2
- (d-b-1) * (d-b)/2]
elif a < c <= d <= b:
l1 += [ (d-c+1) * (c-a)
+ (d-c) * (d-c+1)/2 ]
elif a < c <= b <= d:
l1 += [ (d-c+1) * (c-a)
+ (d-c) * (d-c+1)/2
- (d-b-1) * (d-b)/2]
else:
l1 += [0]
for i in l1:
print(i) | python | test | qsol | codeparrot/apps | all |
I found an interesting problem on https://www.codewars.com/kata/56d49587df52101de70011e4:
You have to write a function that describe Leo:
```python
def leo(oscar):
pass
```
if oscar was (integer) 88, you have to return "Leo finally won the oscar! Leo is happy".
if oscar was 86, you have to return "Not even for Wolf of wallstreet?!"
if it was not 88 or 86 (and below 88) you should return "When will you give Leo an Oscar?"
if it was over 88 you should return "Leo got one already!"
I tried it in Python, but could not do it. Can you solve it? | def leo(oscar):
"""Return string describing Leo based on 'oscar'.
(int) -> str
Conditions:
- If 'oscar' was 88, you should return "Leo finally won the oscar! Leo is happy",
- If 'oscar' was 86, you should return "Not even for Wolf of wallstreet?!",
- If 'oscar' was not 88 or 86 (and below 88) you should return "When will you give Leo an Oscar?",
- If 'oscar' was over 88 you should return "Leo got one already!"
>>> leo(88)
"Leo finally won the oscar! Leo is happy"
Example test cases:
- test.assert_equals(leo(85),"When will you give Leo an Oscar?")
- test.assert_equals(leo(86),"Not even for Wolf of wallstreet?!")
- test.assert_equals(leo(87),"When will you give Leo an Oscar?")
- test.assert_equals(leo(88),"Leo finally won the oscar! Leo is happy")
- test.assert_equals(leo(89),"Leo got one already!")
"""
if oscar > 88:
return "Leo got one already!"
elif oscar == 88:
return "Leo finally won the oscar! Leo is happy"
elif oscar == 86:
return "Not even for Wolf of wallstreet?!"
else:
return "When will you give Leo an Oscar?" | python | train | abovesol | codeparrot/apps | all |
Solve in Python:
Given two integers dividend and divisor, divide two integers without using multiplication, division and mod operator.
Return the quotient after dividing dividend by divisor.
The integer division should truncate toward zero.
Example 1:
Input: dividend = 10, divisor = 3
Output: 3
Example 2:
Input: dividend = 7, divisor = -3
Output: -2
Note:
Both dividend and divisor will be 32-bit signed integers.
The divisor will never be 0.
Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For the purpose of this problem, assume that your function returns 231 − 1 when the division result overflows. | class Solution:
def divide(self, dividend, divisor):
"""
:type dividend: int
:type divisor: int
:rtype: int
"""
positive = (dividend < 0) is (divisor < 0)
dividend, divisor, div = abs(dividend), abs(divisor), abs(divisor)
res = 0
q = 1
while dividend >= divisor:
dividend -= div
res += q
q += q
div += div
if dividend < div:
div = divisor
q = 1
if not positive:
res = -res
return min(max(-2147483648, res), 2147483647) | python | train | qsol | codeparrot/apps | all |
I found an interesting problem on https://www.codewars.com/kata/5b254b2225c2bb99c500008d:
> If you've finished this kata, you can try the [more difficult version](https://www.codewars.com/kata/5b256145a454c8a6990000b5).
## Taking a walk
A promenade is a way of uniquely representing a fraction by a succession of “left or right” choices.
For example, the promenade `"LRLL"` represents the fraction `4/7`.
Each successive choice (`L` or `R`) changes the value of the promenade by combining the values of the
promenade before the most recent left choice with the value before the most recent right choice. If the value before the most recent left choice was *l/m* and the value before the most recent right choice
was r/s then the new value will be *(l+r) / (m+s)*.
If there has never been a left choice we use *l=1* and *m=0*;
if there has never been a right choice we use *r=0* and *s=1*.
So let's take a walk.
* `""` An empty promenade has never had a left choice nor a right choice. Therefore we use *(l=1 and m=0)* and *(r=0 and s=1)*.
So the value of `""` is *(1+0) / (0+1) = 1/1*.
* `"L"`. Before the most recent left choice we have `""`, which equals *1/1*. There still has never been a right choice, so *(r=0 and s=1)*. So the value of `"L"` is *(1+0)/(1+1) = 1/2*
* `"LR"` = 2/3 as we use the values of `""` (before the left choice) and `"L"` (before the right choice)
* `"LRL"` = 3/5 as we use the values of `"LR"` and `"L"`
* `"LRLL"` = 4/7 as we use the values of `"LRL"` and `"L"`
Fractions are allowed to have a larger than b.
## Your task
Implement the `promenade` function, which takes an promenade as input (represented as a string), and returns
the corresponding fraction (represented as a tuple, containing the numerator and the denominator).
```Python
promenade("") == (1,1)
promenade("LR") == (2,3)
promenade("LRLL") == (4,7)
```
```Java
Return the Fraction as an int-Array:
promenade("") == [1,1]
promenade("LR") == [2,3]
promenade("LRLL") == [4,7]
```
*adapted from the 2016 British Informatics Olympiad*
I tried it in Python, but could not do it. Can you solve it? | def promenade(choices):
lm=[1,0]
rs=[0,1]
ans=[1,1]
for i in choices:
if i=='L':
lm=ans[::]
if i=='R':
rs=ans[::]
ans=[lm[0]+rs[0],lm[1]+rs[1]]
return tuple(ans)
def fraction_to_promenade(fraction):
ans=""
frac=list(fraction)
while(frac[0]!=frac[1]):
if frac[0]>frac[1]:
ans+="R"
frac[0]=frac[0]-frac[1]
if frac[1]>frac[0]:
ans+="L"
frac[1]=frac[1]-frac[0]
return ans | python | train | abovesol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/378/A:
Two players are playing a game. First each of them writes an integer from 1 to 6, and then a dice is thrown. The player whose written number got closer to the number on the dice wins. If both payers have the same difference, it's a draw.
The first player wrote number a, the second player wrote number b. How many ways to throw a dice are there, at which the first player wins, or there is a draw, or the second player wins?
-----Input-----
The single line contains two integers a and b (1 ≤ a, b ≤ 6) — the numbers written on the paper by the first and second player, correspondingly.
-----Output-----
Print three integers: the number of ways to throw the dice at which the first player wins, the game ends with a draw or the second player wins, correspondingly.
-----Examples-----
Input
2 5
Output
3 0 3
Input
2 4
Output
2 1 3
-----Note-----
The dice is a standard cube-shaped six-sided object with each side containing a number from 1 to 6, and where all numbers on all sides are distinct.
You can assume that number a is closer to number x than number b, if |a - x| < |b - x|.
I tried it in Python, but could not do it. Can you solve it? | a, b = list(map(int, input().split()))
x = y = z = 0
for i in range(1, 7):
if(abs(a-i) < abs(b-i)):
x += 1
elif(abs(a-i) == abs(b-i)):
y += 1
else:
z += 1
print("%d %d %d" % (x, y, z)) | python | test | abovesol | codeparrot/apps | all |
Solve in Python:
A film festival is coming up in the city N. The festival will last for exactly n days and each day will have a premiere of exactly one film. Each film has a genre — an integer from 1 to k.
On the i-th day the festival will show a movie of genre a_{i}. We know that a movie of each of k genres occurs in the festival programme at least once. In other words, each integer from 1 to k occurs in the sequence a_1, a_2, ..., a_{n} at least once.
Valentine is a movie critic. He wants to watch some movies of the festival and then describe his impressions on his site.
As any creative person, Valentine is very susceptive. After he watched the movie of a certain genre, Valentine forms the mood he preserves until he watches the next movie. If the genre of the next movie is the same, it does not change Valentine's mood. If the genres are different, Valentine's mood changes according to the new genre and Valentine has a stress.
Valentine can't watch all n movies, so he decided to exclude from his to-watch list movies of one of the genres. In other words, Valentine is going to choose exactly one of the k genres and will skip all the movies of this genre. He is sure to visit other movies.
Valentine wants to choose such genre x (1 ≤ x ≤ k), that the total number of after-movie stresses (after all movies of genre x are excluded) were minimum.
-----Input-----
The first line of the input contains two integers n and k (2 ≤ k ≤ n ≤ 10^5), where n is the number of movies and k is the number of genres.
The second line of the input contains a sequence of n positive integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ k), where a_{i} is the genre of the i-th movie. It is guaranteed that each number from 1 to k occurs at least once in this sequence.
-----Output-----
Print a single number — the number of the genre (from 1 to k) of the excluded films. If there are multiple answers, print the genre with the minimum number.
-----Examples-----
Input
10 3
1 1 2 3 2 3 3 1 1 3
Output
3
Input
7 3
3 1 3 2 3 1 2
Output
1
-----Note-----
In... | n, k = map(int, input().split())
t = list(map(int, input().split()))
t = [t[0]] + [t[i] for i in range(1, len(t)) if t[i] != t[i - 1]]
p = [0] * (k + 1)
for i in range(1, len(t) - 1):
if t[i - 1] == t[i + 1]: p[t[i]] += 2
else: p[t[i]] += 1
p[t[0]] += 1
p[t[-1]] += 1
print(p.index(max(p))) | python | test | qsol | codeparrot/apps | all |
I found an interesting problem on https://www.codewars.com/kata/55e6125ad777b540d9000042:
Error Handling is very important in coding and seems to be overlooked or not implemented properly.
#Task
Your task is to implement a function which takes a string as input and return an object containing the properties
vowels and consonants. The vowels property must contain the total count of vowels {a,e,i,o,u}, and the total count of consonants {a,..,z} - {a,e,i,o,u}. Handle invalid input and don't forget to return valid ones.
#Input
The input is any random string. You must then discern what are vowels and what are consonants and sum for each category their total occurrences in an object. However you could also receive inputs that are not strings. If this happens then you must return an object with a vowels and consonants total of 0 because the input was NOT a string. Refer to the Example section for a more visual representation of which inputs you could receive and the outputs expected. :)
Example:
```python
Input: get_count('test')
Output: {vowels:1,consonants:3}
Input: get_count('tEst')
Output: {vowels:1,consonants:3}
Input get_count(' ')
Output: {vowels:0,consonants:0}
Input get_count()
Output: {vowels:0,consonants:0}
```
C#
A Counter class has been put in the preloaded section taking two parameters Vowels and Consonants this must be the Object you return!
I tried it in Python, but could not do it. Can you solve it? | import re
def get_count(words=''):
vow_count, con_count = 0, 0
if type(words) is str:
(remainder, vow_count) = re.subn('[aeiou]', '', words, flags=re.I)
(_, con_count) = re.subn('\w', '', remainder, flags=re.I)
return {'vowels': vow_count, 'consonants': con_count} | python | train | abovesol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/1259/B:
There are $n$ positive integers $a_1, a_2, \dots, a_n$. For the one move you can choose any even value $c$ and divide by two all elements that equal $c$.
For example, if $a=[6,8,12,6,3,12]$ and you choose $c=6$, and $a$ is transformed into $a=[3,8,12,3,3,12]$ after the move.
You need to find the minimal number of moves for transforming $a$ to an array of only odd integers (each element shouldn't be divisible by $2$).
-----Input-----
The first line of the input contains one integer $t$ ($1 \le t \le 10^4$) — the number of test cases in the input. Then $t$ test cases follow.
The first line of a test case contains $n$ ($1 \le n \le 2\cdot10^5$) — the number of integers in the sequence $a$. The second line contains positive integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 10^9$).
The sum of $n$ for all test cases in the input doesn't exceed $2\cdot10^5$.
-----Output-----
For $t$ test cases print the answers in the order of test cases in the input. The answer for the test case is the minimal number of moves needed to make all numbers in the test case odd (i.e. not divisible by $2$).
-----Example-----
Input
4
6
40 6 40 3 20 1
1
1024
4
2 4 8 16
3
3 1 7
Output
4
10
4
0
-----Note-----
In the first test case of the example, the optimal sequence of moves can be as follows:
before making moves $a=[40, 6, 40, 3, 20, 1]$; choose $c=6$; now $a=[40, 3, 40, 3, 20, 1]$; choose $c=40$; now $a=[20, 3, 20, 3, 20, 1]$; choose $c=20$; now $a=[10, 3, 10, 3, 10, 1]$; choose $c=10$; now $a=[5, 3, 5, 3, 5, 1]$ — all numbers are odd.
Thus, all numbers became odd after $4$ moves. In $3$ or fewer moves, you cannot make them all odd.
I tried it in Python, but could not do it. Can you solve it? | def f(x):
tmp = x
z = 0
while tmp % 2 == 0:
tmp //= 2
z += 1
return [tmp, z]
for i in range(int(input())):
n = int(input())
a = list(map(int, input().split()))
sl = dict()
for x in a:
y, z = f(x)
if sl.get(y) == None:
sl[y] = z
else:
sl[y] = max(sl[y], z)
ans = 0
for x in sl.keys():
ans += sl[x]
print(ans) | python | train | abovesol | codeparrot/apps | all |
I found an interesting problem on https://www.codewars.com/kata/59325dc15dbb44b2440000af:
Create a function `isAlt()` that accepts a string as an argument and validates whether the vowels (a, e, i, o, u) and consonants are in alternate order.
```python
is_alt("amazon")
// true
is_alt("apple")
// false
is_alt("banana")
// true
```
Arguments consist of only lowercase letters.
I tried it in Python, but could not do it. Can you solve it? | def is_alt(s):
vowels = list("aeiou")
v = s[0] in vowels
for i in s:
if (i in vowels) != v:
return False
v = not(v)
return True | python | train | abovesol | codeparrot/apps | all |
Solve in Python:
In genetic the reverse complement of a sequence is formed by **reversing** the sequence and then taking the complement of each symbol.
The four nucleotides in DNA is Adenine (A), Cytosine (C), Guanine (G) and Thymine (Thymine).
- A is the complement of T
- C is the complement of G.
This is a bi-directional relation so:
- T is the complement of A
- G is the complement of C.
For this kata you need to complete the reverse complement function that take a DNA string and return the reverse complement string.
**Note**: You need to take care of lower and upper case. And if a sequence conatains some invalid characters you need to return "Invalid sequence".
This kata is based on the following [one](http://www.codewars.com/kata/complementary-dna/ruby) but with a little step in addition. | def reverse_complement(dna):
table = str.maketrans("ACGT", "TGCA")
return "Invalid sequence" if set(dna) - set("ACGT") else dna.translate(table)[::-1] | python | train | qsol | codeparrot/apps | all |
Solve in Python:
It's New Year's Eve soon, so Ivan decided it's high time he started setting the table. Ivan has bought two cakes and cut them into pieces: the first cake has been cut into a pieces, and the second one — into b pieces.
Ivan knows that there will be n people at the celebration (including himself), so Ivan has set n plates for the cakes. Now he is thinking about how to distribute the cakes between the plates. Ivan wants to do it in such a way that all following conditions are met: Each piece of each cake is put on some plate; Each plate contains at least one piece of cake; No plate contains pieces of both cakes.
To make his guests happy, Ivan wants to distribute the cakes in such a way that the minimum number of pieces on the plate is maximized. Formally, Ivan wants to know the maximum possible number x such that he can distribute the cakes according to the aforementioned conditions, and each plate will contain at least x pieces of cake.
Help Ivan to calculate this number x!
-----Input-----
The first line contains three integers n, a and b (1 ≤ a, b ≤ 100, 2 ≤ n ≤ a + b) — the number of plates, the number of pieces of the first cake, and the number of pieces of the second cake, respectively.
-----Output-----
Print the maximum possible number x such that Ivan can distribute the cake in such a way that each plate will contain at least x pieces of cake.
-----Examples-----
Input
5 2 3
Output
1
Input
4 7 10
Output
3
-----Note-----
In the first example there is only one way to distribute cakes to plates, all of them will have 1 cake on it.
In the second example you can have two plates with 3 and 4 pieces of the first cake and two plates both with 5 pieces of the second cake. Minimal number of pieces is 3. | q,w,e=list(map(int,input().split()))
s=w+e
tt=s//q
while ((w//tt)+(e//tt)<q):
tt-=1
if tt>min(w,e):
tt=min(w,e)
print(tt) | python | test | qsol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/1066/B:
Vova's house is an array consisting of $n$ elements (yeah, this is the first problem, I think, where someone lives in the array). There are heaters in some positions of the array. The $i$-th element of the array is $1$ if there is a heater in the position $i$, otherwise the $i$-th element of the array is $0$.
Each heater has a value $r$ ($r$ is the same for all heaters). This value means that the heater at the position $pos$ can warm up all the elements in range $[pos - r + 1; pos + r - 1]$.
Vova likes to walk through his house while he thinks, and he hates cold positions of his house. Vova wants to switch some of his heaters on in such a way that each element of his house will be warmed up by at least one heater.
Vova's target is to warm up the whole house (all the elements of the array), i.e. if $n = 6$, $r = 2$ and heaters are at positions $2$ and $5$, then Vova can warm up the whole house if he switches all the heaters in the house on (then the first $3$ elements will be warmed up by the first heater and the last $3$ elements will be warmed up by the second heater).
Initially, all the heaters are off.
But from the other hand, Vova didn't like to pay much for the electricity. So he wants to switch the minimum number of heaters on in such a way that each element of his house is warmed up by at least one heater.
Your task is to find this number of heaters or say that it is impossible to warm up the whole house.
-----Input-----
The first line of the input contains two integers $n$ and $r$ ($1 \le n, r \le 1000$) — the number of elements in the array and the value of heaters.
The second line contains $n$ integers $a_1, a_2, \dots, a_n$ ($0 \le a_i \le 1$) — the Vova's house description.
-----Output-----
Print one integer — the minimum number of heaters needed to warm up the whole house or -1 if it is impossible to do it.
-----Examples-----
Input
6 2
0 1 1 0 0 1
Output
3
Input
5 3
1 0 0 0 1
Output
2
Input
5 10
0 0 0 0 0
Output
-1
Input
10 3
0 0 1 1 0 1 0 0 0...
I tried it in Python, but could not do it. Can you solve it? | def main():
n, r = list(map(int, input().split()))
arr = [True if c == '1' else False for c in input().split()]
#print(arr)
last_heated = 0
tot = 0
last_turned = -1
while last_heated < n:
optim = last_heated + r - 1
while True:
if optim < 0:
print('-1')
return
if optim <= last_turned:
print('-1')
return
if optim >= n:
optim -= 1
continue
if arr[optim]:
# found a heater
tot += 1
last_heated = optim + r
last_turned = optim
#print('turn on ' + str(optim))
break
optim -= 1
print(tot)
def __starting_point():
main()
__starting_point() | python | test | abovesol | codeparrot/apps | all |
Solve in Python:
Pari wants to buy an expensive chocolate from Arya. She has n coins, the value of the i-th coin is c_{i}. The price of the chocolate is k, so Pari will take a subset of her coins with sum equal to k and give it to Arya.
Looking at her coins, a question came to her mind: after giving the coins to Arya, what values does Arya can make with them? She is jealous and she doesn't want Arya to make a lot of values. So she wants to know all the values x, such that Arya will be able to make x using some subset of coins with the sum k.
Formally, Pari wants to know the values x such that there exists a subset of coins with the sum k such that some subset of this subset has the sum x, i.e. there is exists some way to pay for the chocolate, such that Arya will be able to make the sum x using these coins.
-----Input-----
The first line contains two integers n and k (1 ≤ n, k ≤ 500) — the number of coins and the price of the chocolate, respectively.
Next line will contain n integers c_1, c_2, ..., c_{n} (1 ≤ c_{i} ≤ 500) — the values of Pari's coins.
It's guaranteed that one can make value k using these coins.
-----Output-----
First line of the output must contain a single integer q— the number of suitable values x. Then print q integers in ascending order — the values that Arya can make for some subset of coins of Pari that pays for the chocolate.
-----Examples-----
Input
6 18
5 6 1 10 12 2
Output
16
0 1 2 3 5 6 7 8 10 11 12 13 15 16 17 18
Input
3 50
25 25 50
Output
3
0 25 50 | n, k = list(map(int, input().split()))
cs = list(map(int, input().split()))
# table[c][s] has bit ss set if can make subset s and sub-subset ss
# using only the first c coins.
# We only ever need to know table[c-1] to compute table[c].
table = [[0 for _ in range(k+1)] for _ in range(2)]
# Can always make subset 0 and sub-subset 0 using 0 coins.
table[0][0] = 1
for i, c in enumerate(cs,1):
for s in range(k+1):
# Include the coin in neither subset nor sub-subset.
table[i%2][s] |= table[(i-1)%2][s]
if c <= s:
# Include the coin in subset but not sub-subset.
table[i%2][s] |= table[(i-1)%2][s-c]
# Include the coin in both the subset and sub-subset.
table[i%2][s] |= (table[(i-1)%2][s-c] << c)
possible = [str(i) for i in range(k+1) if (table[n%2][k] >> i) & 1]
print(len(possible))
print(*possible) | python | test | qsol | codeparrot/apps | all |
Solve in Python:
You are given three integers A, B and C.
Determine whether C is not less than A and not greater than B.
-----Constraints-----
- -100≤A,B,C≤100
- A, B and C are all integers.
-----Input-----
Input is given from Standard Input in the following format:
A B C
-----Output-----
If the condition is satisfied, print Yes; otherwise, print No.
-----Sample Input-----
1 3 2
-----Sample Output-----
Yes
C=2 is not less than A=1 and not greater than B=3, and thus the output should be Yes. | S_list = list(map(int,input().split()))
if S_list[1] - S_list[0] >= 0 and S_list[2]- S_list[0] >=0 and S_list[1] - S_list[2] >=0:
result = "Yes"
else:
result = "No"
print(result) | python | test | qsol | codeparrot/apps | all |
I found an interesting problem on https://leetcode.com/problems/increasing-triplet-subsequence/:
Given an unsorted array return whether an increasing subsequence of length 3 exists or not in the array.
Formally the function should:
Return true if there exists i, j, k
such that arr[i] < arr[j] < arr[k] given 0 ≤ i < j < k ≤ n-1
else return false.
Your algorithm should run in O(n) time complexity and O(1) space complexity.
Examples:
Given [1, 2, 3, 4, 5],
return true.
Given [5, 4, 3, 2, 1],
return false.
Credits:Special thanks to @DjangoUnchained for adding this problem and creating all test cases.
I tried it in Python, but could not do it. Can you solve it? | class Solution:
def increasingTriplet(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
if len(nums) < 3: return False
tails = [-float('inf')] + [float('inf')]*3
for x in nums:
for i in range(2, -1, -1):
if x > tails[i]:
tails[i+1] = x
break
if tails[-1] < float('inf'):
return True
return False | python | train | abovesol | codeparrot/apps | all |
Solve in Python:
Motu and Tomu are very good friends who are always looking for new games to play against each other and ways to win these games. One day, they decided to play a new type of game with the following rules:
- The game is played on a sequence $A_0, A_1, \dots, A_{N-1}$.
- The players alternate turns; Motu plays first, since he's earlier in lexicographical order.
- Each player has a score. The initial scores of both players are $0$.
- On his turn, the current player has to pick the element of $A$ with the lowest index, add its value to his score and delete that element from the sequence $A$.
- At the end of the game (when $A$ is empty), Tomu wins if he has strictly greater score than Motu. Otherwise, Motu wins the game.
In other words, Motu starts by selecting $A_0$, adding it to his score and then deleting it; then, Tomu selects $A_1$, adds its value to his score and deletes it, and so on.
Motu and Tomu already chose a sequence $A$ for this game. However, since Tomu plays second, he is given a different advantage: before the game, he is allowed to perform at most $K$ swaps in $A$; afterwards, the two friends are going to play the game on this modified sequence.
Now, Tomu wants you to determine if it is possible to perform up to $K$ swaps in such a way that he can win this game.
-----Input-----
- The first line of the input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows.
- The first line of each test case contains two space-separated integers $N$ and $K$ denoting the number of elements in the sequence and the maximum number of swaps Tomu can perform.
- The second line contains $N$ space-separated integers $A_0, A_1, \dots, A_{N-1}$.
-----Output-----
For each test case, print a single line containing the string "YES" if Tomu can win the game or "NO" otherwise (without quotes).
-----Constraints-----
- $1 \le T \le 100$
- $1 \le N \le 10,000$
- $0 \le K \le 10,000$
- $1 \le A_i \le 10,000$ for each valid $i$
-----Subtasks-----
Subtask #1 (20 points): $1... | for _ in range(int(input())):
n,k = list(map(int,input().split()))
a = list(map(int,input().split()))
m = []
t = []
for i in range(n):
if(i%2 == 0):
m.append(a[i])
else:
t.append(a[i])
m.sort(reverse=True)
t.sort()
mi=min(len(m),len(t))
x1=0
x2=0
while(k!=0 and x1<len(m) and x2<len(m)):
if(m[x1]>t[x2]):
m[x1],t[x2] = t[x2],m[x1]
x1+=1
x2+=1
else:
break
k-=1
if(sum(t) > sum(m)):
print("YES")
else:
print("NO") | python | train | qsol | codeparrot/apps | all |
Solve in Python:
The only difference between easy and hard versions is constraints.
You are given a sequence $a$ consisting of $n$ positive integers.
Let's define a three blocks palindrome as the sequence, consisting of at most two distinct elements (let these elements are $a$ and $b$, $a$ can be equal $b$) and is as follows: $[\underbrace{a, a, \dots, a}_{x}, \underbrace{b, b, \dots, b}_{y}, \underbrace{a, a, \dots, a}_{x}]$. There $x, y$ are integers greater than or equal to $0$. For example, sequences $[]$, $[2]$, $[1, 1]$, $[1, 2, 1]$, $[1, 2, 2, 1]$ and $[1, 1, 2, 1, 1]$ are three block palindromes but $[1, 2, 3, 2, 1]$, $[1, 2, 1, 2, 1]$ and $[1, 2]$ are not.
Your task is to choose the maximum by length subsequence of $a$ that is a three blocks palindrome.
You have to answer $t$ independent test cases.
Recall that the sequence $t$ is a a subsequence of the sequence $s$ if $t$ can be derived from $s$ by removing zero or more elements without changing the order of the remaining elements. For example, if $s=[1, 2, 1, 3, 1, 2, 1]$, then possible subsequences are: $[1, 1, 1, 1]$, $[3]$ and $[1, 2, 1, 3, 1, 2, 1]$, but not $[3, 2, 3]$ and $[1, 1, 1, 1, 2]$.
-----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 first line of the test case contains one integer $n$ ($1 \le n \le 2000$) — the length of $a$. The second line of the test case contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 26$), where $a_i$ is the $i$-th element of $a$. Note that the maximum value of $a_i$ can be up to $26$.
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 — the maximum possible length of some subsequence of $a$ that is a three blocks palindrome.
-----Example-----
Input
6
8
1 1 2 2 3 2 1 1
3
1 3 3
4
1 10 10 1
1
26
2
2 1
3
1 1 1
Output
7
2
4
1
1
3 | for _ in range(int(input())):
n = int(input())
r = list(map(int, input().split()))
d = {i: [] for i in range(1, 27)}
for i in range(n):
d[r[i]].append(i)
ans = 1
for end in range(1, 27):
c = 1
while c * 2 <= len(d[end]):
ll, rr = d[end][c - 1] + 1, d[end][-c] - 1
dd = [0] * 27
for p in range(ll, rr + 1):
dd[r[p]] += 1
ans = max(ans, max(dd) + 2 * c)
c += 1
print (ans) | python | train | qsol | codeparrot/apps | all |
I found an interesting problem on https://www.codewars.com/kata/58855acc9e1de22dff0000ef:
# Task
Make a custom esolang interpreter for the language Stick. Stick is a simple, stack-based esoteric programming language with only 7 commands.
# Commands
* `^`: Pop the stack.
* `!`: Add new element to stack with the value of 0.
* `+`: Increment element. 255+1=0.
* `-`: Decrement element. 0-1=255.
* `*`: Add ascii value of **top** element to the output stream.
* `[`: Skip past **next** `]` if element value is 0.
* `]`: Jump back to the command after **previous** `[` if element value is nonzero.
# Syntax and other info
* You don't need to add support for nested brackets.
* Non-command characters should be ignored.
* Code will always have all brackets closed.
* Note the highlighted **next** and **previous** in the commands reference.
* Program begins with the top element having the value of 0 and being the only element in the stack.
* Program ends when command executor reaches the end.
# Examples
## Hello,...
I tried it in Python, but could not do it. Can you solve it? | def interpreter(tape):
stack, output = [0], ''
i, n = 0, len(tape)
while i < n:
cmd = tape[i]
if cmd == '^':
stack.pop()
elif cmd == '!':
stack.append(0)
elif cmd == '+':
stack[0] = 0 if stack[0] == 255 else stack[0] + 1
elif cmd == '-':
stack[0] = 255 if stack[0] == 0 else stack[0] - 1
elif cmd == '*':
output += chr(stack.pop(0))
elif cmd == '[' and stack[0] == 0:
while tape[i] != ']':
i += 1
elif cmd == ']' and stack[0] != 0:
while tape[i] != '[':
i -= 1
i += 1
return output.replace('\n', '\x02') | python | train | abovesol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/958/A1:
The stardate is 1977 and the science and art of detecting Death Stars is in its infancy. Princess Heidi has received information about the stars in the nearby solar system from the Rebel spies and now, to help her identify the exact location of the Death Star, she needs to know whether this information is correct.
Two rebel spies have provided her with the maps of the solar system. Each map is an N × N grid, where each cell is either occupied by a star or empty. To see whether the information is correct, Heidi needs to know whether the two maps are of the same solar system, or if possibly one of the spies is actually an Empire double agent, feeding her false information.
Unfortunately, spies may have accidentally rotated a map by 90, 180, or 270 degrees, or flipped it along the vertical or the horizontal axis, before delivering it to Heidi. If Heidi can rotate or flip the maps so that two of them become identical, then those maps are of the same solar system. Otherwise, there are traitors in the Rebel ranks! Help Heidi find out.
-----Input-----
The first line of the input contains one number N (1 ≤ N ≤ 10) – the dimension of each map. Next N lines each contain N characters, depicting the first map: 'X' indicates a star, while 'O' indicates an empty quadrant of space. Next N lines each contain N characters, depicting the second map in the same format.
-----Output-----
The only line of output should contain the word Yes if the maps are identical, or No if it is impossible to match them by performing rotations and translations.
-----Examples-----
Input
4
XOOO
XXOO
OOOO
XXXX
XOOO
XOOO
XOXO
XOXX
Output
Yes
Input
2
XX
OO
XO
OX
Output
No
-----Note-----
In the first test, you can match the first map to the second map by first flipping the first map along the vertical axis, and then by rotating it 90 degrees clockwise.
I tried it in Python, but could not do it. Can you solve it? | N = int(input())
first = []
second = []
for i in range(N):
first.append([s for s in input()])
for i in range(N):
second.append([s for s in input()])
def rotate_90(matrix):
return list(zip(*matrix[::-1]))
def flip(matrix):
return matrix[::-1]
def compare_matrices(first, second):
for i in range(N):
for j in range(N):
if first[i][j] != second[i][j]:
return False
return True
def wrap(first, second):
if compare_matrices(first, second) == True:
return 'Yes'
hold_first = first[::]
for _ in range(3):
first = rotate_90(first)
if compare_matrices(first, second) == True:
return 'Yes'
first = hold_first
first = flip(first)
if compare_matrices(first, second) == True:
return 'Yes'
for _ in range(3):
first = rotate_90(first)
if compare_matrices(first, second) == True:
return 'Yes'
return 'No'
print(wrap(first, second)) | python | test | abovesol | codeparrot/apps | all |
Solve in Python:
Alyona has a tree with n vertices. The root of the tree is the vertex 1. In each vertex Alyona wrote an positive integer, in the vertex i she wrote a_{i}. Moreover, the girl wrote a positive integer to every edge of the tree (possibly, different integers on different edges).
Let's define dist(v, u) as the sum of the integers written on the edges of the simple path from v to u.
The vertex v controls the vertex u (v ≠ u) if and only if u is in the subtree of v and dist(v, u) ≤ a_{u}.
Alyona wants to settle in some vertex. In order to do this, she wants to know for each vertex v what is the number of vertices u such that v controls u.
-----Input-----
The first line contains single integer n (1 ≤ n ≤ 2·10^5).
The second line contains n integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10^9) — the integers written in the vertices.
The next (n - 1) lines contain two integers each. The i-th of these lines contains integers p_{i} and w_{i} (1 ≤ p_{i} ≤ n, 1 ≤ w_{i} ≤ 10^9) — the parent of the (i + 1)-th vertex in the tree and the number written on the edge between p_{i} and (i + 1).
It is guaranteed that the given graph is a tree.
-----Output-----
Print n integers — the i-th of these numbers should be equal to the number of vertices that the i-th vertex controls.
-----Examples-----
Input
5
2 5 1 4 6
1 7
1 1
3 5
3 6
Output
1 0 1 0 0
Input
5
9 7 8 6 5
1 1
2 1
3 1
4 1
Output
4 3 2 1 0
-----Note-----
In the example test case the vertex 1 controls the vertex 3, the vertex 3 controls the vertex 5 (note that is doesn't mean the vertex 1 controls the vertex 5). | import sys
import threading
from bisect import bisect_left
n = int(input())
a = list(map(int, input().split()))
e = {}
g = [[] for i in range(n)]
d = [0]*(n+5)
ans = [0]*n
p = [0]*(n+5)
for i in range(n-1):
c, w = map(int, input().split())
c-= 1
g[c].append(i+1)
e[i+1] = w
def dfs(i, h):
nonlocal ans, a, e, g, d, p
p[h]=0
for j in g[i]:
d[h+1] = d[h]+e[j]
dfs(j, h+1)
x = bisect_left(d, d[h]-a[i], 0, h+1)
#print(x-1, i, h, d[h], d[h], a[i])
if x>=0:
p[x-1]-=1
p[h-1]+=p[h]+1
ans[i]=p[h]
def solve():
nonlocal ans
dfs(0, 0)
print(' '.join(map(str, ans)))
max_recur_size = 10**5*2 + 1000
max_stack_size = max_recur_size*500
sys.setrecursionlimit(max_recur_size)
threading.stack_size(max_stack_size)
thread = threading.Thread(target=solve)
thread.start() | python | test | qsol | codeparrot/apps | all |
Solve in Python:
The only difference between easy and hard versions is the constraints.
Vova likes pictures with kittens. The news feed in the social network he uses can be represented as an array of $n$ consecutive pictures (with kittens, of course). Vova likes all these pictures, but some are more beautiful than the others: the $i$-th picture has beauty $a_i$.
Vova wants to repost exactly $x$ pictures in such a way that: each segment of the news feed of at least $k$ consecutive pictures has at least one picture reposted by Vova; the sum of beauty values of reposted pictures is maximum possible.
For example, if $k=1$ then Vova has to repost all the pictures in the news feed. If $k=2$ then Vova can skip some pictures, but between every pair of consecutive pictures Vova has to repost at least one of them.
Your task is to calculate the maximum possible sum of values of reposted pictures if Vova follows conditions described above, or say that there is no way to satisfy all conditions.
-----Input-----
The first line of the input contains three integers $n, k$ and $x$ ($1 \le k, x \le n \le 5000$) — the number of pictures in the news feed, the minimum length of segment with at least one repost in it and the number of pictures Vova is ready to repost.
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 beauty of the $i$-th picture.
-----Output-----
Print -1 if there is no way to repost some pictures to satisfy all the conditions in the problem statement.
Otherwise print one integer — the maximum sum of values of reposted pictures if Vova follows conditions described in the problem statement.
-----Examples-----
Input
5 2 3
5 1 3 10 1
Output
18
Input
6 1 5
10 30 30 70 10 10
Output
-1
Input
4 3 1
1 100 1 1
Output
100 | n, k, x = list(map(int, input().split()))
a = [None] + list(map(int, input().split()))
lo, hi = 0, 10 ** 9 * 5000
q = [None] * (n + 1)
def get(mid):
f, r = 0, 0
q[0] = 0, 0, 0
for i in range(1, n + 1):
if q[r][2] == i - k - 1: r += 1
cur = q[r][0] + a[i] - mid, q[r][1] + 1, i
while r <= f and q[f] <= cur: f -= 1
f += 1
q[f] = cur
if q[r][2] == n - k: r += 1
return q[r]
while lo < hi:
mid = (lo + hi + 1) >> 1
_, cnt, _ = get(mid)
if cnt >= x:
lo = mid
else:
hi = mid - 1
sm, _, _ = get(lo)
ans = max(-1, sm + x * lo)
print(ans) | python | test | qsol | codeparrot/apps | all |
Solve in Python:
Boboniu gives you
$r$ red balls, $g$ green balls, $b$ blue balls, $w$ white balls.
He allows you to do the following operation as many times as you want:
Pick a red ball, a green ball, and a blue ball and then change their color to white.
You should answer if it's possible to arrange all the balls into a palindrome after several (possibly zero) number of described operations.
-----Input-----
The first line contains one integer $T$ ($1\le T\le 100$) denoting the number of test cases.
For each of the next $T$ cases, the first line contains four integers $r$, $g$, $b$ and $w$ ($0\le r,g,b,w\le 10^9$).
-----Output-----
For each test case, print "Yes" if it's possible to arrange all the balls into a palindrome after doing several (possibly zero) number of described operations. Otherwise, print "No".
-----Example-----
Input
4
0 1 1 1
8 1 9 3
0 0 0 0
1000000000 1000000000 1000000000 1000000000
Output
No
Yes
Yes
Yes
-----Note-----
In the first test case, you're not able to do any operation and you can never arrange three balls of distinct colors into a palindrome.
In the second test case, after doing one operation, changing $(8,1,9,3)$ to $(7,0,8,6)$, one of those possible palindromes may be "rrrwwwbbbbrbbbbwwwrrr".
A palindrome is a word, phrase, or sequence that reads the same backwards as forwards. For example, "rggbwbggr", "b", "gg" are palindromes while "rgbb", "gbbgr" are not. Notice that an empty word, phrase, or sequence is palindrome. | for t in range(int(input())):
r,g,b,w = list(map(int, input().split()))
if r==0 or g==0 or b==0:
if r%2+g%2+b%2+w%2 <= 1:
print("Yes")
else:
print("No")
else:
if r%2+g%2+b%2+w%2 == 2:
print("No")
else:
print("Yes") | python | test | qsol | codeparrot/apps | all |
I found an interesting problem on https://atcoder.jp/contests/abc154/tasks/abc154_d:
We have N dice arranged in a line from left to right. The i-th die from the left shows p_i numbers from 1 to p_i with equal probability when thrown.
We will choose K adjacent dice, throw each of them independently, and compute the sum of the numbers shown. Find the maximum possible value of the expected value of this sum.
-----Constraints-----
- 1 ≤ K ≤ N ≤ 200000
- 1 ≤ p_i ≤ 1000
- All values in input are integers.
-----Input-----
Input is given from Standard Input in the following format:
N K
p_1 ... p_N
-----Output-----
Print the maximum possible value of the expected value of the sum of the numbers shown.
Your output will be considered correct when its absolute or relative error from our answer is at most 10^{-6}.
-----Sample Input-----
5 3
1 2 2 4 5
-----Sample Output-----
7.000000000000
When we throw the third, fourth, and fifth dice from the left, the expected value of the sum of the numbers shown is 7. This is the maximum value we can achieve.
I tried it in Python, but could not do it. Can you solve it? | n,k=map(int,input().split())
p=list(map(int,input().split()))
dp=[0]*(n-k+1)
dp[0]=sum(p[:k])
for i in range(n-k):
dp[i+1]=dp[i]+p[k+i]-p[i]
print((max(dp)+k)/2) | python | test | abovesol | codeparrot/apps | all |
I found an interesting problem on https://atcoder.jp/contests/abc118/tasks/abc118_c:
There are N monsters, numbered 1, 2, ..., N.
Initially, the health of Monster i is A_i.
Below, a monster with at least 1 health is called alive.
Until there is only one alive monster, the following is repeated:
- A random alive monster attacks another random alive monster.
- As a result, the health of the monster attacked is reduced by the amount equal to the current health of the monster attacking.
Find the minimum possible final health of the last monster alive.
-----Constraints-----
- All values in input are integers.
- 2 \leq N \leq 10^5
- 1 \leq A_i \leq 10^9
-----Input-----
Input is given from Standard Input in the following format:
N
A_1 A_2 ... A_N
-----Output-----
Print the minimum possible final health of the last monster alive.
-----Sample Input-----
4
2 10 8 40
-----Sample Output-----
2
When only the first monster keeps on attacking, the final health of the last monster will be 2, which is minimum.
I tried it in Python, but could not do it. Can you solve it? | from math import gcd
N = int(input())
A = list(map(int,input().split()))
res = 0
for i in range(N):
res = gcd(res,A[i])
print(res) | python | test | abovesol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/442/A:
Have you ever played Hanabi? If not, then you've got to try it out! This problem deals with a simplified version of the game.
Overall, the game has 25 types of cards (5 distinct colors and 5 distinct values). Borya is holding n cards. The game is somewhat complicated by the fact that everybody sees Borya's cards except for Borya himself. Borya knows which cards he has but he knows nothing about the order they lie in. Note that Borya can have multiple identical cards (and for each of the 25 types of cards he knows exactly how many cards of this type he has).
The aim of the other players is to achieve the state when Borya knows the color and number value of each of his cards. For that, other players can give him hints. The hints can be of two types: color hints and value hints.
A color hint goes like that: a player names some color and points at all the cards of this color.
Similarly goes the value hint. A player names some value and points at all the cards that contain the value.
Determine what minimum number of hints the other players should make for Borya to be certain about each card's color and value.
-----Input-----
The first line contains integer n (1 ≤ n ≤ 100) — the number of Borya's cards. The next line contains the descriptions of n cards. The description of each card consists of exactly two characters. The first character shows the color (overall this position can contain five distinct letters — R, G, B, Y, W). The second character shows the card's value (a digit from 1 to 5). Borya doesn't know exact order of the cards they lie in.
-----Output-----
Print a single integer — the minimum number of hints that the other players should make.
-----Examples-----
Input
2
G3 G3
Output
0
Input
4
G4 R4 R3 B3
Output
2
Input
5
B1 Y1 W1 G1 R1
Output
4
-----Note-----
In the first sample Borya already knows for each card that it is a green three.
In the second sample we can show all fours and all red cards.
In the third sample you need to make hints about any four colors.
I tried it in Python, but could not do it. Can you solve it? | input()
colour = {'R': 0, 'G': 1, 'B': 2, 'Y': 3, 'W': 4}
cards = {(colour[c], ord(v) - ord('1')) for c, v in input().split()}
def ok(cs, vs):
return len({
(c if (cs >> c) & 1 else -1, v if (vs >> v) & 1 else -1)
for c, v in cards
}) == len(cards)
print((min(bin(cs).count('1') + bin(vs).count('1')
for cs in range(1<<5) for vs in range(1<<5)
if ok(cs, vs)
))) | python | test | abovesol | codeparrot/apps | all |
Solve in Python:
Count the number of distinct sequences a_1, a_2, ..., a_{n} (1 ≤ a_{i}) consisting of positive integers such that gcd(a_1, a_2, ..., a_{n}) = x and $\sum_{i = 1}^{n} a_{i} = y$. As this number could be large, print the answer modulo 10^9 + 7.
gcd here means the greatest common divisor.
-----Input-----
The only line contains two positive integers x and y (1 ≤ x, y ≤ 10^9).
-----Output-----
Print the number of such sequences modulo 10^9 + 7.
-----Examples-----
Input
3 9
Output
3
Input
5 8
Output
0
-----Note-----
There are three suitable sequences in the first test: (3, 3, 3), (3, 6), (6, 3).
There are no suitable sequences in the second test. | import math
lectura=lambda:map (int,input().split())
x,y=lectura()
mod= 1000000007
if (y%x!=0):
print("0")
else:
y= y//x
setPrueba=set()
for i in range(1, int(math.sqrt(y) + 1)):
if (y%i==0):
setPrueba.add(i)
setPrueba.add(y// i)
setPrueba=sorted(list(setPrueba))
setOrdenado= setPrueba.copy()
for i in range(len(setOrdenado)):
#setOrdenado[i] = math.pow(2, setPrueba[i] - 1)
setOrdenado[i]=pow(2, setPrueba[i] - 1, mod)
for j in range(i):
if setPrueba[i]% setPrueba[j]==0:
setOrdenado[i]-= setOrdenado[j]
print(setOrdenado[len(setOrdenado)-1] % mod) | python | test | qsol | codeparrot/apps | all |
I found an interesting problem on https://www.codewars.com/kata/54e2213f13d73eb9de0006d2:
For a given array whose element values are randomly picked from single-digit integers `0` to `9`, return an array with the same digit order but all `0`'s paired. Paring two `0`'s generates one `0` at the location of the first.
Ex:
```python
pair_zeros([0, 1, 0, 2])
# paired: ^-----^ cull second zero
== [0, 1, 2];
# kept: ^
pair_zeros([0, 1, 0, 0])
# paired: ^-----^
== [0, 1, 0];
# kept: ^
pair_zeros([1, 0, 7, 0, 1])
# paired: ^-----^
== [1, 0, 7, 1];
# kept: ^
pair_zeros([0, 1, 7, 0, 2, 2, 0, 0, 1, 0])
# paired: ^--------^
# [0, 1, 7, 2, 2, 0, 0, 1, 0]
# kept: ^ paired: ^--^
== [0, 1, 7, 2, 2, 0, 1, 0];
# kept: ^
```
Here are the 2 important rules:
1. Pairing happens from left to right in the array. However, for each pairing, the "second" `0` will always be paired towards the first (right to left)
2. `0`'s generated by pairing can NOT be paired again
I tried it in Python, but could not do it. Can you solve it? | def pair_zeros(arr):
lst = []
zCount = 0
for item in arr:
if item == 0:
zCount += 1
if zCount % 2 != 0:
lst.append(item)
else:
lst.append(item)
return lst | python | train | abovesol | codeparrot/apps | all |
I found an interesting problem on https://www.hackerrank.com/challenges/py-set-symmetric-difference-operation/problem:
=====Function Descriptions=====
.symmetric_difference()
The .symmetric_difference() operator returns a set with all the elements that are in the set and the iterable but not both.
Sometimes, a ^ operator is used in place of the .symmetric_difference() tool, but it only operates on the set of elements in set.
The set is immutable to the .symmetric_difference() operation (or ^ operation).
>>> s = set("Hacker")
>>> print s.symmetric_difference("Rank")
set(['c', 'e', 'H', 'n', 'R', 'r'])
>>> print s.symmetric_difference(set(['R', 'a', 'n', 'k']))
set(['c', 'e', 'H', 'n', 'R', 'r'])
>>> print s.symmetric_difference(['R', 'a', 'n', 'k'])
set(['c', 'e', 'H', 'n', 'R', 'r'])
>>> print s.symmetric_difference(enumerate(['R', 'a', 'n', 'k']))
set(['a', 'c', 'e', 'H', (0, 'R'), 'r', (2, 'n'), 'k', (1, 'a'), (3, 'k')])
>>> print s.symmetric_difference({"Rank":1})
set(['a', 'c', 'e', 'H', 'k', 'Rank', 'r'])
>>> s ^ set("Rank")
set(['c', 'e', 'H', 'n', 'R', 'r'])
=====Problem Statement=====
Students of District College have subscriptions to English and French newspapers. Some students have subscribed to English only, some have subscribed to French only, and some have subscribed to both newspapers.
You are given two sets of student roll numbers. One set has subscribed to the English newspaper, and one set has subscribed to the French newspaper. Your task is to find the total number of students who have subscribed to either the English or the French newspaper but not both.
=====Input Format=====
The first line contains the number of students who have subscribed to the English newspaper.
The second line contains the space separated list of student roll numbers who have subscribed to the English newspaper.
The third line contains the number of students who have subscribed to the French newspaper.
The fourth line contains the space separated list of student roll numbers who have subscribed to the French newspaper.
=====Constraints=====
0 < Total number of students in college < 1000
=====Output Format=====
Output...
I tried it in Python, but could not do it. Can you solve it? | e = int(input())
eng = set(map(int,input().split()))
f = int(input())
fre = set(map(int,input().split()))
print((len(eng ^ fre))) | python | train | abovesol | codeparrot/apps | all |
Solve in Python:
This is a follow-up from my previous Kata which can be found here: http://www.codewars.com/kata/5476f4ca03810c0fc0000098
This time, for any given linear sequence, calculate the function [f(x)] and return it as a function in Javascript or Lambda/Block in Ruby.
For example:
```python
get_function([0, 1, 2, 3, 4])(5) => 5
get_function([0, 3, 6, 9, 12])(10) => 30
get_function([1, 4, 7, 10, 13])(20) => 61
```
Assumptions for this kata are:
```
The sequence argument will always contain 5 values equal to f(0) - f(4).
The function will always be in the format "nx +/- m", 'x +/- m', 'nx', 'x' or 'm'
If a non-linear sequence simply return 'Non-linear sequence' for javascript, ruby, and python. For C#, throw an ArgumentException.
``` | def get_function(seq):
b = seq[0]
a = seq[1] - b
f = lambda x: a*x + b
if not all(f(i) == seq[i] for i in range(5)):
return 'Non-linear sequence'
return f | python | train | qsol | codeparrot/apps | all |
I found an interesting problem on https://www.codewars.com/kata/53c945d750fe7094ee00016b:
A common problem in number theory is to find x given a such that:
a * x = 1 mod [n]
Then x is called the inverse of a modulo n.
Your goal is to code a function inverseMod wich take a and n as parameters and return x.
You may be interested by these pages:
http://en.wikipedia.org/wiki/Modular_multiplicative_inverse
http://en.wikipedia.org/wiki/Extended_Euclidean_algorithm
a and n should be co-prime to have a solution, if it is not the case, you should return None (Python), nil (Ruby) or null (Javascript).
a and n will be positive integers. The problem can easily be generalised to negative integer with some sign changes so we won't deal with them.
I tried it in Python, but could not do it. Can you solve it? | import math
def phi(a):
res = a
b = a
i = 2
while i*i <= a:
if a % i == 0:
res -= res//i
while a % i == 0:
a //= i
i = i+1
if(a>1):
res -= res//a
return res
def inverseMod(a, m):
if math.gcd(a,m) != 1:
return None
_phi = phi(m)
return pow(a,_phi-1,m) | python | train | abovesol | codeparrot/apps | all |
Solve in Python:
Is the MRP of my new shoes exclusive or inclusive of taxes?
-----Input:-----
- First line will contain an integer $P$
-----Output:-----
For each testcase, print either 'Inclusive' or 'Exclusive' without quotes.
-----Constraints-----
- $100 \leq P \leq 999$
-----Sample Input 1:-----
123
-----Sample Output 1:-----
Exclusive
-----Sample Input 2:-----
111
-----Sample Output 2:-----
Inclusive | n = input()
ans = 0
for i in n:
ans = ans ^int(i)
if ans:
print("Inclusive")
else:
print("Exclusive") | python | test | qsol | codeparrot/apps | all |
I found an interesting problem on https://www.codechef.com/problems/LADDU:
You might have heard about our new goodie distribution program aka the "Laddu Accrual System". This problem is designed to give you a glimpse of its rules. You can read the page once before attempting the problem if you wish, nonetheless we will be providing all the information needed here itself.
Laddu Accrual System is our new goodie distribution program. In this program, we will be distributing Laddus in place of goodies for your winnings and various other activities (described below), that you perform on our system. Once you collect enough number of Laddus, you can then redeem them to get yourself anything from a wide range of CodeChef goodies.
Let us know about various activities and amount of laddus you get corresponding to them.
- Contest Win (CodeChef’s Long, Cook-Off, LTIME, or any contest hosted with us) : 300 + Bonus (Bonus = 20 - contest rank). Note that if your rank is > 20, then you won't get any bonus.
- Top Contributor on Discuss : 300
- Bug Finder : 50 - 1000 (depending on the bug severity). It may also fetch you a CodeChef internship!
- Contest Hosting : 50
You can do a checkout for redeeming laddus once a month. The minimum laddus redeemable at Check Out are 200 for Indians and 400 for the rest of the world.
You are given history of various activities of a user. The user has not redeemed any of the its laddus accrued.. Now the user just wants to redeem as less amount of laddus he/she can, so that the laddus can last for as long as possible. Find out for how many maximum number of months he can redeem the laddus.
-----Input-----
- The first line of input contains a single integer T denoting number of test cases
- For each test case:
- First line contains an integer followed by a string denoting activities, origin respectively, where activities denotes number of activities of the user, origin denotes whether the user is Indian or the rest of the world. origin can be "INDIAN" or "NON_INDIAN".
- For each of the next activities lines, each line contains an activity.
An...
I tried it in Python, but could not do it. Can you solve it? | for _ in range(int(input())):
a = input().split()
total=0
for i in range(int(a[0])):
x=input().split()
if x[0]=='CONTEST_WON':
if int(x[1])<20:
total+=20-int(x[1])
total+=300
elif x[0]=='TOP_CONTRIBUTOR':
total+=300
elif x[0]=='BUG_FOUND':
total+=int(x[1])
elif x[0]=='CONTEST_HOSTED':
total+=50
if a[1]=='INDIAN':
print(total//200)
elif a[1]=='NON_INDIAN':
print(total//400) | python | train | abovesol | codeparrot/apps | all |
Solve in Python:
Dima liked the present he got from Inna very much. He liked the present he got from Seryozha even more.
Dima felt so grateful to Inna about the present that he decided to buy her n hares. Inna was very happy. She lined up the hares in a row, numbered them from 1 to n from left to right and started feeding them with carrots. Inna was determined to feed each hare exactly once. But in what order should she feed them?
Inna noticed that each hare radiates joy when she feeds it. And the joy of the specific hare depends on whether Inna fed its adjacent hares before feeding it. Inna knows how much joy a hare radiates if it eats when either both of his adjacent hares are hungry, or one of the adjacent hares is full (that is, has been fed), or both of the adjacent hares are full. Please note that hares number 1 and n don't have a left and a right-adjacent hare correspondingly, so they can never have two full adjacent hares.
Help Inna maximize the total joy the hares radiate. :)
-----Input-----
The first line of the input contains integer n (1 ≤ n ≤ 3000) — the number of hares. Then three lines follow, each line has n integers. The first line contains integers a_1 a_2 ... a_{n}. The second line contains b_1, b_2, ..., b_{n}. The third line contains c_1, c_2, ..., c_{n}. The following limits are fulfilled: 0 ≤ a_{i}, b_{i}, c_{i} ≤ 10^5.
Number a_{i} in the first line shows the joy that hare number i gets if his adjacent hares are both hungry. Number b_{i} in the second line shows the joy that hare number i radiates if he has exactly one full adjacent hare. Number с_{i} in the third line shows the joy that hare number i radiates if both his adjacent hares are full.
-----Output-----
In a single line, print the maximum possible total joy of the hares Inna can get by feeding them.
-----Examples-----
Input
4
1 2 3 4
4 3 2 1
0 1 1 0
Output
13
Input
7
8 5 7 6 1 8 9
2 7 9 5 4 3 1
2 3 3 4 1 1 3
Output
44
Input
3
1 1 1
1 2 1
1 1 1
Output
4 | n = int(input())
R = lambda: [int(i) for i in input().split()]
a, b, c = R(), R(), R()
x, y = a[0], b[0]
for i in range(1, n):
x, y = max(a[i] + y, b[i] + x), max(b[i] + y, c[i] + x)
print(x) | python | test | qsol | codeparrot/apps | all |
Solve in Python:
It is a holiday season, and Koala is decorating his house with cool lights! He owns $n$ lights, all of which flash periodically.
After taking a quick glance at them, Koala realizes that each of his lights can be described with two parameters $a_i$ and $b_i$. Light with parameters $a_i$ and $b_i$ will toggle (on to off, or off to on) every $a_i$ seconds starting from the $b_i$-th second. In other words, it will toggle at the moments $b_i$, $b_i + a_i$, $b_i + 2 \cdot a_i$ and so on.
You know for each light whether it's initially on or off and its corresponding parameters $a_i$ and $b_i$. Koala is wondering what is the maximum number of lights that will ever be on at the same time. So you need to find that out.
[Image] Here is a graphic for the first example.
-----Input-----
The first line contains a single integer $n$ ($1 \le n \le 100$), the number of lights.
The next line contains a string $s$ of $n$ characters. The $i$-th character is "1", if the $i$-th lamp is initially on. Otherwise, $i$-th character is "0".
The $i$-th of the following $n$ lines contains two integers $a_i$ and $b_i$ ($1 \le a_i, b_i \le 5$) — the parameters of the $i$-th light.
-----Output-----
Print a single integer — the maximum number of lights that will ever be on at the same time.
-----Examples-----
Input
3
101
3 3
3 2
3 1
Output
2
Input
4
1111
3 4
5 2
3 1
3 2
Output
4
Input
6
011100
5 3
5 5
2 4
3 5
4 2
1 5
Output
6
-----Note-----
For first example, the lamps' states are shown in the picture above. The largest number of simultaneously on lamps is $2$ (e.g. at the moment $2$).
In the second example, all lights are initially on. So the answer is $4$. | n=int(input())
s=input()
arr=[int(s[i]) for i in range(len(s))]
t=[]
for i in range(n):
t.append([int(x) for x in input().split()])
ans=sum(arr)
for i in range(2000):
for j in range(n):
if i>=t[j][1] and (i-t[j][1]) % t[j][0] == 0:
if arr[j] == 1:
arr[j]=0
else:
arr[j]=1
ans=max(ans,sum(arr))
print(ans) | python | test | qsol | codeparrot/apps | all |
I found an interesting problem on https://www.codewars.com/kata/58b8cc7e8e7121740700002d:
# Task
Given an array `arr`, find the rank of the element at the ith position.
The `rank` of the arr[i] is a value equal to the number of elements `less than or equal to` arr[i] standing before arr[i], plus the number of elements `less than` arr[i] standing after arr[i].
# Example
For `arr = [2,1,2,1,2], i = 2`, the result should be `3`.
There are 2 elements `less than or equal to` arr[2] standing before arr[2]:
`arr[0] <= arr[2]`
`arr[1] <= arr[2]`
There is only 1 element `less than` arr[2] standing after arr[2]:
`arr[3] < arr[2]`
So the result is `2 + 1 = 3`.
# Input/Output
- `[input]` integer array `arr`
An array of integers.
`3 <= arr.length <= 50.`
- `[input]` integer `i`
Index of the element whose rank is to be found.
- `[output]` an integer
Rank of the element at the ith position.
I tried it in Python, but could not do it. Can you solve it? | def rank_of_element(arr,i):
return sum(v < arr[i]+(x<i) for x,v in enumerate(arr) if x!=i) | python | train | abovesol | codeparrot/apps | all |
Solve in Python:
There are $n$ candies in a row, they are numbered from left to right from $1$ to $n$. The size of the $i$-th candy is $a_i$.
Alice and Bob play an interesting and tasty game: they eat candy. Alice will eat candy from left to right, and Bob — from right to left. The game ends if all the candies are eaten.
The process consists of moves. During a move, the player eats one or more sweets from her/his side (Alice eats from the left, Bob — from the right).
Alice makes the first move. During the first move, she will eat $1$ candy (its size is $a_1$). Then, each successive move the players alternate — that is, Bob makes the second move, then Alice, then again Bob and so on.
On each move, a player counts the total size of candies eaten during the current move. Once this number becomes strictly greater than the total size of candies eaten by the other player on their previous move, the current player stops eating and the move ends. In other words, on a move, a player eats the smallest possible number of candies such that the sum of the sizes of candies eaten on this move is strictly greater than the sum of the sizes of candies that the other player ate on the previous move. If there are not enough candies to make a move this way, then the player eats up all the remaining candies and the game ends.
For example, if $n=11$ and $a=[3,1,4,1,5,9,2,6,5,3,5]$, then: move 1: Alice eats one candy of size $3$ and the sequence of candies becomes $[1,4,1,5,9,2,6,5,3,5]$. move 2: Alice ate $3$ on the previous move, which means Bob must eat $4$ or more. Bob eats one candy of size $5$ and the sequence of candies becomes $[1,4,1,5,9,2,6,5,3]$. move 3: Bob ate $5$ on the previous move, which means Alice must eat $6$ or more. Alice eats three candies with the total size of $1+4+1=6$ and the sequence of candies becomes $[5,9,2,6,5,3]$. move 4: Alice ate $6$ on the previous move, which means Bob must eat $7$ or more. Bob eats two candies with the total size of $3+5=8$ and the sequence of candies becomes $[5,9,2,6]$. move 5: Bob... | t = int(input())
for loop in range(t):
n = int(input())
lis = list(map(int,input().split()))
ai = 0
bi = n-1
A = [0]
B = [0]
move = 0
while True:
if ai > bi:
break
na = 0
while na <= B[-1]:
if ai > bi:
break
na += lis[ai]
ai += 1
A.append(na)
if na > 0:
move += 1
nb = 0
while nb <= A[-1]:
if ai > bi:
break
nb += lis[bi]
bi -= 1
B.append(nb)
if nb > 0:
move += 1
print(move,sum(A),sum(B)) | python | test | qsol | codeparrot/apps | all |
Solve in Python:
In the year 4242, the language Haskell has evolved so much that it has become an AI. It can solve very challenging problems, in very little time. Humanity is worried that Haskell will take over the world. All hopes remain tied to the Competitive Programming community as they are the expert in shaving milliseconds off code runtime. Haskell creators have found one particular task that if solved faster than Haskell itself, can be used to hack into Haskell's codebase and thus defeat it. The exact details of the task are as follows,
" Calculate the sum, S(N, K) = , for Q queries. Here Fi is ith Fibonacci number defined as: Fi = i if i = 0 or 1 and Fi = Fi-1 + Fi-2 if i >= 2. "
You being a member of the Competitive Programming community are encouraged to make a submission to this task.
-----Input-----
The first line contains a single integer Q, the number of queries.
Each of the next Q lines contain two integers each, Ni and Ki.
-----Output-----
Output Q lines with one integer each. The ith line should contain the value S(Ni, Ki).
-----Constraints-----
- 1 <= Q <= 5*104
- 1 <= N <= 1018
- 1 <= K <= 1018
-----Example-----
Input:
1
1 1
Output:
1 | mod=10**9+7
def fibonacci(n):
if n < 0:
raise ValueError("Negative arguments not implemented")
return (_fib(n)[0]%mod + mod)%mod;
def _fib(n):
if n == 0:
return (0, 1)
else:
a, b = _fib(n // 2)
c = (a * (b * 2 - a))%mod
d = (a * a + b * b)%mod
if n % 2 == 0:
return (c, d)
else:
return (d, c + d)
def inv(n):
return pow(n,mod-2,mod)
def brute(n,k):
ret = 0
for i in range(0,n+1):
ret+=fibonacci(i)*pow(k,i,mod)
return ret%mod
def ans(n,k):
k%=mod
a = pow(k,n+1,mod)
b=(a*k)%mod
x = a*(fibonacci(n+1))+b*fibonacci(n)-k
y = inv((k*k+k-1)%mod)
return ((x*y)%mod+mod)%mod
for t in range(0,eval(input())):
n,k = list(map(int,input().split()))
print(ans(n,k)) | python | train | qsol | codeparrot/apps | all |
I found an interesting problem on https://www.codewars.com/kata/54f9cba3c417224c63000872:
The Monty Hall problem is a probability puzzle base on the American TV show "Let's Make A Deal".
In this show, you would be presented with 3 doors: One with a prize behind it, and two without (represented with goats).
After choosing a door, the host would open one of the other two doors which didn't include a prize, and ask the participant if he or she wanted to switch to the third door. Most wouldn't. One would think you have a fifty-fifty chance of winning after having been shown a false door, however the math proves that you significantly increase your chances, from 1/3 to 2/3 by switching.
Further information about this puzzle can be found on https://en.wikipedia.org/wiki/Monty_Hall_problem.
In this program you are given an array of people who have all guessed on a door from 1-3, as well as given the door which includes the price. You need to make every person switch to the other door, and increase their chances of winning. Return the win percentage (as a rounded int) of all participants.
I tried it in Python, but could not do it. Can you solve it? | def monty_hall(cdoor, pguesses):
pick_cdoor=1-pguesses.count(cdoor)/len(pguesses)
return round(pick_cdoor*100) | python | train | abovesol | codeparrot/apps | all |
Solve in Python:
Write a simple parser that will parse and run Deadfish.
Deadfish has 4 commands, each 1 character long:
* `i` increments the value (initially `0`)
* `d` decrements the value
* `s` squares the value
* `o` outputs the value into the return array
Invalid characters should be ignored.
```python
parse("iiisdoso") ==> [8, 64]
``` | def parse(data):
action = {'i': lambda v, r: v + 1,
'd': lambda v, r: v - 1,
's': lambda v, r: v * v,
'o': lambda v, r: r.append(v) or v}
v, r = 0, []
for a in data:
v = action[a](v, r) if a in action else v
return r | python | train | qsol | codeparrot/apps | all |
Solve in Python:
There are n schoolchildren, boys and girls, lined up in the school canteen in front of the bun stall. The buns aren't ready yet and the line is undergoing some changes.
Each second all boys that stand right in front of girls, simultaneously swap places with the girls (so that the girls could go closer to the beginning of the line). In other words, if at some time the i-th position has a boy and the (i + 1)-th position has a girl, then in a second, the i-th position will have a girl and the (i + 1)-th one will have a boy.
Let's take an example of a line of four people: a boy, a boy, a girl, a girl (from the beginning to the end of the line). Next second the line will look like that: a boy, a girl, a boy, a girl. Next second it will be a girl, a boy, a girl, a boy. Next second it will be a girl, a girl, a boy, a boy. The line won't change any more.
Your task is: given the arrangement of the children in the line to determine the time needed to move all girls in front of boys (in the example above it takes 3 seconds). Baking buns takes a lot of time, so no one leaves the line until the line stops changing.
-----Input-----
The first line contains a sequence of letters without spaces s_1s_2... s_{n} (1 ≤ n ≤ 10^6), consisting of capital English letters M and F. If letter s_{i} equals M, that means that initially, the line had a boy on the i-th position. If letter s_{i} equals F, then initially the line had a girl on the i-th position.
-----Output-----
Print a single integer — the number of seconds needed to move all the girls in the line in front of the boys. If the line has only boys or only girls, print 0.
-----Examples-----
Input
MFM
Output
1
Input
MMFF
Output
3
Input
FFMMM
Output
0
-----Note-----
In the first test case the sequence of changes looks as follows: MFM → FMM.
The second test sample corresponds to the sample from the statement. The sequence of changes is: MMFF → MFMF → FMFM → FFMM. | a=input();n=len(a);o,k=0,0
for i in range(n):
if(a[i]=='F'):
k=k+1
if(i+1!=k):o=max(o+1,i+1-k)
print(o) | python | test | qsol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/768/F:
Tarly has two different type of items, food boxes and wine barrels. There are f food boxes and w wine barrels. Tarly stores them in various stacks and each stack can consist of either food boxes or wine barrels but not both. The stacks are placed in a line such that no two stacks of food boxes are together and no two stacks of wine barrels are together.
The height of a stack is defined as the number of items in the stack. Two stacks are considered different if either their heights are different or one of them contains food and other contains wine.
Jon Snow doesn't like an arrangement if any stack of wine barrels has height less than or equal to h. What is the probability that Jon Snow will like the arrangement if all arrangement are equiprobably?
Two arrangement of stacks are considered different if exists such i, that i-th stack of one arrangement is different from the i-th stack of the other arrangement.
-----Input-----
The first line of input contains three integers f, w, h (0 ≤ f, w, h ≤ 10^5) — number of food boxes, number of wine barrels and h is as described above. It is guaranteed that he has at least one food box or at least one wine barrel.
-----Output-----
Output the probability that Jon Snow will like the arrangement. The probability is of the form [Image], then you need to output a single integer p·q^{ - 1} mod (10^9 + 7).
-----Examples-----
Input
1 1 1
Output
0
Input
1 2 1
Output
666666672
-----Note-----
In the first example f = 1, w = 1 and h = 1, there are only two possible arrangement of stacks and Jon Snow doesn't like any of them.
In the second example f = 1, w = 2 and h = 1, there are three arrangements. Jon Snow likes the (1) and (3) arrangement. So the probabilty is $\frac{2}{3}$. [Image]
I tried it in Python, but could not do it. Can you solve it? | def build_fac():
nonlocal mod
fac = [1] * int(3e5 + 1)
for i in range(1, int(3e5)):
fac[i] = i*fac[i-1] % mod
return fac
def inv(x):
nonlocal mod
return pow(x, mod-2, mod)
def ncr(n, r):
nonlocal fac
if n < 0 or n < r: return 0
return fac[n]*inv(fac[r])*inv(fac[n-r]) % mod
def cf(f, w, h):
nonlocal mod
if w == 0: return 1
rs = 0
for k in range(1, min(w//(h+1),f+1)+1):
rs += ncr(f+1, k) * ncr(w-k*h-1, k-1) % mod
rs %= mod
return rs
f, w, h = map(int,input().split(' '))
mod = int(1e9 + 7)
fac = build_fac()
cnt = cf(f, w, h)
rs = cnt*inv(ncr(f+w, w)) % mod
print(rs) | python | test | abovesol | codeparrot/apps | all |
I found an interesting problem on https://www.codewars.com/kata/525f50e3b73515a6db000b83:
Write a function that accepts an array of 10 integers (between 0 and 9), that returns a string of those numbers in the form of a phone number.
Example:
```python
create_phone_number([1, 2, 3, 4, 5, 6, 7, 8, 9, 0]) # => returns "(123) 456-7890"
```
```f#
createPhoneNumber [1; 2; 3; 4; 5; 6; 7; 8; 9; 0] // => returns "(123) 456-7890"
```
The returned format must be correct in order to complete this challenge.
Don't forget the space after the closing parentheses!
I tried it in Python, but could not do it. Can you solve it? | def create_phone_number(n):
str1 = ''.join(str(x) for x in n[0:3])
str2 = ''.join(str(x) for x in n[3:6])
str3 = ''.join(str(x) for x in n[6:10])
return '({}) {}-{}'.format(str1, str2, str3) | python | train | abovesol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/606/A:
Carl is a beginner magician. He has a blue, b violet and c orange magic spheres. In one move he can transform two spheres of the same color into one sphere of any other color. To make a spell that has never been seen before, he needs at least x blue, y violet and z orange spheres. Can he get them (possible, in multiple actions)?
-----Input-----
The first line of the input contains three integers a, b and c (0 ≤ a, b, c ≤ 1 000 000) — the number of blue, violet and orange spheres that are in the magician's disposal.
The second line of the input contains three integers, x, y and z (0 ≤ x, y, z ≤ 1 000 000) — the number of blue, violet and orange spheres that he needs to get.
-----Output-----
If the wizard is able to obtain the required numbers of spheres, print "Yes". Otherwise, print "No".
-----Examples-----
Input
4 4 0
2 1 2
Output
Yes
Input
5 6 1
2 7 2
Output
No
Input
3 3 3
2 2 2
Output
Yes
-----Note-----
In the first sample the wizard has 4 blue and 4 violet spheres. In his first action he can turn two blue spheres into one violet one. After that he will have 2 blue and 5 violet spheres. Then he turns 4 violet spheres into 2 orange spheres and he ends up with 2 blue, 1 violet and 2 orange spheres, which is exactly what he needs.
I tried it in Python, but could not do it. Can you solve it? | def f(x):
return x if x <= 0 else x // 2
(a, b, c) = list(map(int, input().split()))
(x, y, z) = list(map(int, input().split()))
(n, m, k) = (a - x, b - y, c - z)
ans = f(n) + f(m) + f(k)
if ans >= 0:
print("Yes")
else:
print("No") | python | test | abovesol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/1085/D:
You are given a tree (an undirected connected graph without cycles) and an integer $s$.
Vanya wants to put weights on all edges of the tree so that all weights are non-negative real numbers and their sum is $s$. At the same time, he wants to make the diameter of the tree as small as possible.
Let's define the diameter of a weighed tree as the maximum sum of the weights of the edges lying on the path between two some vertices of the tree. In other words, the diameter of a weighed tree is the length of the longest simple path in the tree, where length of a path is equal to the sum of weights over all edges in the path.
Find the minimum possible diameter that Vanya can get.
-----Input-----
The first line contains two integer numbers $n$ and $s$ ($2 \leq n \leq 10^5$, $1 \leq s \leq 10^9$) — the number of vertices in the tree and the sum of edge weights.
Each of the following $n−1$ lines contains two space-separated integer numbers $a_i$ and $b_i$ ($1 \leq a_i, b_i \leq n$, $a_i \neq b_i$) — the indexes of vertices connected by an edge. The edges are undirected.
It is guaranteed that the given edges form a tree.
-----Output-----
Print the minimum diameter of the tree that Vanya can get by placing some non-negative real weights on its edges with the sum equal to $s$.
Your answer will be considered correct if its absolute or relative error does not exceed $10^{-6}$.
Formally, let your answer be $a$, and the jury's answer be $b$. Your answer is considered correct if $\frac {|a-b|} {max(1, b)} \leq 10^{-6}$.
-----Examples-----
Input
4 3
1 2
1 3
1 4
Output
2.000000000000000000
Input
6 1
2 1
2 3
2 5
5 4
5 6
Output
0.500000000000000000
Input
5 5
1 2
2 3
3 4
3 5
Output
3.333333333333333333
-----Note-----
In the first example it is necessary to put weights like this: [Image]
It is easy to see that the diameter of this tree is $2$. It can be proved that it is the minimum possible diameter.
In the second example it is necessary to put weights like this: [Image]
I tried it in Python, but could not do it. Can you solve it? | n,s = map(int, input().split())
ans = {}
for i in range(n-1):
a,b = map(int, input().split())
if a in ans:
ans[a].append(b)
else:
ans[a] = [b,]
if b in ans:
ans[b].append(b)
else:
ans[b] = [a,]
max_count = 0
for key in ans:
if len(ans[key]) == 1:
max_count += 1
if n ==2 :
print(s)
else:
print(s/(max_count)*2) | python | test | abovesol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/549/H:
The determinant of a matrix 2 × 2 is defined as follows:$\operatorname{det} \left(\begin{array}{ll}{a} & {b} \\{c} & {d} \end{array} \right) = a d - b c$
A matrix is called degenerate if its determinant is equal to zero.
The norm ||A|| of a matrix A is defined as a maximum of absolute values of its elements.
You are given a matrix $A = \left(\begin{array}{ll}{a} & {b} \\{c} & {d} \end{array} \right)$. Consider any degenerate matrix B such that norm ||A - B|| is minimum possible. Determine ||A - B||.
-----Input-----
The first line contains two integers a and b (|a|, |b| ≤ 10^9), the elements of the first row of matrix A.
The second line contains two integers c and d (|c|, |d| ≤ 10^9) the elements of the second row of matrix A.
-----Output-----
Output a single real number, the minimum possible value of ||A - B||. Your answer is considered to be correct if its absolute or relative error does not exceed 10^{ - 9}.
-----Examples-----
Input
1 2
3 4
Output
0.2000000000
Input
1 0
0 1
Output
0.5000000000
-----Note-----
In the first sample matrix B is $\left(\begin{array}{ll}{1.2} & {1.8} \\{2.8} & {4.2} \end{array} \right)$
In the second sample matrix B is $\left(\begin{array}{ll}{0.5} & {0.5} \\{0.5} & {0.5} \end{array} \right)$
I tried it in Python, but could not do it. Can you solve it? | a, b = map(int, input().split())
c, d = map(int, input().split())
mn = min(a * d, b * c)
mx = max(a * d, b * c)
x = 10 ** 18
if (a + b + c + d) != 0:
x = abs((b * c - a * d) / (a + b + c + d))
if (a + b - c - d) != 0:
x = min(abs((b * c - a * d) / (a + b - c - d)), x)
if (a - b + c - d) != 0:
x = min(abs((b * c - a * d) / (a - b + c - d)), x)
if (a - b - c + d) != 0:
x = min(abs((b * c - a * d) / (a - b - c + d)), x)
if (a + b + c + d) == 0:
x = 0
print(x) | python | test | abovesol | codeparrot/apps | all |
I found an interesting problem on https://leetcode.com/problems/minimum-operations-to-make-array-equal/:
You have an array arr of length n where arr[i] = (2 * i) + 1 for all valid values of i (i.e. 0 <= i < n).
In one operation, you can select two indices x and y where 0 <= x, y < n and subtract 1 from arr[x] and add 1 to arr[y] (i.e. perform arr[x] -=1 and arr[y] += 1). The goal is to make all the elements of the array equal. It is guaranteed that all the elements of the array can be made equal using some operations.
Given an integer n, the length of the array. Return the minimum number of operations needed to make all the elements of arr equal.
Example 1:
Input: n = 3
Output: 2
Explanation: arr = [1, 3, 5]
First operation choose x = 2 and y = 0, this leads arr to be [2, 3, 4]
In the second operation choose x = 2 and y = 0 again, thus arr = [3, 3, 3].
Example 2:
Input: n = 6
Output: 9
Constraints:
1 <= n <= 10^4
I tried it in Python, but could not do it. Can you solve it? | class Solution:
def minOperations(self, n: int) -> int:
arr=[]
for i in range(n):
arr.append((2*i)+1)
s=sum(arr)//n
res=0
for i in range(n//2):
res+=s-arr[i]
return res | python | train | abovesol | codeparrot/apps | all |
I found an interesting problem on https://leetcode.com/problems/minimum-swaps-to-make-strings-equal/:
You are given two strings s1 and s2 of equal length consisting of letters "x" and "y" only. Your task is to make these two strings equal to each other. You can swap any two characters that belong to different strings, which means: swap s1[i] and s2[j].
Return the minimum number of swaps required to make s1 and s2 equal, or return -1 if it is impossible to do so.
Example 1:
Input: s1 = "xx", s2 = "yy"
Output: 1
Explanation:
Swap s1[0] and s2[1], s1 = "yx", s2 = "yx".
Example 2:
Input: s1 = "xy", s2 = "yx"
Output: 2
Explanation:
Swap s1[0] and s2[0], s1 = "yy", s2 = "xx".
Swap s1[0] and s2[1], s1 = "xy", s2 = "xy".
Note that you can't swap s1[0] and s1[1] to make s1 equal to "yx", cause we can only swap chars in different strings.
Example 3:
Input: s1 = "xx", s2 = "xy"
Output: -1
Example 4:
Input: s1 = "xxyyxyxyxx", s2 = "xyyxyxxxyx"
Output: 4
Constraints:
1 <= s1.length, s2.length <= 1000
s1, s2 only contain 'x' or 'y'.
I tried it in Python, but could not do it. Can you solve it? | class Solution:
def minimumSwap(self, s1: str, s2: str) -> int:
x = 0
y = 0
for index in range(0, len(s1)):
if s1[index] != s2[index]:
if s1[index] == 'x':
x += 1
else:
y += 1
mid = ( x + y ) / 2
x, y = x % 2, y % 2
if x + y == 1:
return -1
if x + y == 2:
mid += 1
print(mid)
return int(mid) | python | train | abovesol | codeparrot/apps | all |
I found an interesting problem on https://www.codechef.com/TSTIND16/problems/AMR15A:
Kattapa, as you all know was one of the greatest warriors of his time. The kingdom of Maahishmati had never lost a battle under him (as army-chief), and the reason for that was their really powerful army, also called as Mahasena.
Kattapa was known to be a very superstitious person. He believed that a soldier is "lucky" if the soldier is holding an even number of weapons, and "unlucky" otherwise. He considered the army as "READY FOR BATTLE" if the count of "lucky" soldiers is strictly greater than the count of "unlucky" soldiers, and "NOT READY" otherwise.
Given the number of weapons each soldier is holding, your task is to determine whether the army formed by all these soldiers is "READY FOR BATTLE" or "NOT READY".
Note: You can find the definition of an even number here.
-----Input-----
The first line of input consists of a single integer N denoting the number of soldiers. The second line of input consists of N space separated integers A1, A2, ..., AN, where Ai denotes the number of weapons that the ith soldier is holding.
-----Output-----
Generate one line output saying "READY FOR BATTLE", if the army satisfies the conditions that Kattapa requires or "NOT READY" otherwise (quotes for clarity).
-----Constraints-----
- 1 ≤ N ≤ 100
- 1 ≤ Ai ≤ 100
-----Example 1-----
Input:
1
1
Output:
NOT READY
-----Example 2-----
Input:
1
2
Output:
READY FOR BATTLE
-----Example 3-----
Input:
4
11 12 13 14
Output:
NOT READY
-----Example 4-----
Input:
3
2 3 4
Output:
READY FOR BATTLE
-----Example 5-----
Input:
5
1 2 3 4 5
Output:
NOT READY
-----Explanation-----
- Example 1: For the first example, N = 1 and the array A = [1]. There is only 1 soldier and he is holding 1 weapon, which is odd. The number of soldiers holding an even number of weapons = 0, and number of soldiers holding an odd number of weapons = 1. Hence, the answer is "NOT READY" since the number of soldiers holding an even number of weapons is not greater than the number of soldiers holding an odd number of weapons.
- Example 2: For the second...
I tried it in Python, but could not do it. Can you solve it? | n = int(input())
l = list(map(int, input().split()))
even = 0
for i in range(n):
if l[i]%2 == 0:
even += 1
odd = n - even
if even > odd:
print('READY FOR BATTLE')
else:
print('NOT READY') | python | test | abovesol | codeparrot/apps | all |
I found an interesting problem on https://leetcode.com/problems/two-city-scheduling/:
A company is planning to interview 2n people. Given the array costs where costs[i] = [aCosti, bCosti], the cost of flying the ith person to city a is aCosti, and the cost of flying the ith person to city b is bCosti.
Return the minimum cost to fly every person to a city such that exactly n people arrive in each city.
Example 1:
Input: costs = [[10,20],[30,200],[400,50],[30,20]]
Output: 110
Explanation:
The first person goes to city A for a cost of 10.
The second person goes to city A for a cost of 30.
The third person goes to city B for a cost of 50.
The fourth person goes to city B for a cost of 20.
The total minimum cost is 10 + 30 + 50 + 20 = 110 to have half the people interviewing in each city.
Example 2:
Input: costs = [[259,770],[448,54],[926,667],[184,139],[840,118],[577,469]]
Output: 1859
Example 3:
Input: costs = [[515,563],[451,713],[537,709],[343,819],[855,779],[457,60],[650,359],[631,42]]
Output: 3086
Constraints:
2n == costs.length
2 <= costs.length <= 100
costs.length is even.
1 <= aCosti, bCosti <= 1000
I tried it in Python, but could not do it. Can you solve it? | # sort by difference, where greatest difference is first?
# [[400, 50], [30, 200], [30, 20], [10, 20]]
# B A B A
# [[840, 118], [259, 770], [448, 54], [926, 667], [577, 469], [184, 139]]
# B A B B A A
# [[631, 42], [343, 819], [457, 60], [650, 359], [451, 713], [536, 709], [855, 779], [515, 563]]
# B A B B A A B A
# seemingly works for the given cases
# why??
# positives outweight the negatives
# we will be positive for at least the first n iterations (worst case we pick one city for the first n iterations)
# since we sorted by greatest difference first we will be maximizing our profits by taking
# the optimal choice when the difference is greatest
# we have costs[i] and costs[j] where i <= n and n < j < 2n and difference[i] > difference[j]
# if we make the optimal choice we will be up difference[i] - difference[j]
class Solution:
def twoCitySchedCost(self, costs: List[List[int]]) -> int:
sortedCosts = sorted(costs, key = lambda x: abs(x[0] - x[1]), reverse=True)
numA = 0
numB = 0
res = 0
for cost in sortedCosts:
if numB >= len(sortedCosts) / 2:
res += cost[0]
elif numA >= len(sortedCosts) / 2:
res += cost[1]
else:
if cost[0] < cost[1]:
res += cost[0]
numA += 1
else:
res += cost[1]
numB += 1
return res | python | train | abovesol | codeparrot/apps | all |
Solve in Python:
Given an array of positive integers, replace every element with the least greater element to its right.
If there is no greater element to its right, replace it with -1. For instance, given the array
`[8, 58, 71, 18, 31, 32, 63, 92, 43, 3, 91, 93, 25, 80, 28]`,
the desired output is
`[18, 63, 80, 25, 32, 43, 80, 93, 80, 25, 93, -1, 28, -1, -1]`.
Your task is to create a function "arrayManip()" that takes in an array as its argument, manipulates the array as described above, then return the resulting array.
Note: Return a new array, rather than modifying the passed array. | def array_manip(array):
return [
min((x for x in array[i:] if x > n), default=-1)
for i, n in enumerate(array)] | python | train | qsol | codeparrot/apps | all |
Solve in Python:
A number `n` is called `prime happy` if there is at least one prime less than `n` and the `sum of all primes less than n` is evenly divisible by `n`. Write `isPrimeHappy(n)` which returns `true` if `n` is `prime happy` else `false`. | def isPrime(n):
for i in range(2,int(n**.5)+1):
if n%i == 0:
return False
return True
def is_prime_happy(n):
sum = 0
for i in range(2,n):
if isPrime(i):
sum += i
if sum > 0 and not sum%n:
return True
return False | python | train | qsol | codeparrot/apps | all |
I found an interesting problem on https://leetcode.com/problems/count-good-nodes-in-binary-tree/:
Given a binary tree root, a node X in the tree is named good if in the path from root to X there are no nodes with a value greater than X.
Return the number of good nodes in the binary tree.
Example 1:
Input: root = [3,1,4,3,null,1,5]
Output: 4
Explanation: Nodes in blue are good.
Root Node (3) is always a good node.
Node 4 -> (3,4) is the maximum value in the path starting from the root.
Node 5 -> (3,4,5) is the maximum value in the path
Node 3 -> (3,1,3) is the maximum value in the path.
Example 2:
Input: root = [3,3,null,4,2]
Output: 3
Explanation: Node 2 -> (3, 3, 2) is not good, because "3" is higher than it.
Example 3:
Input: root = [1]
Output: 1
Explanation: Root is considered as good.
Constraints:
The number of nodes in the binary tree is in the range [1, 10^5].
Each node's value is between [-10^4, 10^4].
I tried it in Python, but could not do it. Can you solve it? | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def goodNodes(self, root: TreeNode) -> int:
return self.count_good_nodes(root, root.val)
def count_good_nodes(self, root: TreeNode, highest_val: int) -> int:
current_highest = highest_val
total = 0
if root.val >= current_highest:
total += 1
current_highest = root.val
if root.left:
total += self.count_good_nodes(root.left, current_highest)
if root.right:
total += self.count_good_nodes(root.right, current_highest)
return total | python | train | abovesol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/979/A:
Katie, Kuro and Shiro are best friends. They have known each other since kindergarten. That's why they often share everything with each other and work together on some very hard problems.
Today is Shiro's birthday. She really loves pizza so she wants to invite her friends to the pizza restaurant near her house to celebrate her birthday, including her best friends Katie and Kuro.
She has ordered a very big round pizza, in order to serve her many friends. Exactly $n$ of Shiro's friends are here. That's why she has to divide the pizza into $n + 1$ slices (Shiro also needs to eat). She wants the slices to be exactly the same size and shape. If not, some of her friends will get mad and go home early, and the party will be over.
Shiro is now hungry. She wants to cut the pizza with minimum of straight cuts. A cut is a straight segment, it might have ends inside or outside the pizza. But she is too lazy to pick up the calculator.
As usual, she will ask Katie and Kuro for help. But they haven't come yet. Could you help Shiro with this problem?
-----Input-----
A single line contains one non-negative integer $n$ ($0 \le n \leq 10^{18}$) — the number of Shiro's friends. The circular pizza has to be sliced into $n + 1$ pieces.
-----Output-----
A single integer — the number of straight cuts Shiro needs.
-----Examples-----
Input
3
Output
2
Input
4
Output
5
-----Note-----
To cut the round pizza into quarters one has to make two cuts through the center with angle $90^{\circ}$ between them.
To cut the round pizza into five equal parts one has to make five cuts.
I tried it in Python, but could not do it. Can you solve it? | n = int(input())
if n == 0:
print(0)
elif n % 2 == 1:
print((n + 1) // 2)
else:
print(n + 1) | python | test | abovesol | codeparrot/apps | all |
Solve in Python:
Kicker (table football) is a board game based on football, in which players control the footballers' figures mounted on rods by using bars to get the ball into the opponent's goal. When playing two on two, one player of each team controls the goalkeeper and the full-backs (plays defence), the other player controls the half-backs and forwards (plays attack).
Two teams of company Q decided to battle each other. Let's enumerate players from both teams by integers from 1 to 4. The first and second player play in the first team, the third and the fourth one play in the second team. For each of the four players we know their game skills in defence and attack. The defence skill of the i-th player is a_{i}, the attack skill is b_{i}.
Before the game, the teams determine how they will play. First the players of the first team decide who will play in the attack, and who will play in the defence. Then the second team players do the same, based on the choice of their opponents.
We will define a team's defence as the defence skill of player of the team who plays defence. Similarly, a team's attack is the attack skill of the player of the team who plays attack. We assume that one team is guaranteed to beat the other one, if its defence is strictly greater than the opponent's attack and its attack is strictly greater than the opponent's defence.
The teams of company Q know each other's strengths and therefore arrange their teams optimally. Identify the team that is guaranteed to win (if both teams act optimally) or tell that there is no such team.
-----Input-----
The input contain the players' description in four lines. The i-th line contains two space-separated integers a_{i} and b_{i} (1 ≤ a_{i}, b_{i} ≤ 100) — the defence and the attack skill of the i-th player, correspondingly.
-----Output-----
If the first team can win, print phrase "Team 1" (without the quotes), if the second team can win, print phrase "Team 2" (without the quotes). If no of the teams can definitely win, print "Draw" (without the... | team1, team2 = (lambda t : [[list(map(int, input().split())) for x in range(2)] for y in range(2)])('input')
if (lambda t1, t2 : any(all(t1[x][0] > t2[y][1] and t1[1 - x][1] > t2[1 - y][0] for y in range(2)) for x in range(2)))(team1, team2):
print('Team 1')
elif (lambda t1, t2 : all(any(t2[y][0] > t1[x][1] and t2[1 - y][1] > t1[1 - x][0] for y in range(2)) for x in range(2)))(team1, team2):
print('Team 2')
else:
print('Draw') | python | test | qsol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/1142/C:
Recently Vasya learned that, given two points with different $x$ coordinates, you can draw through them exactly one parabola with equation of type $y = x^2 + bx + c$, where $b$ and $c$ are reals. Let's call such a parabola an $U$-shaped one.
Vasya drew several distinct points with integer coordinates on a plane and then drew an $U$-shaped parabola through each pair of the points that have different $x$ coordinates. The picture became somewhat messy, but Vasya still wants to count how many of the parabolas drawn don't have any drawn point inside their internal area. Help Vasya.
The internal area of an $U$-shaped parabola is the part of the plane that lies strictly above the parabola when the $y$ axis is directed upwards.
-----Input-----
The first line contains a single integer $n$ ($1 \le n \le 100\,000$) — the number of points.
The next $n$ lines describe the points, the $i$-th of them contains two integers $x_i$ and $y_i$ — the coordinates of the $i$-th point. It is guaranteed that all points are distinct and that the coordinates do not exceed $10^6$ by absolute value.
-----Output-----
In the only line print a single integer — the number of $U$-shaped parabolas that pass through at least two of the given points and do not contain any of the given points inside their internal area (excluding the parabola itself).
-----Examples-----
Input
3
-1 0
0 2
1 0
Output
2
Input
5
1 0
1 -1
0 -1
-1 0
-1 -1
Output
1
-----Note-----
On the pictures below all $U$-shaped parabolas that pass through at least two given points are drawn for each of the examples. The $U$-shaped parabolas that do not have any given point inside their internal area are drawn in red. [Image] The first example.
[Image] The second example.
I tried it in Python, but could not do it. Can you solve it? | n = int(input())
rows = [input().split() for _ in range(n)]
rows = [(int(x),int(y)) for x,y in rows]
points = {}
for x,y in rows:
if x in points:
points[x] = max(y, points[x])
else:
points[x] = y
points = sorted(points.items(),key=lambda point: point[0])
def above(p,p1,p2):
"""
x1 < x2
y1 = x1^2 + bx1 + c
y2 = x2^2 + bx2 + c
y >? x^2 + bx + c
y2 - y1 = x2^2 - x1^2 + bx2 - bx1
b = (y2 - y1 - x2^2 + x1^2) / (x2 - x1)
b * (x2 - x1) = y2 - y1 - x2^2 + x1^2
c = y1 - x1^2 - bx1
c * (x2 - x1) = (y1 - x1^2) * (x2 - x1) - x1 * (y2 - y1 - x2^2 + x1^2)
y * (x2 - x1) >? (x^2 + bx + c) * (x2 - x1)
y * (x2 - x1) >?
x^2 * (x2 - x1)
+ x * (y2 - y1 - x2^2 + x1^2)
+ (y1 - x1^2) * (x2 - x1) - x1 * (y2 - y1 - x2^2 + x1^2)
"""
x,y = p
x1,y1 = p1
x2,y2 = p2
x_2 = x**2
x12 = x1**2
x22 = x2**2
x2_x1 = x2 - x1
eq_b = y2 - y1 - x22 + x12
term_y = y * x2_x1
term_x2 = x_2 * x2_x1
term_x = x * eq_b
term_c = (y1 - x12) * x2_x1 - (x1 * eq_b)
return term_y >= term_x2 + term_x + term_c
#print(above(points[2],points[0],points[1]))
Us = []
for i, p in enumerate(points):
while len(Us) >= 2:
p1, p2 = Us[-2:]
if above(p,p1,p2):
Us.pop()
else:
break
Us.append(p)
out = len(Us) - 1
print(out) | python | train | abovesol | codeparrot/apps | all |
I found an interesting problem on https://www.codewars.com/kata/5a045fee46d843effa000070:
The aim of the kata is to decompose `n!` (factorial n) into its prime factors.
Examples:
```
n = 12; decomp(12) -> "2^10 * 3^5 * 5^2 * 7 * 11"
since 12! is divisible by 2 ten times, by 3 five times, by 5 two times and by 7 and 11 only once.
n = 22; decomp(22) -> "2^19 * 3^9 * 5^4 * 7^3 * 11^2 * 13 * 17 * 19"
n = 25; decomp(25) -> 2^22 * 3^10 * 5^6 * 7^3 * 11^2 * 13 * 17 * 19 * 23
```
Prime numbers should be in increasing order. When the exponent of a prime is 1 don't put the exponent.
Notes
- the function is `decomp(n)` and should return the decomposition of `n!` into its prime factors in increasing order of the primes, as a string.
- factorial can be a very big number (`4000! has 12674 digits`, n will go from 300 to 4000).
- In Fortran - as in any other language - the returned string is not permitted to contain any redundant trailing whitespace: you can use `dynamically allocated character strings`.
I tried it in Python, but could not do it. Can you solve it? | def primes(n):
primes = [2]
for i in range(3,n+1):
if all(i%p!= 0 for p in primes) == True:
primes.append(i)
return(primes)
def decomp(n):
prim = primes(n)
factors = {}
for i in range(2, n+1):
if i in prim:
factors[i] = 1
else:
for p in prim:
while i%p == 0:
factors[p] += 1
i /= p
if i == 1:
break
res = ''
for x, y in factors.items():
res += '{0}^{1} * '.format(x,y) if y != 1 else '{0} * '.format(x)
return(res[:-3]) | python | train | abovesol | codeparrot/apps | all |
Solve in Python:
Do you remember how Kai constructed the word "eternity" using pieces of ice as components?
Little Sheldon plays with pieces of ice, each piece has exactly one digit between 0 and 9. He wants to construct his favourite number t. He realized that digits 6 and 9 are very similar, so he can rotate piece of ice with 6 to use as 9 (and vice versa). Similary, 2 and 5 work the same. There is no other pair of digits with similar effect. He called this effect "Digital Mimicry".
Sheldon favourite number is t. He wants to have as many instances of t as possible. How many instances he can construct using the given sequence of ice pieces. He can use any piece at most once.
-----Input-----
The first line contains integer t (1 ≤ t ≤ 10000). The second line contains the sequence of digits on the pieces. The length of line is equal to the number of pieces and between 1 and 200, inclusive. It contains digits between 0 and 9.
-----Output-----
Print the required number of instances.
-----Examples-----
Input
42
23454
Output
2
Input
169
12118999
Output
1
-----Note-----
This problem contains very weak pretests. | t = input().replace('5', '2').replace('9', '6')
s = input().replace('5', '2').replace('9', '6')
res = 10 ** 100
for i in t:
res = min(res, s.count(i) // t.count(i))
print(res) | python | test | qsol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/1311/A:
You are given two positive integers $a$ and $b$.
In one move, you can change $a$ in the following way:
Choose any positive odd integer $x$ ($x > 0$) and replace $a$ with $a+x$; choose any positive even integer $y$ ($y > 0$) and replace $a$ with $a-y$.
You can perform as many such operations as you want. You can choose the same numbers $x$ and $y$ in different moves.
Your task is to find the minimum number of moves required to obtain $b$ from $a$. It is guaranteed that you can always obtain $b$ from $a$.
You have to answer $t$ independent test cases.
-----Input-----
The first line of the input contains one integer $t$ ($1 \le t \le 10^4$) — the number of test cases.
Then $t$ test cases follow. Each test case is given as two space-separated integers $a$ and $b$ ($1 \le a, b \le 10^9$).
-----Output-----
For each test case, print the answer — the minimum number of moves required to obtain $b$ from $a$ if you can perform any number of moves described in the problem statement. It is guaranteed that you can always obtain $b$ from $a$.
-----Example-----
Input
5
2 3
10 10
2 4
7 4
9 3
Output
1
0
2
2
1
-----Note-----
In the first test case, you can just add $1$.
In the second test case, you don't need to do anything.
In the third test case, you can add $1$ two times.
In the fourth test case, you can subtract $4$ and add $1$.
In the fifth test case, you can just subtract $6$.
I tried it in Python, but could not do it. Can you solve it? | t = int(input())
for i in range(t):
line = input()
[a, b] = [int(x) for x in line.split(' ')]
if a == b:
print(0)
if a > b:
if a % 2 == b % 2:
print(1)
else:
print(2)
elif a < b:
if a % 2 == b % 2:
print(2)
else:
print(1) | python | test | abovesol | codeparrot/apps | all |
Solve in Python:
You are given an integer $n$. In one move, you can either multiply $n$ by two or divide $n$ by $6$ (if it is divisible by $6$ without the remainder).
Your task is to find the minimum number of moves needed to obtain $1$ from $n$ or determine if it's impossible to do that.
You have to answer $t$ independent test cases.
-----Input-----
The first line of the input contains one integer $t$ ($1 \le t \le 2 \cdot 10^4$) — the number of test cases. Then $t$ test cases follow.
The only line of the test case contains one integer $n$ ($1 \le n \le 10^9$).
-----Output-----
For each test case, print the answer — the minimum number of moves needed to obtain $1$ from $n$ if it's possible to do that or -1 if it's impossible to obtain $1$ from $n$.
-----Example-----
Input
7
1
2
3
12
12345
15116544
387420489
Output
0
-1
2
-1
-1
12
36
-----Note-----
Consider the sixth test case of the example. The answer can be obtained by the following sequence of moves from the given integer $15116544$:
Divide by $6$ and get $2519424$; divide by $6$ and get $419904$; divide by $6$ and get $69984$; divide by $6$ and get $11664$; multiply by $2$ and get $23328$; divide by $6$ and get $3888$; divide by $6$ and get $648$; divide by $6$ and get $108$; multiply by $2$ and get $216$; divide by $6$ and get $36$; divide by $6$ and get $6$; divide by $6$ and get $1$. | for testcase in range(int(input())):
n = int(input())
cnt2, cnt3 = 0, 0
while n % 2 == 0:
n //= 2
cnt2 += 1
while n % 3 == 0:
n //= 3
cnt3 += 1
if n > 1 or cnt3 < cnt2:
print(-1)
continue
print(2 * cnt3 - cnt2) | python | test | qsol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/879/A:
It seems that Borya is seriously sick. He is going visit n doctors to find out the exact diagnosis. Each of the doctors needs the information about all previous visits, so Borya has to visit them in the prescribed order (i.e. Borya should first visit doctor 1, then doctor 2, then doctor 3 and so on). Borya will get the information about his health from the last doctor.
Doctors have a strange working schedule. The doctor i goes to work on the s_{i}-th day and works every d_{i} day. So, he works on days s_{i}, s_{i} + d_{i}, s_{i} + 2d_{i}, ....
The doctor's appointment takes quite a long time, so Borya can not see more than one doctor per day. What is the minimum time he needs to visit all doctors?
-----Input-----
First line contains an integer n — number of doctors (1 ≤ n ≤ 1000).
Next n lines contain two numbers s_{i} and d_{i} (1 ≤ s_{i}, d_{i} ≤ 1000).
-----Output-----
Output a single integer — the minimum day at which Borya can visit the last doctor.
-----Examples-----
Input
3
2 2
1 2
2 2
Output
4
Input
2
10 1
6 5
Output
11
-----Note-----
In the first sample case, Borya can visit all doctors on days 2, 3 and 4.
In the second sample case, Borya can visit all doctors on days 10 and 11.
I tried it in Python, but could not do it. Can you solve it? | n = int(input())
ans = 0
c = 1
import math
for i in range(n):
s,d = map(int, input().split())
p = int(math.ceil(max(0, c - s) / d))
c = s + p*d + 1
print(c-1) | python | test | abovesol | codeparrot/apps | all |
I found an interesting problem on https://www.codewars.com/kata/51e04f6b544cf3f6550000c1:
Let's pretend your company just hired your friend from college and paid you a referral bonus. Awesome! To celebrate, you're taking your team out to the terrible dive bar next door and using the referral bonus to buy, and build, the largest three-dimensional beer can pyramid you can. And then probably drink those beers, because let's pretend it's Friday too.
A beer can pyramid will square the number of cans in each level - 1 can in the top level, 4 in the second, 9 in the next, 16, 25...
Complete the beeramid function to return the number of **complete** levels of a beer can pyramid you can make, given the parameters of:
1) your referral bonus, and
2) the price of a beer can
For example:
I tried it in Python, but could not do it. Can you solve it? | from itertools import count
def beeramid(bonus, price):
bonus = max(bonus,0)
n = bonus//price
return next(x for x in count(int((n*3)**(1/3)+1),-1) if x*(x+1)*(2*x+1)//6 <= n) | python | train | abovesol | codeparrot/apps | all |
I found an interesting problem on https://www.codewars.com/kata/558db3ca718883bd17000031:
< PREVIOUS KATA
NEXT KATA >
## Task:
You have to write a function `pattern` which returns the following Pattern(See Examples) upto desired number of rows.
* Note:```Returning``` the pattern is not the same as ```Printing``` the pattern.
### Parameters:
pattern( n , x , y );
^ ^ ^
| | |
Term upto which Number of times Number of times
Basic Pattern Basic Pattern Basic Pattern
should be should be should be
created repeated repeated
horizontally vertically
* Note: `Basic Pattern` means what we created in Complete The Pattern #12
## Rules/Note:
* The pattern should be created using only unit digits.
* If `n < 1` then it should return "" i.e. empty string.
* If `x <= 1` then the basic pattern should not be repeated horizontally.
* If `y <= 1` then the basic pattern should not be repeated vertically.
* `The length of each line is same`, and is equal to the length of longest line in the pattern.
* Range of Parameters (for the sake of CW Compiler) :
+ `n ∈ (-∞,25]`
+ `x ∈ (-∞,10]`
+ `y ∈ (-∞,10]`
* If only two arguments are passed then the function `pattern` should run as if `y <= 1`.
* If only one argument is passed then the function `pattern` should run as if `x <= 1` & `y <= 1`.
* The function `pattern` should work when extra arguments are passed, by ignoring the extra arguments.
## Examples:
* Having Three Arguments-
+ pattern(4,3,2):
1 1 1 1
2 2 2 2 2 2
3 3 3 3 3 3
4 4 4
3 3 3 3 3 3
2 2 2 2 2 2
1 1 1 1
2 2 2 2 2 2
3 3 3 3 3 3
4 4 4
3 3 3 3 3 3
2 2 2 2 2 2
1 1 1 ...
I tried it in Python, but could not do it. Can you solve it? | def pattern(n,m=1,l=1,*args):
if n < 1:return ''
m = max(1,m)
li, mid, r = ['1'+' '*((n*2-1)-2)+'1'+(' '*((n*2-1)-2)+'1')*(m-1)],1,(n*2-1)-2-2
for i in range(2, n + 1):
li.append(' '*(i-1)+f"{' '*mid}".join([str(i%10)+' '*r+(str(i%10)if i!=n else '')for o in range(m)])+' '*(i-1))
r -= 2 ; mid += 2
li = li + li[:-1][::-1]
well = li.copy()
return "\n".join(li + ["\n".join(well[1:]) for i in range(l-1)]) | python | train | abovesol | codeparrot/apps | all |
I found an interesting problem on https://www.codechef.com/LOCAPR16/problems/BLTOUR:
In Byteland there are N cities, numbered 1 through N. Some pairs of cities are connected by bi-directional roads in such a way that starting from any one city you can visit all other cities either directly or indirectly.
Chef is currently at city A and wants to visit all other cities in Byteland. Chef can only move according to following rule.
If Chef is at city A then he continues to move from city A to city B, city B to city C (provided A is directly connected to B, B is directly connected to C) and so on unless there are no more cities leading from current city.
If so he jumps back to previous city and repeat the same tour with other cities leading from it which are not visited. Chef repeat this step unless all cities are not visited.
Help Chef to count number of ways in which he can visit all other cities . As this number can be large print it modulo 109+7
-----Input-----
- The first line of the input contains an integer T denoting the number of test cases. The description of T test cases follows.
- The first line of each test case contains a single integer N denoting the number of cities in Byteland.
- Next N-1 lines contain two space-separated integers u and v denoting there is bi-directional road between city numbered u and v.
- Next line contains a single integer A denoting the city number where Chef is present.
-----Output-----
- For each test case, output a single line containing number of ways in which Chef can visit all cities modulo 109+7.
-----Constraints-----
- 1 ≤ T ≤ 5
- 1 ≤ N ≤ 105
- 1 ≤ A ≤ N
-----Subtasks-----
Subtask #1 : (10 points)
- 1 ≤ N ≤ 5
Subtask #2 : (30 points)
- 1 ≤ N ≤ 100
Subtask #3 : (60 points)
- 1 ≤ N ≤ 105
-----Example-----
Input:
2
3
1 2
1 3
1
5
1 2
1 3
2 4
2 5
1
Output:
2
4
-----Explanation-----
Example case 1. Chef can visit cities in two ways according to the problem: 1-2-3 and 1-3-2
Example case 1. Chef can visit cities in four ways according to the problem:
1-2-4-5-3
1-2-5-4-3
1-3-2-4-5
1-3-2-5-4
I tried it in Python, but could not do it. Can you solve it? | import sys
sys.setrecursionlimit(10**8)
MOD = 10**9+7
fac = [0]*(10**5+1)
def pre() :
fac[0] = 1
for i in range(1,10**5+1) :
fac[i] = fac[i-1]*i
fac[i] = fac[i]%MOD
def dfs(gp , vertex , visited , deg , ans) :
visited[vertex] = 1
stack = []
stack.append(vertex)
while len(stack)>0 :
vertex = stack.pop()
ans = ans%MOD * fac[deg[vertex]]%MOD
ans %= MOD
for i in gp[vertex] :
if not visited[i] :
visited[i] = 1
if vertex in gp[i] :
deg[i] -= 1
stack.append(i)
return ans%MOD
pre()
for __ in range(eval(input())) :
n = eval(input())
deg = [0]*(n+1)
st = [[] for __ in range(n+1)]
for _ in range(n-1) :
a , b = list(map(int,sys.stdin.readline().split()))
st[a].append(b)
st[b].append(a)
deg[a] += 1
deg[b] += 1
k = eval(input())
visited = [0]*(n+1)
print(dfs(st ,k,visited,deg , 1)%MOD) | python | train | abovesol | codeparrot/apps | all |
Solve in Python:
Little girl Susie accidentally found her elder brother's notebook. She has many things to do, more important than solving problems, but she found this problem too interesting, so she wanted to know its solution and decided to ask you about it. So, the problem statement is as follows.
Let's assume that we are given a connected weighted undirected graph G = (V, E) (here V is the set of vertices, E is the set of edges). The shortest-path tree from vertex u is such graph G_1 = (V, E_1) that is a tree with the set of edges E_1 that is the subset of the set of edges of the initial graph E, and the lengths of the shortest paths from u to any vertex to G and to G_1 are the same.
You are given a connected weighted undirected graph G and vertex u. Your task is to find the shortest-path tree of the given graph from vertex u, the total weight of whose edges is minimum possible.
-----Input-----
The first line contains two numbers, n and m (1 ≤ n ≤ 3·10^5, 0 ≤ m ≤ 3·10^5) — the number of vertices and edges of the graph, respectively.
Next m lines contain three integers each, representing an edge — u_{i}, v_{i}, w_{i} — the numbers of vertices connected by an edge and the weight of the edge (u_{i} ≠ v_{i}, 1 ≤ w_{i} ≤ 10^9). It is guaranteed that graph is connected and that there is no more than one edge between any pair of vertices.
The last line of the input contains integer u (1 ≤ u ≤ n) — the number of the start vertex.
-----Output-----
In the first line print the minimum total weight of the edges of the tree.
In the next line print the indices of the edges that are included in the tree, separated by spaces. The edges are numbered starting from 1 in the order they follow in the input. You may print the numbers of the edges in any order.
If there are multiple answers, print any of them.
-----Examples-----
Input
3 3
1 2 1
2 3 1
1 3 2
3
Output
2
1 2
Input
4 4
1 2 1
2 3 1
3 4 1
4 1 2
4
Output
4
2 3 4
-----Note-----
In the first sample there are two possible shortest path trees:
with edges 1 – 3... | import heapq
n,m = list(map(int, input().split()))
g = [[] for i in range(n)]
for i in range(1,m+1):
x,y,z = list(map(int, input().split()))
x -= 1
y -= 1
g[x].append((y,z,i))
g[y].append((x,z,i))
v = int(input())-1
q = [(0,0,v,0)]
s = []
u = [0] * n
a = 0
while len(q) :
d,l,x,e = heapq.heappop(q)
if not u[x]:
u[x] = 1
s.append(str(e))
a += l
for i,k,f in g[x]:
if not u[i]:
heapq.heappush(q, (d+k,k,i,f))
print(a)
print(' '.join(s[1:])) | python | test | qsol | codeparrot/apps | all |
Solve in Python:
# Task
You are given an array of integers `a` and a non-negative number of operations `k`, applied to the array. Each operation consists of two parts:
```
find the maximum element value of the array;
replace each element a[i] with (maximum element value - a[i]).```
How will the array look like after `k` such operations?
# Example
For `a = [-4, 0, -1, 0]` and `k = 2`, the output should be `[0, 4, 3, 4]`.
```
initial array: [-4, 0, -1, 0]
1st operation:
find the maximum value --> 0
replace each element: --> [(0 - -4), (0 - 0), (0 - -1), (0 - 0)]
--> [4, 0, 1, 0]
2nd operation:
find the maximum value --> 4
replace each element: --> [(4 - 4), (4 - 0), (4 - 1), (4 - 0)]
--> [0, 4, 3, 4]
```
For `a = [0, -1, 0, 0, -1, -1, -1, -1, 1, -1]` and `k = 1`,
the output should be `[1, 2, 1, 1, 2, 2, 2, 2, 0, 2]`.
```
initial array: [0, -1, 0, 0, -1, -1, -1, -1, 1, -1]
1st operation:
find the maximum value --> 1
replace each element: -->
[(1-0),(1- -1),(1-0),(1-0),(1- -1),(1- -1),(1- -1),(1- -1),(1-1),(1- -1)]
--> [1, 2, 1, 1, 2, 2, 2, 2, 0, 2]
```
# Input/Output
- `[input]` integer array a
The initial array.
Constraints:
`1 <= a.length <= 100`
`-100 <= a[i] <= 100`
- `[input]` integer `k`
non-negative number of operations.
Constraints: `0 <= k <= 100000`
- [output] an integer array
The array after `k` operations. | def array_operations(a, n):
li = []
for i in range(n):
m = max(a)
a = [m-i for i in a]
if a in li:
if not n & 1 : return li[-1]
return a
li.append(a)
return a | python | train | qsol | codeparrot/apps | all |
Solve in Python:
Complete the function that determines the score of a hand in the card game [Blackjack](https://en.wikipedia.org/wiki/Blackjack) (aka 21).
The function receives an array of strings that represent each card in the hand (`"2"`, `"3",` ..., `"10"`, `"J"`, `"Q"`, `"K"` or `"A"`) and should return the score of the hand (integer).
~~~if:c
Note: in C the function receives a character array with the card `10` represented by the character `T`.
~~~
### Scoring rules:
Number cards count as their face value (2 through 10). Jack, Queen and King count as 10. An Ace can be counted as either 1 or 11.
Return the highest score of the cards that is less than or equal to 21. If there is no score less than or equal to 21 return the smallest score more than 21.
## Examples
```
["A"] ==> 11
["A", "J"] ==> 21
["A", "10", "A"] ==> 12
["5", "3", "7"] ==> 15
["5", "4", "3", "2", "A", "K"] ==> 25
``` | def score_hand(cards):
aces = [i for i in cards if i == 'A']
cards = list(filter(lambda x: x is not 'A', cards))
cards.extend(aces)
total = 0
for i, card in enumerate(cards):
if card in ['J', 'Q', 'K']:
total += 10
elif card is 'A':
total += 11 if 11 <= (21 - total) and "".join(cards).rindex('A') == i else 1
else:
total += int(card)
return total | python | train | qsol | codeparrot/apps | all |
Solve in Python:
## Decode the diagonal.
Given a grid of characters. Output a decoded message as a string.
Input
```
H Z R R Q
D I F C A E A !
G H T E L A E
L M N H P R F
X Z R P E
```
Output
`HITHERE!` (diagonally down right `↘` and diagonally up right `↗` if you can't go further).
The message ends when there is no space at the right up or down diagonal.
To make things even clearer: the same example, but in a simplified view
```
H _ _ _ _
_ I _ _ _ _ _ !
_ _ T _ _ _ E
_ _ _ H _ R _
_ _ _ _ E
``` | def get_diagonale_code(grid: str) -> str:
flag=True
temp=grid.split("\n")
for i,j in enumerate(temp):
temp[i]=j.split()
res=""
x=0
y=0
while True:
try:
res+=temp[y][x]
if y==len(temp)-1:
flag=False
elif y==0 and not flag:
flag=True
y+=1 if flag else -1
x+=1
except:
return res | python | train | qsol | codeparrot/apps | all |
Solve in Python:
Navnit is a college student and there are $N$ students in his college .Students are numbered from $1$ to $N$.
You are given $M$ facts that "Student $A_i$ and $B_i$".The same fact can be given multiple times .If $A_i$ is a friend of $B_i$ ,then $B_i$ is also a friend of $A_i$ . If $A_i$ is a friend of $B_i$ and $B_i$ is a friend of $C_i$ then $A_i$ is also a friend of $C_i$.
Find number of ways in which two students can be selected in such a way that they are not friends.
-----Input:-----
- First line will contain two integers $N$ and $M$.
- Then $M$ lines follow. Each line contains two integers $A_i$ and $B_i$ denoting the students who are friends.
-----Output:-----
For each testcase, output the number of ways in which two students can be selected in such a way that they are friends.
-----Constraints-----
- $2 \leq N \leq 200000$
- $0 \leq M \leq 200000$
- $1 \leq A_i,B_i \leq N$
-----Sample Input:-----
5 3
1 2
3 4
1 5
-----Sample Output:-----
6
-----EXPLANATION:-----
Groups of friend are $[1,2,5]$ and $[3,4]$.Hence the answer is 3 X 2 =6. | # cook your dish here
from collections import defaultdict
d=defaultdict(list)
def dfs(i):
p=0
nonlocal v
e=[i]
while(e!=[]):
p+=1
x=e.pop(0)
v[x]=1
for i in d[x]:
if v[i]==-1:
v[i]=1
e.append(i)
return p
n,m=list(map(int,input().split()))
for i in range(n+1):
d[i]=[]
for _ in range(m):
a,b=list(map(int,input().split()))
d[a].append(b)
d[b].append(a)
v=[]
for i in range(n+1):
v.append(-1)
c=0
p=[]
for i in range(1,n+1):
if v[i]==-1:
c+=1
p.append(dfs(i))
an=0
s=0
for i in range(c):
s+=p[i]
an+=p[i]*(n-s)
print(an) | python | train | qsol | codeparrot/apps | all |
I found an interesting problem on https://www.codechef.com/problems/UWCOI20B:
Using his tip-top physique, Kim has now climbed up the mountain where the base is located. Kim has found the door to the (supposedly) super secret base. Well, it is super secret, but obviously no match for Kim's talents.
The door is guarded by a row of $N$ buttons. Every button has a single number $A_i$ written on it. Surprisingly, more than one button can have the same number on it. Kim recognises this as Soum's VerySafe door, for which you need to press two buttons to enter the password. More importantly, the sum of the two numbers on the buttons you press must be odd. Kim can obviously break through this door easily, but he also wants to know how many different pairs of buttons he can pick in order to break through the door.
Can you help Kim find the number of different pairs of buttons he can press to break through the door?
Note: Two pairs are considered different if any of the buttons pressed in the pair is different (by position of the button pressed). Two pairs are not considered different if they're the same position of buttons, pressed in a different order.
Please refer to the samples for more details.
-----Input:-----
- The first line contains a single integer $T$, representing the number of testcases. $2T$ lines follow, 2 for each testcase.
- For each testcase, the first line contains a single integer $N$, the number of buttons.
- The second line of each testcase contains $N$ space-separated integers, $A_1, A_2, \ldots, A_N$, representing the numbers written on each button.
-----Output:-----
Print a single number, $K$, representing the number of pairs of buttons in $A$ which have an odd sum.
-----Subtasks-----
For all subtasks, $1 \leq T \leq 10$, $1 \leq N \leq 100000$, and $1 \leq A_i \leq 100000$ for all $A_i$.
Subtask 1 [15 points] : $N \leq 2$, There are at most 2 buttons
Subtask 2 [45 points] : $N \leq 1000$, There are at most 1000 buttons
Subtask 3 [40 points] : No additional constraints.
-----Sample Input:-----
3
4
3 5 3 4
2
5 7
1
4
-----Sample...
I tried it in Python, but could not do it. Can you solve it? | # cook your dish here
t = int(input())
while t>0:
n = int(input())
a = list(map(int, input().split()))
cnt = 0
for i in range(n):
if a[i]%2!=0:
cnt = cnt + 1
ans = n - cnt
print(ans*cnt)
t = t-1 | python | train | abovesol | codeparrot/apps | all |
Solve in Python:
Given two numbers and an arithmetic operator (the name of it, as a string), return the result of the two numbers having that operator used on them.
```a``` and ```b``` will both be positive integers, and ```a``` will always be the first number in the operation, and ```b``` always the second.
The four operators are "add", "subtract", "divide", "multiply".
A few examples:
``` javascript
ArithmeticFunction.arithmetic(5, 2, "add") => returns 7
ArithmeticFunction.arithmetic(5, 2, "subtract") => returns 3
ArithmeticFunction.arithmetic(5, 2, "multiply") => returns 10
ArithmeticFunction.arithmetic(5, 2, "divide") => returns 2
```
Try to do it without using if statements! | def arithmetic(a, b, operator):
opd = {'add': a+b,'subtract': a-b,'multiply': a*b,'divide': a/b}
return opd[operator] | python | train | qsol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/776/E:
The Holmes children are fighting over who amongst them is the cleverest.
Mycroft asked Sherlock and Eurus to find value of f(n), where f(1) = 1 and for n ≥ 2, f(n) is the number of distinct ordered positive integer pairs (x, y) that satisfy x + y = n and gcd(x, y) = 1. The integer gcd(a, b) is the greatest common divisor of a and b.
Sherlock said that solving this was child's play and asked Mycroft to instead get the value of $g(n) = \sum_{d|n} f(n / d)$. Summation is done over all positive integers d that divide n.
Eurus was quietly observing all this and finally came up with her problem to astonish both Sherlock and Mycroft.
She defined a k-composite function F_{k}(n) recursively as follows:
$F_{k}(n) = \left\{\begin{array}{ll}{f(g(n)),} & {\text{for} k = 1} \\{g(F_{k - 1}(n)),} & {\text{for} k > 1 \text{and} k \operatorname{mod} 2 = 0} \\{f(F_{k - 1}(n)),} & {\text{for} k > 1 \text{and} k \operatorname{mod} 2 = 1} \end{array} \right.$
She wants them to tell the value of F_{k}(n) modulo 1000000007.
-----Input-----
A single line of input contains two space separated integers n (1 ≤ n ≤ 10^12) and k (1 ≤ k ≤ 10^12) indicating that Eurus asks Sherlock and Mycroft to find the value of F_{k}(n) modulo 1000000007.
-----Output-----
Output a single integer — the value of F_{k}(n) modulo 1000000007.
-----Examples-----
Input
7 1
Output
6
Input
10 2
Output
4
-----Note-----
In the first case, there are 6 distinct ordered pairs (1, 6), (2, 5), (3, 4), (4, 3), (5, 2) and (6, 1) satisfying x + y = 7 and gcd(x, y) = 1. Hence, f(7) = 6. So, F_1(7) = f(g(7)) = f(f(7) + f(1)) = f(6 + 1) = f(7) = 6.
I tried it in Python, but could not do it. Can you solve it? | MOD = 1000000007
def phi(n):
res = n
for i in range(2,int(n**(0.5)+1)):
if n % i == 0:
while n % i == 0:
n = n//i
res -= res//i
if n > 1:
res -= res//n
return res
n,k = list(map(int,input().split()))
k = (k+1)//2
ans = n
for _ in range(k):
if ans > 1:
ans = phi(ans)
else:
break
print(ans % MOD) | python | test | abovesol | codeparrot/apps | all |
Solve in Python:
In this simple exercise, you will build a program that takes a value, `integer `, and returns a list of its multiples up to another value, `limit `. If `limit` is a multiple of ```integer```, it should be included as well. There will only ever be positive integers passed into the function, not consisting of 0. The limit will always be higher than the base.
For example, if the parameters passed are `(2, 6)`, the function should return `[2, 4, 6]` as 2, 4, and 6 are the multiples of 2 up to 6.
If you can, try writing it in only one line of code. | find_multiples = lambda a, b: list(range(a, b + 1, a)) | python | train | qsol | codeparrot/apps | all |
Solve in Python:
Consider the following numbers (where `n!` is `factorial(n)`):
```
u1 = (1 / 1!) * (1!)
u2 = (1 / 2!) * (1! + 2!)
u3 = (1 / 3!) * (1! + 2! + 3!)
...
un = (1 / n!) * (1! + 2! + 3! + ... + n!)
```
Which will win: `1 / n!` or `(1! + 2! + 3! + ... + n!)`?
Are these numbers going to `0` because of `1/n!` or to infinity due
to the sum of factorials or to another number?
## Task
Calculate `(1 / n!) * (1! + 2! + 3! + ... + n!)`
for a given `n`, where `n` is an integer greater or equal to `1`.
To avoid discussions about rounding, return the result **truncated** to 6 decimal places, for example:
```
1.0000989217538616 will be truncated to 1.000098
1.2125000000000001 will be truncated to 1.2125
```
## Remark
Keep in mind that factorials grow rather rapidly, and you need to handle large inputs.
## Hint
You could try to simplify the expression. | # truncate to 6 decimals
def trunc(n):
return float(str(n)[:8])
def going(n):
sum = 1
fact = 1.0
for i in range(1,n):
fact = fact/(n-i+1)
sum += fact
return trunc(sum) | python | train | qsol | codeparrot/apps | all |
Solve in Python:
You get a new job working for Eggman Movers. Your first task is to write a method that will allow the admin staff to enter a person’s name and return what that person's role is in the company.
You will be given an array of object literals holding the current employees of the company. You code must find the employee with the matching firstName and lastName and then return the role for that employee or if no employee is not found it should return "Does not work here!"
The array is preloaded and can be referenced using the variable `employees` (`$employees` in Ruby). It uses the following structure.
```python
employees = [ {'first_name': "Dipper", 'last_name': "Pines", 'role': "Boss"}, ...... ]
```
There are no duplicate names in the array and the name passed in will be a single string with a space between the first and last name i.e. Jane Doe or just a name. | employees = [{'first_name': 'Ollie', 'last_name': 'Hepburn', 'role': 'Boss'}, {'first_name': 'Morty', 'last_name': 'Smith', 'role': 'Truck Driver'}, {'first_name': 'Peter', 'last_name': 'Ross', 'role': 'Warehouse Manager'}, {'first_name': 'Cal', 'last_name': 'Neil', 'role': 'Sales Assistant'}, {'first_name': 'Jesse', 'last_name': 'Saunders', 'role': 'Admin'}, {'first_name': 'Anna', 'last_name': 'Jones', 'role': 'Sales Assistant'}, {'first_name': 'Carmel', 'last_name': 'Hamm', 'role': 'Admin'}, {'first_name': 'Tori', 'last_name': 'Sparks', 'role': 'Sales Manager'}, {'first_name': 'Peter', 'last_name': 'Jones', 'role': 'Warehouse Picker'}, {'first_name': 'Mort', 'last_name': 'Smith', 'role': 'Warehouse Picker'}, {'first_name': 'Anna', 'last_name': 'Bell', 'role': 'Admin'}, {'first_name': 'Jewel', 'last_name': 'Bell', 'role': 'Receptionist'}, {'first_name': 'Colin', 'last_name': 'Brown', 'role': 'Trainee'}]
def find_employees_role(name):
return next(
(d['role'] for d in employees if '{0[first_name]} {0[last_name]}'.format(d) == name),
'Does not work here!'
) | python | train | qsol | codeparrot/apps | all |
I found an interesting problem on https://www.hackerrank.com/challenges/list-comprehensions/problem:
=====Problem Statement=====
Let's learn about list comprehensions! You are given three integers x, y and z representing the dimensions of a cuboid along with an integer n. Print a list of all possible coordinates given by (i,j,k) on a 3D grid where the sum of i+j+k is not equal to n. Here, 0≤i≤x;0≤j≤y;0≤k≤z. Please use list comprehensions rather than multiple loops, as a learning exercise.
=====Example=====
x = 1
y = 1
z = 2
n = 3
All permutations of [i,j,k] are:
[[0,0,0],[0,0,1],[0,0,2],[0,1,0],[0,1,1],[0,1,2],[1,0,0],[1,0,1],[1,0,2],[1,1,0],[1,1,1],[1,1,2]]
Print an array of the elements that do not sum to n = 3
[[0,0,0],[0,0,1],[0,0,2],[0,1,0],[0,1,1],[1,0,0],[1,0,1],[1,1,0],[1,1,2]]
=====Input Format=====
Four integers x, y, z and n, each on a separate line.
=====Constraints=====
Print the list in lexographic increasing order
I tried it in Python, but could not do it. Can you solve it? | def __starting_point():
x = int(input())
y = int(input())
z = int(input())
n = int(input())
print([ [ i, j, k] for i in range(x + 1) for j in range(y + 1) for k in range(z + 1) if ( (i + j + k) != n )])
__starting_point() | python | test | abovesol | codeparrot/apps | all |
Solve in Python:
Given a positive integer `n`, return first n dgits of Thue-Morse sequence, as a string (see examples).
Thue-Morse sequence is a binary sequence with 0 as the first element. The rest of the sequece is obtained by adding the Boolean (binary) complement of a group obtained so far.
```
For example:
0
01
0110
01101001
and so on...
```
![alt](https://upload.wikimedia.org/wikipedia/commons/f/f1/Morse-Thue_sequence.gif)
Ex.:
```python
thue_morse(1); #"0"
thue_morse(2); #"01"
thue_morse(5); #"01101"
thue_morse(10): #"0110100110"
```
- You don't need to test if n is valid - it will always be a positive integer.
- `n` will be between 1 and 10000
[Thue-Morse on Wikipedia](https://en.wikipedia.org/wiki/Thue%E2%80%93Morse_sequence)
[Another kata on Thue-Morse](https://www.codewars.com/kata/simple-fun-number-106-is-thue-morse) by @myjinxin2015 | from codecs import decode
tm=b'QlpoOTFBWSZTWYSVjQkACcGIAGAAIACQEAUjUFRlVFsRLBUYVGKjKjVGJo01tbMxratRqjKjFRhU\nYJbQSyFRpCo4u5IpwoSEJKxoSA=='
for c in ('base64','bz2','utf8'): tm=decode(tm,c)
def thue_morse(n):
return tm[:n] | python | train | qsol | codeparrot/apps | all |
I found an interesting problem on https://atcoder.jp/contests/abc110/tasks/abc110_b:
Our world is one-dimensional, and ruled by two empires called Empire A and Empire B.
The capital of Empire A is located at coordinate X, and that of Empire B is located at coordinate Y.
One day, Empire A becomes inclined to put the cities at coordinates x_1, x_2, ..., x_N under its control, and Empire B becomes inclined to put the cities at coordinates y_1, y_2, ..., y_M under its control.
If there exists an integer Z that satisfies all of the following three conditions, they will come to an agreement, but otherwise war will break out.
- X < Z \leq Y
- x_1, x_2, ..., x_N < Z
- y_1, y_2, ..., y_M \geq Z
Determine if war will break out.
-----Constraints-----
- All values in input are integers.
- 1 \leq N, M \leq 100
- -100 \leq X < Y \leq 100
- -100 \leq x_i, y_i \leq 100
- x_1, x_2, ..., x_N \neq X
- x_i are all different.
- y_1, y_2, ..., y_M \neq Y
- y_i are all different.
-----Input-----
Input is given from Standard Input in the following format:
N M X Y
x_1 x_2 ... x_N
y_1 y_2 ... y_M
-----Output-----
If war will break out, print War; otherwise, print No War.
-----Sample Input-----
3 2 10 20
8 15 13
16 22
-----Sample Output-----
No War
The choice Z = 16 satisfies all of the three conditions as follows, thus they will come to an agreement.
- X = 10 < 16 \leq 20 = Y
- 8, 15, 13 < 16
- 16, 22 \geq 16
I tried it in Python, but could not do it. Can you solve it? | n,m,x,y = map(int, input().split())
xl = list(map(int, input().split()))
yl = list(map(int, input().split()))
z = 'War'
for i in range(x+1,y+1):
if max(xl) < i and i <= min(yl):
z = 'No War'
break
print(z) | python | test | abovesol | codeparrot/apps | all |
Solve in Python:
Further research on zombie thought processes yielded interesting results. As we know from the previous problem, the nervous system of a zombie consists of n brains and m brain connectors joining some pairs of brains together. It was observed that the intellectual abilities of a zombie depend mainly on the topology of its nervous system. More precisely, we define the distance between two brains u and v (1 ≤ u, v ≤ n) as the minimum number of brain connectors used when transmitting a thought between these two brains. The brain latency of a zombie is defined to be the maximum distance between any two of its brains. Researchers conjecture that the brain latency is the crucial parameter which determines how smart a given zombie is. Help them test this conjecture by writing a program to compute brain latencies of nervous systems.
In this problem you may assume that any nervous system given in the input is valid, i.e., it satisfies conditions (1) and (2) from the easy version.
-----Input-----
The first line of the input contains two space-separated integers n and m (1 ≤ n, m ≤ 100000) denoting the number of brains (which are conveniently numbered from 1 to n) and the number of brain connectors in the nervous system, respectively. In the next m lines, descriptions of brain connectors follow. Every connector is given as a pair of brains a b it connects (1 ≤ a, b ≤ n and a ≠ b).
-----Output-----
Print one number – the brain latency.
-----Examples-----
Input
4 3
1 2
1 3
1 4
Output
2
Input
5 4
1 2
2 3
3 4
3 5
Output
3 | n,m=map(int,input().split())
gr=[[] for i in range(n)]
for i in range(m):
u,v=map(int,input().split())
gr[v-1].append(u-1)
gr[u-1].append(v-1)
v=[False for i in range(n)]
s=[0]
tr={}
tr[0]=0
while s:
x=s.pop()
v[x]=True
for j in gr[x]:
if v[j]:continue
s.append(j)
tr[j]=tr[x]+1
va=0
ma=0
for j in tr.keys():
if ma<tr[j]:
ma=tr[j]
va=j
v=[False for i in range(n)]
s=[va]
tr={}
tr[va]=0
while s:
x=s.pop()
v[x]=True
for i in gr[x]:
if v[i]:continue
s.append(i)
tr[i]=tr[x]+1
print(max(tr.values())) | python | test | qsol | codeparrot/apps | all |
Solve in Python:
You are given an undirected tree of $n$ vertices.
Some vertices are colored blue, some are colored red and some are uncolored. It is guaranteed that the tree contains at least one red vertex and at least one blue vertex.
You choose an edge and remove it from the tree. Tree falls apart into two connected components. Let's call an edge nice if neither of the resulting components contain vertices of both red and blue colors.
How many nice edges are there in the given tree?
-----Input-----
The first line contains a single integer $n$ ($2 \le n \le 3 \cdot 10^5$) — the number of vertices in the tree.
The second line contains $n$ integers $a_1, a_2, \dots, a_n$ ($0 \le a_i \le 2$) — the colors of the vertices. $a_i = 1$ means that vertex $i$ is colored red, $a_i = 2$ means that vertex $i$ is colored blue and $a_i = 0$ means that vertex $i$ is uncolored.
The $i$-th of the next $n - 1$ lines contains two integers $v_i$ and $u_i$ ($1 \le v_i, u_i \le n$, $v_i \ne u_i$) — the edges of the tree. It is guaranteed that the given edges form a tree. It is guaranteed that the tree contains at least one red vertex and at least one blue vertex.
-----Output-----
Print a single integer — the number of nice edges in the given tree.
-----Examples-----
Input
5
2 0 0 1 2
1 2
2 3
2 4
2 5
Output
1
Input
5
1 0 0 0 2
1 2
2 3
3 4
4 5
Output
4
Input
3
1 1 2
2 3
1 3
Output
0
-----Note-----
Here is the tree from the first example: [Image]
The only nice edge is edge $(2, 4)$. Removing it makes the tree fall apart into components $\{4\}$ and $\{1, 2, 3, 5\}$. The first component only includes a red vertex and the second component includes blue vertices and uncolored vertices.
Here is the tree from the second example: [Image]
Every edge is nice in it.
Here is the tree from the third example: [Image]
Edge $(1, 3)$ splits the into components $\{1\}$ and $\{3, 2\}$, the latter one includes both red and blue vertex, thus the edge isn't nice. Edge $(2, 3)$ splits the into components $\{1, 3\}$ and $\{2\}$, the former... | import sys
from collections import defaultdict
n = int(input())
#n,k = [int(__) for __ in raw_input().split()]
arr = [int(__) for __ in input().split()]
sactive = set()
sactive.add(0)
nums = [0] * n
d1 = defaultdict(set)
d2 = defaultdict(set)
d = defaultdict(set)
lines = sys.stdin.readlines()
for i in range(n-1):
sactive.add(i+1)
s,f = [int(__) for __ in lines[i].strip().split()]
s -= 1
f -= 1
d[s].add(f)
d[f].add(s)
nums[f] += 1
nums[s] += 1
leaves = set()
for i in range(n):
if nums[i] == 1:
leaves.add(i)
while len(leaves):
x = leaves.pop()
if arr[x] == 0:
sactive.remove(x)
nums[x] -= 1
targ = d[x].pop()
nums[targ] -= 1
d[targ].remove(x)
if nums[targ] == 1:
leaves.add(targ)
sactive1 = sactive.copy()
for targ in d:
d1[targ] = d[targ].copy()
nums1 = nums[:]
nums2 = nums[:]
for i in range(n):
if nums1[i] == 1:
leaves.add(i)
while len(leaves):
x = leaves.pop()
if arr[x] != 1:
sactive1.remove(x)
nums1[x] -= 1
targ = d1[x].pop()
nums1[targ] -= 1
d1[targ].remove(x)
if nums1[targ] == 1:
leaves.add(targ)
sactive2 = sactive.copy()
for targ in d:
d2[targ] = d[targ].copy()
for i in range(n):
if nums2[i] == 1:
leaves.add(i)
while len(leaves):
x = leaves.pop()
if arr[x] != 2:
sactive2.remove(x)
nums2[x] -= 1
targ = d2[x].pop()
nums2[targ] -= 1
d2[targ].remove(x)
if nums2[targ] == 1:
leaves.add(targ)
if len(sactive1 & sactive2) > 0:
print(0)
else:
print(len(sactive) - len(sactive1) - len(sactive2) + 1)
#print(nums)
#print('both',sactive)
#print('1',sactive1)
#print('2',sactive2)
#print(d) | python | test | qsol | codeparrot/apps | all |
I found an interesting problem on https://www.codewars.com/kata/56c0ca8c6d88fdb61b000f06:
You're fed up about changing the version of your software manually. Instead, you will create a little script that will make it for you.
# Exercice
Create a function `nextVersion`, that will take a string in parameter, and will return a string containing the next version number.
For example:
# Rules
All numbers, except the first one, must be lower than 10: if there are, you have to set them to 0 and increment the next number in sequence.
You can assume all tests inputs to be valid.
I tried it in Python, but could not do it. Can you solve it? | def next_version(version):
c, s = version.count(".") + 1, version.replace(".", "")
n = f"{int(s)+1:0{len(s)}d}"[::-1]
return (".".join(n[i] for i in range(c)) + n[c:])[::-1] | python | train | abovesol | codeparrot/apps | all |
I found an interesting problem on https://www.codewars.com/kata/5a3141fe55519e04d90009d8:
Lеt's create function to play cards. Our rules:
We have the preloaded `deck`:
```
deck = ['joker','2♣','3♣','4♣','5♣','6♣','7♣','8♣','9♣','10♣','J♣','Q♣','K♣','A♣',
'2♦','3♦','4♦','5♦','6♦','7♦','8♦','9♦','10♦','J♦','Q♦','K♦','A♦',
'2♥','3♥','4♥','5♥','6♥','7♥','8♥','9♥','10♥','J♥','Q♥','K♥','A♥',
'2♠','3♠','4♠','5♠','6♠','7♠','8♠','9♠','10♠','J♠','Q♠','K♠','A♠']
```
We have 3 arguments:
`card1` and `card2` - any card of our deck.
`trump` - the main suit of four ('♣', '♦', '♥', '♠').
If both cards have the same suit, the big one wins.
If the cards have different suits (and no one has trump) return 'Let's play again.'
If one card has `trump` unlike another, wins the first one.
If both cards have `trump`, the big one wins.
If `card1` wins, return 'The first card won.' and vice versa.
If the cards are equal, return 'Someone cheats.'
A few games:
```
('3♣', 'Q♣', '♦') -> 'The second card won.'
('5♥', 'A♣', '♦') -> 'Let us play again.'
('8♠', '8♠', '♣') -> 'Someone cheats.'
('2♦', 'A♠', '♦') -> 'The first card won.'
('joker', 'joker', '♦') -> 'Someone cheats.'
```
P.S. As a card you can also get the string 'joker' - it means this card always wins.
I tried it in Python, but could not do it. Can you solve it? | deck = ['joker','2♣','3♣','4♣','5♣','6♣','7♣','8♣','9♣','10♣','J♣','Q♣','K♣','A♣',
'2♦','3♦','4♦','5♦','6♦','7♦','8♦','9♦','10♦','J♦','Q♦','K♦','A♦',
'2♥','3♥','4♥','5♥','6♥','7♥','8♥','9♥','10♥','J♥','Q♥','K♥','A♥',
'2♠','3♠','4♠','5♠','6♠','7♠','8♠','9♠','10♠','J♠','Q♠','K♠','A♠']
def card_game(card_1, card_2, trump):
if card_1 == card_2:
return "Someone cheats."
ordinal, trumps = ["first", "second"], f"{card_1}{card_2}".count(trump)
if "joker" in (card_1, card_2):
winner = ordinal[card_2 == "joker"]
elif trumps == 1:
winner = ordinal[trump in card_2]
elif card_1[-1] == card_2[-1]:
winner = ordinal[deck.index(card_2) > deck.index(card_1)]
elif trumps == 0:
return "Let us play again."
return f"The {winner} card won." | python | train | abovesol | codeparrot/apps | all |
Solve in Python:
One unknown hacker wants to get the admin's password of AtForces testing system, to get problems from the next contest. To achieve that, he sneaked into the administrator's office and stole a piece of paper with a list of $n$ passwords — strings, consists of small Latin letters.
Hacker went home and started preparing to hack AtForces. He found that the system contains only passwords from the stolen list and that the system determines the equivalence of the passwords $a$ and $b$ as follows: two passwords $a$ and $b$ are equivalent if there is a letter, that exists in both $a$ and $b$; two passwords $a$ and $b$ are equivalent if there is a password $c$ from the list, which is equivalent to both $a$ and $b$.
If a password is set in the system and an equivalent one is applied to access the system, then the user is accessed into the system.
For example, if the list contain passwords "a", "b", "ab", "d", then passwords "a", "b", "ab" are equivalent to each other, but the password "d" is not equivalent to any other password from list. In other words, if: admin's password is "b", then you can access to system by using any of this passwords: "a", "b", "ab"; admin's password is "d", then you can access to system by using only "d".
Only one password from the list is the admin's password from the testing system. Help hacker to calculate the minimal number of passwords, required to guaranteed access to the system. Keep in mind that the hacker does not know which password is set in the system.
-----Input-----
The first line contain integer $n$ ($1 \le n \le 2 \cdot 10^5$) — number of passwords in the list. Next $n$ lines contains passwords from the list – non-empty strings $s_i$, with length at most $50$ letters. Some of the passwords may be equal.
It is guaranteed that the total length of all passwords does not exceed $10^6$ letters. All of them consist only of lowercase Latin letters.
-----Output-----
In a single line print the minimal number of passwords, the use of which will allow guaranteed to access... | # from sys import stdin
# def rl():
# return [int(w) for w in stdin.readline().split()]
from bisect import bisect_right
from bisect import bisect_left
from collections import defaultdict
from math import sqrt,factorial,gcd,log2,inf,ceil
# map(int,input().split())
# # l = list(map(int,input().split()))
# from itertools import permutations
import sys
input = sys.stdin.readline
# t = int(input())
#
# for _ in range(t):
# a,b,c = map(int,input().split())
# a,b,c = sorted([a,b,c])
# ans = 0
# ans+=b
# c-=b
#
# a,c = sorted([a,c])
# ans+=a
# print(ans)
# print(ans)
def find_parent(u):
if par[u]!=u:
par[u]=find_parent(par[u])
return par[u]
n = int(input())
la = []
hash = defaultdict(list)
par = [0]+[i+1 for i in range(26)]
rank = [1]*(26+1)
seti = set()
booli = [False]*(27)
for i in range(n):
z = input()
z = z[:len(z)-1]
k = min(z)
set1 = set(min(k))
booli[ord(k) - 97 + 1] = True
a = ord(k) - 97 + 1
z2 = find_parent(a)
for i in range(len(z)):
booli[ord(z[i]) - 97 + 1] = True
if z[i] not in set1 :
b = ord(z[i]) - 97 + 1
z1 = find_parent(b)
if z1!=z2:
par[z1] = z2
set1.add(i)
ans = set()
for i in range(26):
if booli[i+1] == True:
# print(chr(i+98))
z = find_parent(i+1)
ans.add(z)
print(len(ans)) | python | test | qsol | codeparrot/apps | all |
Solve in Python:
Dasha logged into the system and began to solve problems. One of them is as follows:
Given two sequences a and b of length n each you need to write a sequence c of length n, the i-th element of which is calculated as follows: c_{i} = b_{i} - a_{i}.
About sequences a and b we know that their elements are in the range from l to r. More formally, elements satisfy the following conditions: l ≤ a_{i} ≤ r and l ≤ b_{i} ≤ r. About sequence c we know that all its elements are distinct.
[Image]
Dasha wrote a solution to that problem quickly, but checking her work on the standard test was not so easy. Due to an error in the test system only the sequence a and the compressed sequence of the sequence c were known from that test.
Let's give the definition to a compressed sequence. A compressed sequence of sequence c of length n is a sequence p of length n, so that p_{i} equals to the number of integers which are less than or equal to c_{i} in the sequence c. For example, for the sequence c = [250, 200, 300, 100, 50] the compressed sequence will be p = [4, 3, 5, 2, 1]. Pay attention that in c all integers are distinct. Consequently, the compressed sequence contains all integers from 1 to n inclusively.
Help Dasha to find any sequence b for which the calculated compressed sequence of sequence c is correct.
-----Input-----
The first line contains three integers n, l, r (1 ≤ n ≤ 10^5, 1 ≤ l ≤ r ≤ 10^9) — the length of the sequence and boundaries of the segment where the elements of sequences a and b are.
The next line contains n integers a_1, a_2, ..., a_{n} (l ≤ a_{i} ≤ r) — the elements of the sequence a.
The next line contains n distinct integers p_1, p_2, ..., p_{n} (1 ≤ p_{i} ≤ n) — the compressed sequence of the sequence c.
-----Output-----
If there is no the suitable sequence b, then in the only line print "-1".
Otherwise, in the only line print n integers — the elements of any suitable sequence b.
-----Examples-----
Input
5 1 5
1 1 1 1 1
3 1 5 4 2
Output
3 1 5 4 2
Input
4 2 9
3 4 8 9
3 2 1... | R= lambda: list(map(int,input().split()))
n,l,r= R()
a,d=list(R()),list(R())
b=[l for _ in range(n)]
c=[0 for _ in range(n)]
for i in range(n):
c[d[i]-1]=i
dif=l-a[c[0]]
for x in c[1:]:
if b[x]-a[x]<=dif:
b[x]=a[x]+dif+1
dif=b[x]-a[x]
if b[x]>r:
print("-1")
return
print(" ".join(map(str,b))) | python | test | qsol | codeparrot/apps | all |
I found an interesting problem on https://www.codewars.com/kata/549c7ae26d86c7c3ed000b87:
For all x in the range of integers [0, 2 ** n), let y[x] be the binary exclusive-or of x and x // 2. Find the sum of all numbers in y.
Write a function sum_them that, given n, will return the value of the above sum.
This can be implemented a simple loop as shown in the initial code. But once n starts getting to higher numbers, such as 2000 (which will be tested), the loop is too slow.
There is a simple solution that can quickly find the sum. Find it!
Assume that n is a nonnegative integer.
Hint: The complete solution can be written in two lines.
I tried it in Python, but could not do it. Can you solve it? | def sum_them(n):
return 2 ** (n*2-1) - 2 ** (n-1) | python | train | abovesol | codeparrot/apps | all |
Solve in Python:
Given two integer arrays where the second array is a shuffled duplicate of the first array with one element missing, find the missing element.
Please note, there may be duplicates in the arrays, so checking if a numerical value exists in one and not the other is not a valid solution.
```
find_missing([1, 2, 2, 3], [1, 2, 3]) => 2
```
```
find_missing([6, 1, 3, 6, 8, 2], [3, 6, 6, 1, 2]) => 8
```
The first array will always have at least one element. | def find_missing(a, b):
for x in b:
a.remove(x)
return a[0] | python | train | qsol | codeparrot/apps | all |
I found an interesting problem on https://leetcode.com/problems/decode-string/:
Given an encoded string, return it's decoded string.
The encoding rule is: k[encoded_string], where the encoded_string inside the square brackets is being repeated exactly k times. Note that k is guaranteed to be a positive integer.
You may assume that the input string is always valid; No extra white spaces, square brackets are well-formed, etc.
Furthermore, you may assume that the original data does not contain any digits and that digits are only for those repeat numbers, k. For example, there won't be input like 3a or 2[4].
Examples:
s = "3[a]2[bc]", return "aaabcbc".
s = "3[a2[c]]", return "accaccacc".
s = "2[abc]3[cd]ef", return "abcabccdcdcdef".
I tried it in Python, but could not do it. Can you solve it? | class Solution:
def decodeString(self, s):
"""
:type s: str
:rtype: str
"""
stack_num = []
stack_str = []
num = ''
string = ''
for c in s:
if c.isdigit():
if num == '':
stack_str.append(string)
string = ''
num += c
elif c == '[':
stack_num.append(int(num))
num = ''
elif c == ']':
string = stack_str.pop() + string * stack_num.pop()
else:
string += c
return string | python | train | abovesol | codeparrot/apps | all |
I found an interesting problem on https://www.codechef.com/problems/CHEFADV:
Mysterious Chefland… Recently, Chef realised that Discuss, the educational system of Chefland, is out of date. Therefore, he is trying to find ways to update the infrastructure in the country. One possible way is to move all materials from Discuss to Discourse.
Chef will have access to Discourse if his knowledge and power become exactly equal to $N$ and $M$ respectively. Initially, he has power $1$ and knowledge $1$.
Chef can perform actions of the following types to improve his skills:
- solve a problem — increase his knowledge by $X$
- do a push-up — increase his power by $Y$
- install ShareChat to keep in touch with friends — increase both knowledge and power by $1$
Chef can only install ShareChat at most once. The remaining actions may be performed any number of times and the actions may be performed in any order.
Help Chef find out whether it is possible to move from Discuss to Discourse.
-----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 four space-separated integers $N$, $M$, $X$ and $Y$.
-----Output-----
For each test case, print a single line containing the string "Chefirnemo" if it is possible to reach the required knowledge and power or "Pofik" if it is impossible.
-----Constraints-----
- $1 \le T \le 1,000$
- $1 \le N, M, X, Y \le 10^9$
-----Subtasks-----
Subtask #1 (30 points): $1 \le N, M, X, Y \le 100$
Subtask #2 (70 points): original constraints
-----Example Input-----
5
2 2 1 2
11 10 5 9
11 11 5 9
12 11 5 9
1 2 1 100
-----Example Output-----
Chefirnemo
Chefirnemo
Pofik
Chefirnemo
Pofik
-----Explanation-----
Example case 2: We add $Y=9$ once to the power to get power $10$. We add $X=5$ twice to the knowledge to get knowledge $11$.
Example case 3: We can see that it is impossible to reach power $M=11$ no matter which or how many operations we do. Note that the ShareChat operation will increase both knowledge and power by $1$, and...
I tried it in Python, but could not do it. Can you solve it? | t = int(input())
for _ in range(t):
n, m, x, y = (int(x) for x in input().split())
a = (n-1)%x == 0 and (m-1)%y == 0
b = (n-2)%x == 0 and (m-2)%y == 0 and min(n,m)>1
if a or b :
print("Chefirnemo")
else:
print("Pofik") | python | train | abovesol | codeparrot/apps | all |
Solve in Python:
You are given two strings s and t of the same length. You want to change s to t. Changing the i-th character of s to i-th character of t costs |s[i] - t[i]| that is, the absolute difference between the ASCII values of the characters.
You are also given an integer maxCost.
Return the maximum length of a substring of s that can be changed to be the same as the corresponding substring of twith a cost less than or equal to maxCost.
If there is no substring from s that can be changed to its corresponding substring from t, return 0.
Example 1:
Input: s = "abcd", t = "bcdf", maxCost = 3
Output: 3
Explanation: "abc" of s can change to "bcd". That costs 3, so the maximum length is 3.
Example 2:
Input: s = "abcd", t = "cdef", maxCost = 3
Output: 1
Explanation: Each character in s costs 2 to change to charactor in t, so the maximum length is 1.
Example 3:
Input: s = "abcd", t = "acde", maxCost = 0
Output: 1
Explanation: You can't make any change, so the maximum length is 1.
Constraints:
1 <= s.length, t.length <= 10^5
0 <= maxCost <= 10^6
s and t only contain lower case English letters. | class Solution:
def equalSubstring(self, s: str, t: str, maxCost: int) -> int:
i = 0
for j in range(len(s)):
maxCost -= abs(ord(s[j]) - ord(t[j]))
if maxCost < 0:
maxCost += abs(ord(s[i]) - ord(t[i]))
i += 1
return j - i + 1 | python | train | qsol | codeparrot/apps | all |
I found an interesting problem on https://www.codewars.com/kata/5720a81309e1f9b232001c5b:
# RegExp Fun #1 - When I miss few days of gym
## Disclaimer
The background story of this Kata is 100% fiction. Any resemblance to real people or real events is **nothing more than a coincidence** and should be regarded as such.
## Background Story
You are a person who loves to go to the gym everyday with the squad of people that you've known since early childhood. However, you recently contracted a sickness that forced you to stay at home for over a week. As you see your body getting weaker and weaker every day and as you see your biceps and triceps disappearing, you can't help but lay in bed and cry. You're usually an optimistic person but this time negative thoughts come to your head ...
![When I miss few days of gym](https://pics.onsizzle.com/Instagram-faf8c9.png)
## Task
As can be seen from the funny image above (or am I the only person to find the picture above hilarious?) there is lots of slang. Your task is to define a function ```gymSlang``` which accepts a string argument and does the following:
1. Replace *all* instances of ```"probably"``` to ```"prolly"```
2. Replace *all* instances of ```"i am"``` to ```"i'm"```
3. Replace *all* instances of ```"instagram"``` to ```"insta"```
4. Replace *all* instances of ```"do not"``` to ```"don't"```
5. Replace *all* instances of ```"going to"``` to ```"gonna"```
6. Replace *all* instances of ```"combination"``` to ```"combo"```
Your replacement regexes **should be case-sensitive**, only replacing the words above with slang if the detected pattern is in **lowercase**. However, please note that apart from 100% lowercase matches, you will **also have to replace matches that are correctly capitalized** (e.g. ```"Probably" => "Prolly"``` or ```"Instagram" => "Insta"```).
Finally, your code will be tested to make sure that you have used **RegExp** replace in your code.
Enjoy :D
I tried it in Python, but could not do it. Can you solve it? | from functools import reduce
REPLS = (
('probably', 'prolly'), ('Probably', 'Prolly'), ('i am', "i'm"),
('I am', "I'm"), ('instagram', 'insta'), ('Instagram', 'Insta'),
('do not', "don't"), ('Do not', "Don't"), ('going to', 'gonna'),
('Going to', 'Gonna'), ('combination', 'combo'), ('Combination', 'Combo')
)
def gym_slang(s, _=None):
return reduce(lambda a, kv: a.replace(*kv), REPLS, s) | python | train | abovesol | codeparrot/apps | all |
Solve in Python:
In this Kata, you will create a function that converts a string with letters and numbers to the inverse of that string (with regards to Alpha and Numeric characters). So, e.g. the letter `a` will become `1` and number `1` will become `a`; `z` will become `26` and `26` will become `z`.
Example: `"a25bz"` would become `"1y226"`
Numbers representing letters (`n <= 26`) will always be separated by letters, for all test cases:
* `"a26b"` may be tested, but not `"a262b"`
* `"cjw9k"` may be tested, but not `"cjw99k"`
A list named `alphabet` is preloaded for you: `['a', 'b', 'c', ...]`
A dictionary of letters and their number equivalent is also preloaded for you called `alphabetnums = {'a': '1', 'b': '2', 'c': '3', ...}` | import re
def AlphaNum_NumAlpha(string):
return ''.join(chr(int(e)+96) if e.isdigit() else str(ord(e)-96) for e in re.split('([a-z])', string) if e) | python | train | qsol | codeparrot/apps | all |
Solve in Python:
Although Inzane successfully found his beloved bone, Zane, his owner, has yet to return. To search for Zane, he would need a lot of money, of which he sadly has none. To deal with the problem, he has decided to hack the banks. [Image]
There are n banks, numbered from 1 to n. There are also n - 1 wires connecting the banks. All banks are initially online. Each bank also has its initial strength: bank i has initial strength a_{i}.
Let us define some keywords before we proceed. Bank i and bank j are neighboring if and only if there exists a wire directly connecting them. Bank i and bank j are semi-neighboring if and only if there exists an online bank k such that bank i and bank k are neighboring and bank k and bank j are neighboring.
When a bank is hacked, it becomes offline (and no longer online), and other banks that are neighboring or semi-neighboring to it have their strengths increased by 1.
To start his plan, Inzane will choose a bank to hack first. Indeed, the strength of such bank must not exceed the strength of his computer. After this, he will repeatedly choose some bank to hack next until all the banks are hacked, but he can continue to hack bank x if and only if all these conditions are met: Bank x is online. That is, bank x is not hacked yet. Bank x is neighboring to some offline bank. The strength of bank x is less than or equal to the strength of Inzane's computer.
Determine the minimum strength of the computer Inzane needs to hack all the banks.
-----Input-----
The first line contains one integer n (1 ≤ n ≤ 3·10^5) — the total number of banks.
The second line contains n integers a_1, a_2, ..., a_{n} ( - 10^9 ≤ a_{i} ≤ 10^9) — the strengths of the banks.
Each of the next n - 1 lines contains two integers u_{i} and v_{i} (1 ≤ u_{i}, v_{i} ≤ n, u_{i} ≠ v_{i}) — meaning that there is a wire directly connecting banks u_{i} and v_{i}.
It is guaranteed that the wires connect the banks in such a way that Inzane can somehow hack all the banks using a computer with appropriate... | import sys
def solve():
n=int(sys.stdin.readline())
d=list(map(int,sys.stdin.readline().split()))
s=[[] for g in d]
mx_tmp=max(d)
mx_tmp2=max(g for g in d+[-2e9] if g<mx_tmp)
mxpt=[mx_tmp,mx_tmp2]
mxcnt=[d.count(mx_tmp),d.count(mx_tmp2)]
for i in range(1,n):
a,b=map(int,sys.stdin.readline().split())
a-=1;
b-=1;
s[a]+=[b]
s[b]+=[a]
mx=int(2e9)
for i in range(n):
nmx=[]+mxcnt
tmpmax=d[i]
for k in s[i]:
if d[k]==mxpt[0]:
nmx[0]-=1
elif d[k]==mxpt[1]:
nmx[1]-=1
if nmx[0]!=mxcnt[0]:
tmpmax=mxpt[0]+1
elif nmx[1]!=mxcnt[1]:
tmpmax=max(tmpmax,mxpt[1]+1)
if d[i]==mxpt[0]:
nmx[0]-=1
elif d[i]==mxpt[1]:
nmx[1]-=1
if nmx[0]:
tmpmax=mxpt[0]+2
elif nmx[1]:
tmpmax=max(mxpt[1]+2,tmpmax)
mx=min(mx,tmpmax)
print(mx)
def __starting_point():
solve()
__starting_point() | python | test | qsol | codeparrot/apps | all |
Solve in Python:
Given n non-negative integers a1, a2, ..., an, where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). Find two lines, which together with x-axis forms a container, such that the container contains the most water.
Note: You may not slant the container and n is at least 2. | class Solution:
def maxArea(self, height):
"""
:type height: List[int]
:rtype: int
"""
left_index = 0
right_index = len(height) - 1
water = 0
while True:
if left_index >= right_index:
break
left_height = height[left_index]
right_height = height[right_index]
water = max(water, (right_index - left_index) * min(left_height, right_height))
if left_height < right_height:
left_index += 1
else:
right_index -= 1
return water | python | train | qsol | codeparrot/apps | all |
I found an interesting problem on https://www.codewars.com/kata/56044de2aa75e28875000017:
You have to create a method "compoundArray" which should take as input two int arrays of different length and return one int array with numbers of both arrays shuffled one by one.
```Example:
Input - {1,2,3,4,5,6} and {9,8,7,6}
Output - {1,9,2,8,3,7,4,6,5,6}
```
I tried it in Python, but could not do it. Can you solve it? | def compound_array(a, b):
answer = []
while a or b:
if a: answer.append(a.pop(0))
if b: answer.append(b.pop(0))
return answer | python | train | abovesol | codeparrot/apps | all |
I found an interesting problem on https://www.codewars.com/kata/54df2067ecaa226eca000229:
Due to another of his misbehaved,
the primary school's teacher of the young Gauß, Herr J.G. Büttner, to keep the bored and unruly young schoolboy Karl Friedrich Gauss busy for a good long time, while he teaching arithmetic to his mates,
assigned him the problem of adding up all the whole numbers from 1 through a given number `n`.
Your task is to help the young Carl Friedrich to solve this problem as quickly as you can; so, he can astonish his teacher and rescue his recreation interval.
Here's, an example:
```
f(n=100) // returns 5050
```
It's your duty to verify that n is a valid positive integer number. If not, please, return false (None for Python, null for C#).
> **Note:** the goal of this kata is to invite you to think about some 'basic' mathematic formula and how you can do performance optimization on your code.
> Advanced - experienced users should try to solve it in one line, without loops, or optimizing the code as much as they can.
-----
**Credits:** this kata was inspired by the farzher's kata 'Sum of large ints' . In fact, it can be seen as a sort of prep kata for that one.
I tried it in Python, but could not do it. Can you solve it? | def f(n):
if isinstance(n, int) and n >0:
return (1/2)*n*(n+1)
else:
return None | python | train | abovesol | codeparrot/apps | all |