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... | 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 int... | 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 ... | 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... | 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 t... | 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 positiv... | # 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 ... | 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 ... | 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 (an... | 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... | 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 = ... | 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... | 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(fract... | 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.... | 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... | 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 an... | 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 ... | 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:
... | 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")... | 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-di... | 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 Iv... | 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 hea... | 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:
prin... | 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,... | 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... | 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 sa... | 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 <... | 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... | 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 ... | 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]>... | 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... | 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... | 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 ... | 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 ==... | 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 loc... | 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):... | 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... | 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
... | 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... | 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... | 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 ... | 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 ... | 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 monste... | 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. T... | 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') + bi... | 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---... | 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))
... | 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... | 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 ^ opera... | 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, ... | 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... | 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
... | 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... | 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... | 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':
to... | 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 fe... | 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 ... | 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:
... | 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 elemen... | 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 eat... | 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
... | 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 m... | 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)... | 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 choo... | 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(... | 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... | 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 a... | 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, ... | 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 "... | 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 ... | 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 wa... | 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_coun... | 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|... | 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... | 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... | 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, ... | 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
... | 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.
Katta... | 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 minimu... | # 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,... | 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... | 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,... | # 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)
de... | 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 pizz... | 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 pla... | 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[... | 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... | 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... | 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... | 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... | 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 o... | 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 rep... | 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)
e... | 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$ indep... | 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 shoul... | 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, th... | 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``` th... | 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 ... | 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 curre... | 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()
... | 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... | 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(... | 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 `... | 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... | 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 - ... | 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 end... | 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:
... | 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 $... | # 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,... | 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 ... | # 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 fou... | 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 sat... | 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 ... | 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 consisti... | 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!` ... | # 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 f... | 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', '... | 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 ... | 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... | 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 cit... | 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 ... | 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... | 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 conne... | 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):
s... | 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 r... | 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♦','... | 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♠'... | 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 s... | # 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 iterto... | 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 ... | 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(" ".joi... | 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 ... | 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... | 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... | 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.appe... | 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 Dis... | 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... | 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.... | 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', 'Comb... | 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... | 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 wire... | 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;
... | 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.
... | 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_heigh... | 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} ... | 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 hi... | 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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.