inputs stringlengths 175 2.22k | targets stringlengths 10 2.05k | language stringclasses 1
value | split stringclasses 2
values | template stringclasses 2
values | dataset stringclasses 1
value | config stringclasses 1
value |
|---|---|---|---|---|---|---|
Solve in Python:
The main city magazine offers its readers an opportunity to publish their ads. The format of the ad should be like this:
There are space-separated non-empty words of lowercase and uppercase Latin letters.
There are hyphen characters '-' in some words, their positions set word wrapping points. Word ca... | n = int(input())
s = input()
s += ' '
def ok(w):
wordcnt = 0
lettercnt = 0
linecnt = 0
for j in range(len(s)):
if not (s[j]==' ' or s[j]=='-'):
lettercnt += 1;
else:
lettercnt += 1
if j==len(s)-1:
lettercnt -= 1
if (wordcnt+lettercnt)>w:
linecnt += 1
wordcnt = lettercnt
else:
word... | python | test | qsol | codeparrot/apps | all |
Solve in Python:
There is a grid of squares with H horizontal rows and W vertical columns.
The square at the i-th row from the top and the j-th column from the left is represented as (i, j).
Each square is black or white.
The color of the square is given as an H-by-W matrix (a_{i, j}).
If a_{i, j} is ., the square (i, ... | import sys
input = sys.stdin.readline
H, W = map(int, input().split())
grid = []
for _ in range(H):
grid.append(list(input().strip()))
h_set = set()
for i in range(H):
flag = True
for j in range(W):
if grid[i][j] == "#":
flag = False
break
if flag:
h_set.add(i)
... | python | test | qsol | codeparrot/apps | all |
I found an interesting problem on https://www.codewars.com/kata/5840946ea3d4c78e90000068:
It's the most hotly anticipated game of the school year - Gryffindor vs Slytherin! Write a function which returns the winning team.
You will be given two arrays with two values.
The first given value is the number of points sc... | def game_winners(gryffindor, slytherin):
g = gryffindor[0] + 150 * (gryffindor[1] == "yes")
s = slytherin[0] + 150 * (slytherin[1] == "yes")
return "Gryffindor wins!" if g > s else "Slytherin wins!" if s > g else "It's a draw!" | python | train | abovesol | codeparrot/apps | all |
I found an interesting problem on https://www.codewars.com/kata/554a44516729e4d80b000012:
Let us begin with an example:
A man has a rather old car being worth $2000.
He saw a secondhand car being worth $8000. He wants to keep his old car until he can buy the secondhand one.
He thinks he can save $1000 each month but... | def nbMonths(oldCarPrice, newCarPrice, saving, loss):
months = 0
budget = oldCarPrice
while budget < newCarPrice:
months += 1
if months % 2 == 0:
loss += 0.5
oldCarPrice *= (100 - loss) / 100
newCarPrice *= (100 - loss) / 100
budget = saving ... | python | train | abovesol | codeparrot/apps | all |
I found an interesting problem on https://www.codechef.com/MAY16/problems/CHBLLS:
Chef has bought ten balls of five colours. There are two balls of each colour. Balls of same colour have same weight. Let us enumerate colours by numbers from 1 to 5. Chef knows that all balls, except two (of same colour), weigh exactly o... | print("1")
print("3 1 2 2")
print("3 3 4 4")
import sys
d = {1:1,
2:2,
-1:3,
-2:4,
0:5
}
sys.stdout.flush()
v = eval(input())
print("2")
print(d[v]) | python | test | abovesol | codeparrot/apps | all |
Solve in Python:
# Our Setup
Alice and Bob work in an office. When the workload is light and the boss isn't looking, they often play simple word games for fun. This is one of those days!
# This Game
Today Alice and Bob are playing what they like to call _Mutations_, where they take turns trying to "think up" a new f... | import re
def genMask(w):
x = list(w)
for i in range(len(w)):
x[i] = '.'
yield ''.join(x)
x[i] = w[i]
def mutations(alice, bob, word, first):
players, seen = [alice,bob], {word}
win, failed, i = -1, -1, first^1
while 1:
i ^= 1
lst = players[i]
... | python | train | qsol | codeparrot/apps | all |
Solve in Python:
Sereja loves number sequences very much. That's why he decided to make himself a new one following a certain algorithm.
Sereja takes a blank piece of paper. Then he starts writing out the sequence in m stages. Each time he either adds a new number to the end of the sequence or takes l first elements o... | n=int(input())
a=[]
for i in range(n):
a.append(list(map(int,input().split())))
m=int(input())
b=list([int(x)-1 for x in input().split()])
c=[]
now=0
k=0
ans=[]
for i in range(n):
t=a[i]
if t[0]==1:
now+=1
if len(c)<100000: c.append(t[1])
if k<m and b[k]==now-1:
ans.append(t[1])
k+=1
else:
last=now
... | python | train | qsol | codeparrot/apps | all |
Solve in Python:
We have a string S of length N consisting of uppercase English letters.
How many times does ABC occur in S as contiguous subsequences (see Sample Inputs and Outputs)?
-----Constraints-----
- 3 \leq N \leq 50
- S consists of uppercase English letters.
-----Input-----
Input is given from Standard Inp... | n = int(input())
s = list(input())
cnt = 0
for i in range(n-2):
if s[i]+s[i+1]+s[i+2] == "ABC":
cnt += 1
print(cnt) | python | test | qsol | codeparrot/apps | all |
Solve in Python:
Stepan has the newest electronic device with a display. Different digits can be shown on it. Each digit is shown on a seven-section indicator like it is shown on the picture below. [Image]
So, for example, to show the digit 3 on the display, 5 sections must be highlighted; and for the digit 6, 6 sect... | n = 0
one = 0
seven = 0
i = 0
j = 0
n = int(input())
if n % 2 == 0:
for i in range(1, n // 2 + 1):
print('1', end="")
else:
print('7', end="")
n = n - 3
while n > 1:
print('1', end="")
n = n - 2 | python | test | qsol | codeparrot/apps | all |
Solve in Python:
There are N people numbered 1 to N. Each of them is either an honest person whose testimonies are always correct or an unkind person whose testimonies may be correct or not.
Person i gives A_i testimonies. The j-th testimony by Person i is represented by two integers x_{ij} and y_{ij}. If y_{ij} = 1, t... | n=int(input())
a=[]
l=[]
for i in range(n):
A=int(input())
L=[list(map(int,input().split())) for _ in range(A)]
a.append(A)
l.append(L)
ans=0
for i in range(2**n):
b=[0]*n
for j in range(n):
if (i>>j)&1:
b[j]=1
for k in range(n):
f... | python | test | qsol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/411/B:
The research center Q has developed a new multi-core processor. The processor consists of n cores and has k cells of cache memory. Consider the work of this processor.
At each cycle each core of the processor gets one instruction: eithe... | n, m, k = map(int, input().split())
a = [[0 for i in range(m)] for j in range(n)]
inf = [0 for i in range(k + 1)]
stat = [True for i in range(n + 1)]
time = [0 for i in range(n + 1)]
for i in range(n):
a[i] = list(map(int, input().split()))
for i in range(m):
for j in range(1, n + 1):
if stat[j]:
... | python | test | abovesol | codeparrot/apps | all |
Solve in Python:
Takahashi is meeting up with Aoki.
They have planned to meet at a place that is D meters away from Takahashi's house in T minutes from now.
Takahashi will leave his house now and go straight to the place at a speed of S meters per minute.
Will he arrive in time?
-----Constraints-----
- 1 \leq D \leq ... | d,t,s = input().strip().split()
d,t,s = [int(d), int(t), int(s)]
sum = d / s
if t >= sum :
print('Yes')
else:
print('No') | python | test | qsol | codeparrot/apps | all |
I found an interesting problem on https://atcoder.jp/contests/abc165/tasks/abc165_c:
Given are positive integers N, M, Q, and Q quadruples of integers ( a_i , b_i , c_i , d_i ).
Consider a sequence A satisfying the following conditions:
- A is a sequence of N positive integers.
- 1 \leq A_1 \leq A_2 \le \cdots \leq A... | from itertools import combinations_with_replacement
N, M, Q = map(int, input().split())
T = []
for q in range(Q):
T.append(list(map(int, input().split())))
A = list(combinations_with_replacement(list(range(1, M+1)), N))
Alist = [list(a) for a in A]
#print(Alist)
Max = 0
for a in Alist:
cost = 0
for t i... | python | test | abovesol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/1375/G:
You are given a tree with $n$ vertices. You are allowed to modify the structure of the tree through the following multi-step operation: Choose three vertices $a$, $b$, and $c$ such that $b$ is adjacent to both $a$ and $c$. For every v... | from collections import defaultdict
n = int(input())
graph = defaultdict(list)
for i in range(n - 1):
l = list(map(int, input().split()))
graph[l[0]].append(l[1])
graph[l[1]].append(l[0])
color_v = [-1]*(n + 1)
color_v[1] = 0
q = [1]
while q:
x = q.pop()
for i in graph[x]:
if color_v[i] == -... | python | test | abovesol | codeparrot/apps | all |
Solve in Python:
You are given a huge decimal number consisting of $n$ digits. It is guaranteed that this number has no leading zeros. Each digit of this number is either 0 or 1.
You may perform several (possibly zero) operations with this number. During each operation you are allowed to change any digit of your numbe... | n,x,y=[int(x) for x in input().split()]
a=[int(x) for x in list(input())]
counter=0
for i in range(n-x,n):
if i==n-y-1:
if a[i]==0:
counter+=1
else:
if a[i]==1:
counter+=1
print(counter) | python | test | qsol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/254/B:
In 2013, the writers of Berland State University should prepare problems for n Olympiads. We will assume that the Olympiads are numbered with consecutive integers from 1 to n. For each Olympiad we know how many members of the jury must b... | import sys
from functools import lru_cache, cmp_to_key
from heapq import merge, heapify, heappop, heappush, nsmallest
from math import ceil, floor, gcd, fabs, factorial, fmod, sqrt, inf
from collections import defaultdict as dd, deque, Counter as C
from itertools import combinations as comb, permutations as perm
from b... | python | test | abovesol | codeparrot/apps | all |
I found an interesting problem on https://www.codewars.com/kata/58de819eb76cf778fe00005c:
A palindrome is a word, phrase, number, or other sequence of characters which reads the same backward as forward. Examples of numerical palindromes are:
2332
110011
54322345
For this kata, single digit numbers will not be consi... | import re
def palindrome(num):
if not (isinstance(num, int) and num > 0):
return 'Not valid'
return bool(re.search(r'(.)\1|(.).\2', str(num))) | python | train | abovesol | codeparrot/apps | all |
I found an interesting problem on https://www.codewars.com/kata/59f04228e63f8ceb92000038:
The number ```1331``` is the first positive perfect cube, higher than ```1```, having all its digits odd (its cubic root is ```11```).
The next one is ```3375```.
In the interval [-5000, 5000] there are six pure odd digit perfe... | def get_podpc():
r=[]
x=1
while (x*x*x<=1e17):
y=x*x*x
if all(int(d)%2==1 for d in str(y)):
r.append(y)
x+=2
return sorted([-1*x for x in r]+r)
arr=get_podpc()
def odd_dig_cubic(a, b):
return [x for x in arr if a<=x<=b] | python | train | abovesol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/547/B:
Mike is the president of country What-The-Fatherland. There are n bears living in this country besides Mike. All of them are standing in a line and they are numbered from 1 to n from left to right. i-th bear is exactly a_{i} feet high.
... | n = int(input())
a = [0] + list(map(int,input().split())) + [0]
r = [0] * (n + 1)
st = [(0, 0)]
for i in range(1, n + 2):
while a[i] < st[-1][0]:
r[i - st[-2][1] - 1] = max(st[-1][0], r[i - st[-2][1] - 1])
st.pop()
st.append((a[i], i))
for i in range(n): r[-i - 2] = max(r[-i - 2], r[-i - 1])
print(*r[1:]) | python | train | abovesol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/1006/A:
Mishka got an integer array $a$ of length $n$ as a birthday present (what a surprise!).
Mishka doesn't like this present and wants to change it somehow. He has invented an algorithm and called it "Mishka's Adjacent Replacements Algorit... | n = int(input())
lst = [int(x) for x in input().split()]
for i in range(len(lst)):
if lst[i]%2==0:
lst[i]-=1
lst = [str(x) for x in lst]
print(' '.join(lst)) | python | test | abovesol | codeparrot/apps | all |
I found an interesting problem on https://atcoder.jp/contests/abc122/tasks/abc122_c:
You are given a string S of length N consisting of A, C, G and T. Answer the following Q queries:
- Query i (1 \leq i \leq Q): You will be given integers l_i and r_i (1 \leq l_i < r_i \leq N). Consider the substring of S starting at i... | N,Q=list(map(int,input().split()))
S=input()
cnt=[0,0]
for i in range(1,N):
cnt.append(cnt[-1]+S[i-1:i+1].count("AC"))
for _ in range(Q):
l,r=list(map(int,input().split()))
print((cnt[r]-cnt[l])) | python | test | abovesol | codeparrot/apps | all |
Solve in Python:
Being a nonconformist, Volodya is displeased with the current state of things, particularly with the order of natural numbers (natural number is positive integer number). He is determined to rearrange them. But there are too many natural numbers, so Volodya decided to start with the first n. He writes ... | a,b=list(map(int,input().split()))
c=b-(a+1)//2
print(2*c if c>0 else 2*b-1) | python | test | qsol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/1437/E:
You are given an array of $n$ integers $a_1$, $a_2$, ..., $a_n$, and a set $b$ of $k$ distinct integers from $1$ to $n$.
In one operation, you may choose two integers $i$ and $x$ ($1 \le i \le n$, $x$ can be any integer) and assign $a_... | import sys
input=sys.stdin.readline
n,k = map(int,input().split())
a = list(map(int,input().split()))
b = []
if k:
b = list(map(int,input().split()))
for i in range(n):
a[i] -= i
prev = -1
ans = 0
for j in range(k + 1):
if j < k:
val = b[j] - 1
if j and a[prev] > a[val]:
print(-1... | python | test | abovesol | codeparrot/apps | all |
Solve in Python:
Iroha has a sequence of N strings S_1, S_2, ..., S_N. The length of each string is L.
She will concatenate all of the strings in some order, to produce a long string.
Among all strings that she can produce in this way, find the lexicographically smallest one.
Here, a string s=s_1s_2s_3...s_n is lexicog... | N,L = map(int,input().split())
S = []
for i in range(N):
S.append(str(input()))
S.sort()
print(''.join(S)) | python | train | qsol | codeparrot/apps | all |
Solve in Python:
The Physical education teacher at SESC is a sort of mathematician too. His most favorite topic in mathematics is progressions. That is why the teacher wants the students lined up in non-decreasing height form an arithmetic progression.
To achieve the goal, the gym teacher ordered a lot of magical buns... | q = 10001
n, a = int(input()), list(map(int, input().split()))
a.sort()
for i in range(40000 // (n - 1) + 1):
b = [a[j] - j * i for j in range(n)]
u, v = max(b), min(b)
p = (u - v + 1) // 2
if p < q: q, s, d = p, v + p, i
print(q)
print(s, d) | python | test | qsol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/443/B:
Kolya got string s for his birthday, the string consists of small English letters. He immediately added k more characters to the right of the string.
Then Borya came and said that the new string contained a tandem repeat of length l as ... | s = input().rstrip()
k = int(input())
if k > len(s):
print((len(s) + k) - ((len(s) + k) % 2 == 1))
else:
aux = []
for j in range(1, len(s)):
i = len(s) - 1
cnt = 0
while i - j >= 0 and s[i] == s[i - j]:
i -= 1
cnt += 1
if cnt == j:
... | python | test | abovesol | codeparrot/apps | all |
Solve in Python:
You are given an array $a_1, a_2, \dots , a_n$ consisting of integers from $0$ to $9$. A subarray $a_l, a_{l+1}, a_{l+2}, \dots , a_{r-1}, a_r$ is good if the sum of elements of this subarray is equal to the length of this subarray ($\sum\limits_{i=l}^{r} a_i = r - l + 1$).
For example, if $a = [1, 2,... | T, = list(map(int, input().split()))
for t in range(T):
N, = list(map(int, input().split()))
X = [0]*(N+1)
for i, c in enumerate(input().strip()):
X[i+1] = X[i]+int(c)
d = dict()
for i in range( N+1):
x = X[i] - i
if x not in d:
d[x] = 0
d[x] += 1
R = ... | python | test | qsol | codeparrot/apps | all |
Solve in Python:
You are given a directed graph consisting of n vertices and m edges (each edge is directed, so it can be traversed in only one direction). You are allowed to remove at most one edge from it.
Can you make this graph acyclic by removing at most one edge from it? A directed graph is called acyclic iff it... | n, m = [int(x) for x in input().split()]
a = [[] for i in range(n)]
for i in range(m):
u, v = [int(x) for x in input().split()]
a[u - 1].append(v - 1)
color = [0] * n # 0 - white, 1 - grey, 2 - black
cycle = []
blocked_u, blocked_v = -1, -1
def dfs(u):
nonlocal color
nonlocal cycle
if color[u]:
... | python | test | qsol | codeparrot/apps | all |
I found an interesting problem on https://www.codechef.com/COOK17/problems/CIELAB:
In Ciel's restaurant, a waiter is training.
Since the waiter isn't good at arithmetic, sometimes he gives guests wrong change.
Ciel gives him a simple problem.
What is A-B (A minus B) ?
Surprisingly, his answer is wrong.
To be more prec... | a, b = [int(x) for x in input().split()]
r = list(str(a-b))
if r[0] == "1":
r[0] = "2"
else:
r[0]="1"
print("".join(r)) | python | train | abovesol | codeparrot/apps | all |
I found an interesting problem on https://www.codewars.com/kata/53689951c8a5ca91ac000566:
Given an array of arguments, representing system call arguments keys and values, join it into a single, space-delimited string. You don't need to care about the application name -- your task is only about parameters.
Each element... | def args_to_string(args):
return ' '.join('-'*(len(a)>1 and 1+(len(a[0])>1))+' '.join(a) if type(a)==list else a for a in args) | python | train | abovesol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/978/D:
Polycarp likes arithmetic progressions. A sequence $[a_1, a_2, \dots, a_n]$ is called an arithmetic progression if for each $i$ ($1 \le i < n$) the value $a_{i+1} - a_i$ is the same. For example, the sequences $[42]$, $[5, 5, 5]$, $[2, 1... | def solve(n, a):
if n <= 2:
return 0
d = [v - u for u, v in zip(a, a[1:])]
max_d = max(d)
min_d = min(d)
if max_d - min_d > 4:
return -1
min_cnt = -1
for d in range(min_d, max_d + 1):
for d0 in range(-1, 2):
y = a[0] + d0
valid = True
cnt = 0 if d0 == 0 else 1
for x in a[1:]:
dx = abs(y ... | python | test | abovesol | codeparrot/apps | all |
Solve in Python:
One common way of digitalizing sound is to record sound intensity at particular time moments. For each time moment intensity is recorded as a non-negative integer. Thus we can represent a sound file as an array of $n$ non-negative integers.
If there are exactly $K$ distinct values in the array, then w... | n,i=list(map(int,input().split()))
k=2**(8*i//n) if 8*i//n < 20 else n
a=[int(x) for x in input().split()]
a.sort()
freq = [1]
for i in range(1, len(a)):
if a[i-1] == a[i]:
freq[-1] += 1
else:
freq.append(1)
window = sum(freq[:k])
ans = window
for i in range(k, len(freq)):
window += freq[i]
window -= freq[i-k]
... | python | test | qsol | codeparrot/apps | all |
Solve in Python:
Pasha has a positive integer a without leading zeroes. Today he decided that the number is too small and he should make it larger. Unfortunately, the only operation Pasha can do is to swap two adjacent decimal digits of the integer.
Help Pasha count the maximum number he can get if he has the time to ... | def yoba(a, k):
if not a:
return []
elif not k:
return a
else:
m = max(a[:k + 1])
mi = a.index(m)
if m > a[0]:
a[1:mi + 1] = a[:mi]
a[0] = m
k -= mi
return [a[0]] + yoba(a[1:], k)
a, k = str.split(input())
k = int(... | python | test | qsol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/486/E:
The next "Data Structures and Algorithms" lesson will be about Longest Increasing Subsequence (LIS for short) of a sequence. For better understanding, Nam decided to learn it a few days before the lesson.
Nam created a sequence a consis... | N = int( input() )
A = list( map( int, input().split() ) )
maxa = max( A )
def upd( ftree, x, v ):
while x <= maxa:
ftree[ x ] = max( ftree[ x ], v )
x += x & -x
def qry( ftree, x ):
res = 0
while x:
res = max( res, ftree[ x ] )
x -= x & -x
return res
st_len = [ 0 for i in range( N ) ]
ftree... | python | test | abovesol | codeparrot/apps | all |
I found an interesting problem on https://www.codechef.com/problems/EAREA:
You are given a convex polygon $P$ with vertices $P_0, P_1, \ldots, P_{n-1}$, each having integer coordinates. On each edge $P_{i} P_{(i+1) \% n}$ of the polygon, choose a point $R_i$ uniformly at random. What is the expected area of the convex ... | # cook your dish here
def func(a,n):
if n < 3:
return 0
res_arr = []
for i in range(n):
x = (a[i][0] + a[(i + 1) % n][0]) / 2
y = (a[i][1] + a[(i + 1) % n][1]) / 2
res_arr.append((x, y))
l = len(res_arr)
s = 0
for i in range(n):
u = res_arr[i][0]*res_arr[(i+1) % l][1]
v = res_arr[i][1]*res_arr[(i+1) %... | python | train | abovesol | codeparrot/apps | all |
Solve in Python:
Create a function that differentiates a polynomial for a given value of `x`.
Your function will receive 2 arguments: a polynomial as a string, and a point to evaluate the equation as an integer.
## Assumptions:
* There will be a coefficient near each `x`, unless the coefficient equals `1` or `-1`.
*... | def parse_monom(monom):
if 'x' not in monom: monom = monom + 'x^0'
if monom.startswith('x'): monom = '1' + monom
if monom.startswith('-x'): monom = '-1' + monom[1:]
if monom.endswith('x'): monom = monom + '^1'
coefficient, degree = map(int, monom.replace('x', '').split('^'))
return degree, coeff... | python | train | qsol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/520/B:
Vasya has found a strange device. On the front panel of a device there are: a red button, a blue button and a display showing some positive integer. After clicking the red button, device multiplies the displayed number by two. After clic... | def main() -> object:
"""
:rtype : Integer
:return: The answer which the problem is required.
"""
n, m = [int(i) for i in input().split()]
count = 0
while n < m:
if m % 2 == 0:
m >>= 1
else:
m += 1
count += 1
count += n - m
return coun... | python | test | abovesol | codeparrot/apps | all |
Solve in Python:
A shop sells N kinds of fruits, Fruit 1, \ldots, N, at prices of p_1, \ldots, p_N yen per item, respectively. (Yen is the currency of Japan.)
Here, we will choose K kinds of fruits and buy one of each chosen kind. Find the minimum possible total price of those fruits.
-----Constraints-----
- 1 \leq K... | N,K = list(map(int,input().split()))
P = sorted((list(map(int,input().split()))))
print((sum(P[:K]))) | python | test | qsol | codeparrot/apps | all |
I found an interesting problem on https://leetcode.com/problems/largest-values-from-labels/:
We have a set of items: the i-th item has value values[i] and label labels[i].
Then, we choose a subset S of these items, such that:
|S| <= num_wanted
For every label L, the number of items in S with label L is <= use_limit.
... | import heapq
class Solution:
def largestValsFromLabels(self, values: List[int], labels: List[int], num_wanted: int, use_limit: int) -> int:
maxHeap = []
for value, label in zip(values, labels):
print((value, label))
heappush(maxHeap, (-value, label))
... | python | train | abovesol | codeparrot/apps | all |
Solve in Python:
Write a function that accepts two parameters, i) a string (containing a list of words) and ii) an integer (n). The function should alphabetize the list based on the nth letter of each word.
The letters should be compared case-insensitive. If both letters are the same, order them normally (lexicograph... | from operator import itemgetter
def sort_it(list_, n):
return ', '.join(sorted(list_.split(', '), key=itemgetter(n - 1))) | python | train | qsol | codeparrot/apps | all |
Solve in Python:
Takahashi made N problems for competitive programming.
The problems are numbered 1 to N, and the difficulty of Problem i is represented as an integer d_i (the higher, the harder).
He is dividing the problems into two categories by choosing an integer K, as follows:
- A problem with difficulty K or hig... | N = int(input())
d = list(map(int, input().split()))
d.sort()
print(d[N//2] - d[N//2-1]) | python | test | qsol | codeparrot/apps | all |
Solve in Python:
There is a game that involves three variables, denoted A, B, and C.
As the game progresses, there will be N events where you are asked to make a choice.
Each of these choices is represented by a string s_i. If s_i is AB, you must add 1 to A or B then subtract 1 from the other; if s_i is AC, you must ad... | N, A, B, C = map(int, input().split())
S = [input() for _ in range(N)]
ans = []
for i, s in enumerate(S):
if s == "AB":
if A == 0:
A += 1
B -= 1
ans.append("A")
elif B == 0:
A -= 1
B += 1
ans.append("B")
else:
... | python | test | qsol | codeparrot/apps | all |
Solve in Python:
$n$ boys and $m$ girls came to the party. Each boy presented each girl some integer number of sweets (possibly zero). All boys are numbered with integers from $1$ to $n$ and all girls are numbered with integers from $1$ to $m$. For all $1 \leq i \leq n$ the minimal number of sweets, which $i$-th boy pr... | n, m = list(map(int, input().split()))
b = list(map(int, input().split()))
g = list(map(int, input().split()))
x = max(b)
y = min(g)
if x > y:
print(-1)
elif x == y:
print(sum(b) * m + sum(g) - x * m)
else:
m1, m2 = 0, 0
for c in b:
if c >= m1:
m1, m2 = c, m1
elif c >= m2:
... | python | train | qsol | codeparrot/apps | all |
I found an interesting problem on https://atcoder.jp/contests/arc068/tasks/arc068_a:
Snuke has decided to play with a six-sided die. Each of its six sides shows an integer 1 through 6, and two numbers on opposite sides always add up to 7.
Snuke will first put the die on the table with an arbitrary side facing upward, t... | import sys
sys.setrecursionlimit(10**7)
def I(): return int(sys.stdin.readline().rstrip())
def MI(): return list(map(int,sys.stdin.readline().rstrip().split()))
def LI(): return list(map(int,sys.stdin.readline().rstrip().split())) #空白あり
def LI2(): return list(map(int,sys.stdin.readline().rstrip())) #空白なし
def S(): re... | python | test | abovesol | codeparrot/apps | all |
Solve in Python:
You are given string s. Your task is to determine if the given string s contains two non-overlapping substrings "AB" and "BA" (the substrings can go in any order).
-----Input-----
The only line of input contains a string s of length between 1 and 10^5 consisting of uppercase Latin letters.
-----Ou... | def __starting_point():
s = input()
a = None
b = None
for i in range(len(s) - 1):
if s[i] == 'A' and s[i + 1] == 'B':
if a is None:
a = i
if b is not None and abs(i - b) > 1:
print('YES')
return
if s[i] == 'B' an... | python | test | qsol | codeparrot/apps | all |
I found an interesting problem on https://www.codewars.com/kata/56314d3c326bbcf386000007:
Write a function to calculate compound tax using the following table:
For $10 and under, the tax rate should be 10%.
For $20 and under, the tax rate on the first $10 is %10, and the tax on the rest is 7%.
For $30 and under, the t... | def tax_calculator(total):
if not isinstance(total, (int, float)) or total < 0: return 0
tax = 0
if total > 30: tax = 2.2 + (total - 30) * 0.03
elif total > 20: tax = 1.7 + (total - 20) * 0.05
elif total > 10: tax = 1 + (total-10) * 0.07
elif total > 0: tax = total / 10.0
return r... | python | train | abovesol | codeparrot/apps | all |
I found an interesting problem on https://leetcode.com/problems/max-consecutive-ones-iii/:
Given an array A of 0s and 1s, we may change up to K values from 0 to 1.
Return the length of the longest (contiguous) subarray that contains only 1s.
Example 1:
Input: A = [1,1,1,0,0,0,1,1,1,1,0], K = 2
Output: 6
Explanation... | class Solution:
def longestOnes(self, A: List[int], K: int) -> int:
i = 0
j = 0
numZeros = 0
bestSize = 0
while j < len(A):
if A[j] == 1:
pass
elif A[j] == 0:
numZeros += 1
while numZero... | python | train | abovesol | codeparrot/apps | all |
I found an interesting problem on https://atcoder.jp/contests/abc092/tasks/arc093_a:
There are N sightseeing spots on the x-axis, numbered 1, 2, ..., N.
Spot i is at the point with coordinate A_i.
It costs |a - b| yen (the currency of Japan) to travel from a point with coordinate a to another point with coordinate b al... | def main():
n = int(input())
a = list(map(int, input().split()))
a.append(0)
base = abs(a[0])
for i in range(n):
base += abs(a[i+1] - a[i])
ans = []
for i in range(n):
if (a[i] - a[i-1]) * (a[i+1] - a[i]) >= 0:
ans.append(base)
else:
ans.... | python | test | abovesol | codeparrot/apps | all |
I found an interesting problem on https://www.codechef.com/problems/XOMMON:
Given an array of n$n$ integers : A1,A2,...,An$ A_1, A_2,... , A_n$, find the longest size subsequence which satisfies the following property: The xor of adjacent integers in the subsequence must be non-decreasing.
-----Input:-----
- First lin... | # cook your dish here
n=int(input())
l=list(map(int,input().split()))
a=[]
for i in range(0,n):
for j in range(i+1,n):
a.append((l[i]^l[j],(i,j)))
a.sort()
dp=[0]*n
for i in range(0,len(a)):
x=a[i][0]
left,right=a[i][1][0],a[i][1][1]
dp[right]=max(dp[left]+1,dp[right])
print(max(dp)+1) | python | train | abovesol | codeparrot/apps | all |
I found an interesting problem on https://leetcode.com/problems/remove-comments/:
Given a C++ program, remove comments from it. The program source is an array where source[i] is the i-th line of the source code. This represents the result of splitting the original source code string by the newline character \n.
In C+... | S1 = 1
S2 = 2
S3 = 3
S4 = 4
S5 = 5
class Solution(object):
def __init__(self):
self.state = S1
def removeComments(self, source):
"""
:type source: List[str]
:rtype: List[str]
"""
ret = []
buf = []
for s in source:
... | python | train | abovesol | codeparrot/apps | all |
Solve in Python:
A substring of some string is called the most frequent, if the number of its occurrences is not less than number of occurrences of any other substring.
You are given a set of strings. A string (not necessarily from this set) is called good if all elements of the set are the most frequent substrings of... | n=int(input())
m=[]
sc=[]
for i in range(n):
m.append(input())
sc.append(set(m[i]))
if len(sc[i])!=len(m[i]):
print('NO')
break
else:
i=0
pX=False
while i<len(m):
j=i+1
p=False
while j<len(m):
#print(m)
z=len(sc[i].intersection(sc[j... | 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 = map(int, input().split())
a = [None] + list(map(int, input().split()))
dp = [[-1] * (n + 1) for i in range(x + 1)]
dp[0][0] = 0
for i in range(1, x + 1):
for j in range(1, n + 1):
dp[i][j] = max(dp[i - 1][max(0, j - k):j])
if dp[i][j] != -1: dp[i][j] += a[j]
ans = max(dp[x][n - k + 1:n + 1... | python | test | qsol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/779/B:
Polycarp is crazy about round numbers. He especially likes the numbers divisible by 10^{k}.
In the given number of n Polycarp wants to remove the least number of digits to get a number that is divisible by 10^{k}. For example, if k = 3,... | l = input().split()
k = int(l[1]) ; n = l[0]
n = n[::-1]
def compute() :
j = 0 ; i = 0 ; ans = 0
if len(n) <= k :
return len(n)-1
while j < k and i < len(n) :
if n[i] != '0' :
ans += 1
else: j+= 1
i += 1
if i == len(n) and j < k :
return len(n)-1
else:
return ans
print(compute()) | python | test | abovesol | codeparrot/apps | all |
Solve in Python:
You are going to eat X red apples and Y green apples.
You have A red apples of deliciousness p_1,p_2, \dots, p_A, B green apples of deliciousness q_1,q_2, \dots, q_B, and C colorless apples of deliciousness r_1,r_2, \dots, r_C.
Before eating a colorless apple, you can paint it red or green, and it wi... | X, Y, A, B, C = list(map(int, input().split()))
Ps = list(map(int, input().split()))
Qs = list(map(int, input().split()))
Rs = list(map(int, input().split()))
Ps.sort(reverse=True)
Qs.sort(reverse=True)
Rs += Ps[:X] + Qs[:Y]
Rs.sort(reverse=True)
ans = sum(Rs[:X+Y])
print(ans) | python | test | qsol | codeparrot/apps | all |
Solve in Python:
Lee is used to finish his stories in a stylish way, this time he barely failed it, but Ice Bear came and helped him. Lee is so grateful for it, so he decided to show Ice Bear his new game called "Critic"...
The game is a one versus one game. It has $t$ rounds, each round has two integers $s_i$ and $e_... | import sys
input = sys.stdin.readline
def win(s, e):
if e == s:
return False
elif e == s + 1:
return True
elif e & 1:
return s & 1 == 0
elif e // 2 < s:
return s & 1 == 1
elif e // 4 < s:
return True
else:
return win(s, e // 4)
def lose(s, e)... | python | test | qsol | codeparrot/apps | all |
Solve in Python:
# Task:
Write a function that accepts an integer `n` and returns **the sum of the factorials of the first **`n`** Fibonacci numbers**
## Examples:
```python
sum_fib(2) = 2 # 0! + 1! = 2
sum_fib(3) = 3 # 0! + 1! + 1! = 3
sum_fib(4) = 5 # 0! + 1! + 1! + 2! = 5
sum_fib(10) = 2952327990396041... | from math import factorial
def sum_fib(n):
fibo_num = 1
fibo_num_prev = 0
sum_factorial = 0
for num in range(0,n):
sum_factorial = sum_factorial + factorial(fibo_num_prev)
fibo_num_prev, fibo_num = fibo_num, fibo_num + fibo_num_prev
return sum_factorial | python | train | qsol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/630/E:
Developing tools for creation of locations maps for turn-based fights in a new game, Petya faced the following problem.
A field map consists of hexagonal cells. Since locations sizes are going to be big, a game designer wants to have a ... | ch=input()
d=ch.split(" ")
x1=int(d[0])
y1=int(d[1])
x2=int(d[2])
y2=int(d[3])
nby=(y2-y1)//2+1
nbx=(x2-x1)//2+1
print(nby*nbx+(nby-1)*(nbx-1)) | python | test | abovesol | codeparrot/apps | all |
Solve in Python:
We guessed a permutation $p$ consisting of $n$ integers. The permutation of length $n$ is the array of length $n$ where each element from $1$ to $n$ appears exactly once. This permutation is a secret for you.
For each position $r$ from $2$ to $n$ we chose some other index $l$ ($l < r$) and gave you th... | from collections import Counter
from itertools import chain
def dfs(n, r, hint_sets, count, removed, result):
# print(n, r, hint_sets, count, removed, result)
if len(result) == n - 1:
last = (set(range(1, n + 1)) - set(result)).pop()
result.append(last)
return True
i, including_r ... | python | train | qsol | codeparrot/apps | all |
I found an interesting problem on https://www.codechef.com/problems/CHFPARTY:
Tonight, Chef would like to hold a party for his $N$ friends.
All friends are invited and they arrive at the party one by one in an arbitrary order. However, they have certain conditions — for each valid $i$, when the $i$-th friend arrives at... | # cook your dish here
t=0
try:
t=int(input())
except:
pass
for _ in range(t):
n = int(input())
a = list(map(int, input().split()))
a = sorted(a)
already_present = 0
for requirement in a:
if already_present>=requirement:
already_present+=1
print(already_present) | python | train | abovesol | codeparrot/apps | all |
I found an interesting problem on https://www.codechef.com/COM12020/problems/CODE_00:
Give me Biscuit
Sunny wants to make slices of biscuit of size c * d into identical pieces.
but each piece is a square having maximum possible side length with no left over piece of biscuit.
Input Format
The first line contains an ... | t = int(input())
for i in range(t):
m,n = map(int,input().split())
mul = m*n
while(m!=n):
if (m>n):
m-=n
else:
n-=m
print(mul//(m*n)) | python | train | abovesol | codeparrot/apps | all |
Solve in Python:
Make a function that receives a value, ```val``` and outputs the smallest higher number than the given value, and this number belong to a set of positive integers that have the following properties:
- their digits occur only once
- they are odd
- they are multiple of three
```python
next_numb(12) =... | def next_numb(val):
i = val + 1
while i <= 9999999999:
if i % 3 == 0 and i % 2 and len(str(i)) == len(set(str(i))):
return i
i += 1
return 'There is no possible number that fulfills those requirements' | python | train | qsol | codeparrot/apps | all |
I found an interesting problem on https://atcoder.jp/contests/abc100/tasks/abc100_b:
Today, the memorable AtCoder Beginner Contest 100 takes place. On this occasion, Takahashi would like to give an integer to Ringo.
As the name of the contest is AtCoder Beginner Contest 100, Ringo would be happy if he is given a posit... | d, n = list(map(int, input().split()))
start = 100 ** d
counter = 0
while True:
if start % (100 ** d) == 0 and start % (100 ** (d + 1)) != 0:
counter += 1
if counter == n:
print(start)
break
start += 100 ** d | python | test | abovesol | codeparrot/apps | all |
Solve in Python:
Given a binary tree, return the vertical order traversal of its nodes values.
For each node at position (X, Y), its left and right children respectively will be at positions (X-1, Y-1) and (X+1, Y-1).
Running a vertical line from X = -infinity to X = +infinity, whenever the vertical line touches some n... | # 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 verticalTraversal(self, root: TreeNode) -> List[List[int]]:
res = []
frontier = [(root, ... | python | train | qsol | codeparrot/apps | all |
Solve in Python:
You are given a string S as input. This represents a valid date in the year 2019 in the yyyy/mm/dd format. (For example, April 30, 2019 is represented as 2019/04/30.)
Write a program that prints Heisei if the date represented by S is not later than April 30, 2019, and prints TBD otherwise.
-----Constr... | s=input()
if int(s[5]+s[6])>=5:
print('TBD')
else:
print('Heisei') | python | test | qsol | codeparrot/apps | all |
Solve in Python:
Vasily has a deck of cards consisting of n cards. There is an integer on each of the cards, this integer is between 1 and 100 000, inclusive. It is possible that some cards have the same integers on them.
Vasily decided to sort the cards. To do this, he repeatedly takes the top card from the deck, and... | n = int(input())
s = list(map(int,input().split(' ')))
a = []
for i in range(max(s)):
a.append([])
for i in range(len(s)):
a[s[i]-1].append(i)
a = list([x for x in a if x != []])
if len(a) > 1:
for i in range(1,len(a)):
if len(a[i]) > 1:
s = a[i-1][-1]
if s > a[i][0] and ... | python | train | qsol | codeparrot/apps | all |
Solve in Python:
One day Nikita found the string containing letters "a" and "b" only.
Nikita thinks that string is beautiful if it can be cut into 3 strings (possibly empty) without changing the order of the letters, where the 1-st and the 3-rd one contain only letters "a" and the 2-nd contains only letters "b".
Nik... | # python3
# utf-8
string = input()
prefix___a_nr = [0]
prefix___b_nr = [0]
for sym in string:
curr_a_nr = prefix___a_nr[-1]
curr_b_nr = prefix___b_nr[-1]
if sym == 'a':
curr_a_nr += 1
elif sym == 'b':
curr_b_nr += 1
prefix___a_nr.append(curr_a_nr)
prefix___b_nr.append(curr_b_nr)... | python | test | qsol | codeparrot/apps | all |
I found an interesting problem on https://www.codewars.com/kata/58cda88814e65627c5000045:
# Write Number in Expanded Form - Part 2
This is version 2 of my ['Write Number in Exanded Form' Kata](https://www.codewars.com/kata/write-number-in-expanded-form).
You will be given a number and you will need to return it as a ... | def expanded_form1(num):
a = len(str(num))
b = []
for i,j in enumerate(str(num)):
if j != '0':
b.append(j+'0'*(a-i-1))
return ' + '.join(b)
def expanded_form(num):
a = str(num).index('.')
m = int(str(num)[:a])
n = '0' + str(num)[a+1:]
b = []
for i,j in enumerate(... | python | train | abovesol | codeparrot/apps | all |
Solve in Python:
The ZCO scholarship contest offers scholarships to first time ZCO participants. You are participating in it for the first time. So you want to know the number of participants who'll get the scholarship.
You know that the maximum number of scholarships offered is $R$ and there are a total of $N$ partici... | for _ in range(int(input())):
n,r,x,y=map(int,input().split())
if x>0:
arr=set(list(map(int,input().split())))
if y>0:
brr=set(list(map(int,input().split())))
if x>0 and y>0:
crr=list(arr.union(brr))
t=n-len(crr)
if t>r:
print(r)
else:
print(t)
elif x>0 or y>0:
s=max(x,y)
t=n-s
if t>r :
... | python | train | qsol | codeparrot/apps | all |
Solve in Python:
Some people leave the lights at their workplaces on when they leave that is a waste of resources. As a hausmeister of DHBW, Sagheer waits till all students and professors leave the university building, then goes and turns all the lights off.
The building consists of n floors with stairs at the left an... | def coun(pref):
now = 0
for i in range(n):
pos = pref[i]
if pos == 'l':
if i < n - 1 and sum(check[(i + 1):]) > 0:
now += 1
if "1" in mat[i]:
if pref[i + 1] == "r":
now += (m + 1)
else:
... | python | test | qsol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/1105/C:
Ayoub had an array $a$ of integers of size $n$ and this array had two interesting properties: All the integers in the array were between $l$ and $r$ (inclusive). The sum of all the elements was divisible by $3$.
Unfortunately, Ayou... | from sys import stdin, stdout
prime = 10**9 + 7
def unitMatrix(size):
out = [[0]*size for i in range(size)]
for i in range(size):
out[i][i] = 1
return out
def matrixMult(pre, post):
rows = len(pre)
mid = len(post)
columns = len(post[0])
out = [[0]*columns for i in range(rows)]
... | python | test | abovesol | codeparrot/apps | all |
I found an interesting problem on https://atcoder.jp/contests/abc067/tasks/arc078_a:
Snuke and Raccoon have a heap of N cards. The i-th card from the top has the integer a_i written on it.
They will share these cards.
First, Snuke will take some number of cards from the top of the heap, then Raccoon will take all the r... | n=int(input())
a=list(map(int,input().split()))
ans=2*(10**14)+1
s=sum(a)
x=0
y=s
for i in range(n-1):
x+=a[i]
y-=a[i]
ans=min(ans,abs(x-y))
print(ans) | python | test | abovesol | codeparrot/apps | all |
Solve in Python:
There are n students at Berland State University. Every student has two skills, each measured as a number: a_{i} — the programming skill and b_{i} — the sports skill.
It is announced that an Olympiad in programming and sports will be held soon. That's why Berland State University should choose two tea... | #!/usr/bin/env python3
from itertools import accumulate
from heapq import heappop, heappush
def top(ppl_indices, vals, start):
Q = []
res = [0 for i in range(len(ppl_indices))]
for k, idx in enumerate(ppl_indices):
heappush(Q, -vals[idx])
if k >= start:
res[k] = res[k-1] - heap... | python | test | qsol | codeparrot/apps | all |
Solve in Python:
As you know America’s Presidential Elections are about to take place and the most popular leader of the Republican party Donald Trump is famous for throwing allegations against anyone he meets.
He goes to a rally and meets n people which he wants to offend. For each person i he can choose an integer b... | for t in range(int(input())):
n = int(input())
a = sorted(map(int,input().split()))
ans = 1
for i in range(n):
ans *= (a[i]-i)
ans %= (10**9+7)
if (ans == 0):
break
print(ans) | python | train | qsol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/960/A:
A has a string consisting of some number of lowercase English letters 'a'. He gives it to his friend B who appends some number of letters 'b' to the end of this string. Since both A and B like the characters 'a' and 'b', they have made s... | s = input()
flag = 0
ans = 1
aa = s.count("a")
bb = s.count("b")
cc = s.count("c")
if min(aa,bb) == 0 or (bb != cc and aa != cc):
print("NO")
else:
for i in s:
if flag == 0:
if i == "b":
flag = 1
continue
if i != "a":
ans = 0
... | python | test | abovesol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/704/A:
Thor is getting used to the Earth. As a gift Loki gave him a smartphone. There are n applications on this phone. Thor is fascinated by this phone. He has only one minor issue: he can't count the number of unread notifications generated b... | '''input
4 6
1 2
1 4
1 2
3 3
1 3
1 3
'''
n, q = list(map(int, input().split()))
count = [0 for i in range(n + 1)]
queue = []
read = set()
unread = 0
ans = []
last_q_idx = 0
last_app_idx = [1 for i in range(n + 1)]
for i in range(q):
action, num = list(map(int, input().split()))
if action == 1:
queu... | python | train | abovesol | codeparrot/apps | all |
Solve in Python:
You are given strings S and T consisting of lowercase English letters.
You can perform the following operation on S any number of times:
Operation: Choose two distinct lowercase English letters c_1 and c_2, then replace every occurrence of c_1 with c_2, and every occurrence of c_2 with c_1.
Determine i... | import bisect,collections,copy,itertools,math,string
import sys
def I(): return int(sys.stdin.readline().rstrip())
def LI(): return list(map(int,sys.stdin.readline().rstrip().split()))
def S(): return sys.stdin.readline().rstrip()
def LS(): return list(sys.stdin.readline().rstrip().split())
def main():
s = S()
... | python | test | qsol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/802/B:
Whereas humans nowadays read fewer and fewer books on paper, book readership among marmots has surged. Heidi has expanded the library and is now serving longer request sequences.
-----Input-----
Same as the easy version, but the limit... | # https://codeforces.com/problemset/problem/802/B
import heapq
n, k = map(int, input().split())
a = list(map(int, input().split()))
d = {}
pos = {}
Q = []
cnt = 0
for i, x in enumerate(a):
if x not in pos:
pos[x] = []
pos[x].append(i)
for i, x in enumerate(a):
if x not in... | python | test | abovesol | codeparrot/apps | all |
I found an interesting problem on https://atcoder.jp/contests/abc107/tasks/abc107_a:
There is an N-car train.
You are given an integer i. Find the value of j such that the following statement is true: "the i-th car from the front of the train is the j-th car from the back."
-----Constraints-----
- 1 \leq N \leq 100
... | n, i = map(int, input().split())
print(n - i + 1) | python | test | abovesol | codeparrot/apps | all |
I found an interesting problem on https://leetcode.com/problems/rearrange-spaces-between-words/:
You are given a string text of words that are placed among some number of spaces. Each word consists of one or more lowercase English letters and are separated by at least one space. It's guaranteed that text contains at le... | class Solution:
def reorderSpaces(self, text: str) -> str:
# separate words and spaces
words = text.split(' ')
words = list(filter(lambda x: len(x) > 0, words))
# print(words)
# get their counts so we can do some math
wordsLen = len(words)
spacesLen ... | python | train | abovesol | codeparrot/apps | all |
I found an interesting problem on https://www.codewars.com/kata/5a084a098ba9146690000969:
This kata requires you to convert minutes (`int`) to hours and minutes in the format `hh:mm` (`string`).
If the input is `0` or negative value, then you should return `"00:00"`
**Hint:** use the modulo operation to solve this ch... | def time_convert(num):
return '{:02}:{:02}'.format(*divmod(max(0, num), 60)) | python | train | abovesol | codeparrot/apps | all |
I found an interesting problem on https://www.codechef.com/ICOD2016/problems/ICODE16G:
Abhishek is fond of playing cricket very much. One morning, he is playing cricket with his friends. Abhishek is a right-hand batsman
.He has to face all types of balls either good or bad. There are total 26 balls in the game and ... | import sys
for _ in range(0,eval(input())):
d,c,inp,mp,n,q=[],0,list(map(ord,list(sys.stdin.readline().strip()))),sys.stdin.readline().strip(),eval(input()),ord('a')
for i in range(0,len(inp)):
nn,h=n,0
for j in range(i,len(inp)):
if ( (mp[inp[j]-q]=='g') or nn>0 ):
... | python | train | abovesol | codeparrot/apps | all |
I found an interesting problem on https://www.codewars.com/kata/58983deb128a54b530000be6:
Write a function that checks the braces status in a string, and return `True` if all braces are properly closed, or `False` otherwise. Available types of brackets: `()`, `[]`, `{}`.
**Please note, you need to write this function ... | def braces_status(string):
s = "".join(list(filter(lambda ch: ch in "{[()]}",list(string))))
while '{}' in s or '()' in s or '[]' in s:
s=s.replace('{}','')
s=s.replace('[]','')
s=s.replace('()','')
return s=='' | python | train | abovesol | codeparrot/apps | all |
Solve in Python:
You are given a bracket sequence $s$ (not necessarily a regular one). A bracket sequence is a string containing only characters '(' and ')'.
A regular bracket sequence is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters '1' and '+' between the ori... | MOD=10**9+7
n=int(input())
s=[c=='(' for c in input()]
m=len(s)
z=[[0,0]]
for v in s:
a=z[-1][v]
z[-1][v]=len(z)
z.append(z[a][:])
z[m][0]=z[m][1]=m
dp=[[0 for _ in range(m+1)] for _ in range(n+1)]
dp[0][0]=1
for _ in range(2*n):
ndp=[[0 for _ in range(m+1)] for _ in range(n+1)]
for i in range(n+1):
for j in ran... | python | test | qsol | codeparrot/apps | all |
I found an interesting problem on https://www.codewars.com/kata/5886faac54a7111c21000072:
# Task
A media access control address (MAC address) is a unique identifier assigned to network interfaces for communications on the physical network segment.
The standard (IEEE 802) format for printing MAC-48 addresses in human... | is_mac_48_address = lambda address: bool( __import__("re").match('-'.join(['[0-9A-F]{2}']*6) + '$', address) ) | python | train | abovesol | codeparrot/apps | all |
I found an interesting problem on https://www.codewars.com/kata/52ec24228a515e620b0005ef:
# How many ways can you make the sum of a number?
From wikipedia: https://en.wikipedia.org/wiki/Partition_(number_theory)#
>In number theory and combinatorics, a partition of a positive integer *n*, also called an *integer parti... | import functools
@functools.lru_cache(1 << 16)
def f(n, m):
if n == 0:
return 1
return sum(f(n - i, i) for i in range(1, min(n, m)+1))
def exp_sum(n):
return f(n, n) | python | train | abovesol | codeparrot/apps | all |
Solve in Python:
A tree is an undirected connected graph without cycles. The distance between two vertices is the number of edges in a simple path between them.
Limak is a little polar bear. He lives in a tree that consists of n vertices, numbered 1 through n.
Limak recently learned how to jump. He can jump from a ve... | """
#If FastIO not needed, used this and don't forget to strip
#import sys, math
#input = sys.stdin.readline
"""
import os
import sys
from io import BytesIO, IOBase
import heapq as h
from bisect import bisect_left, bisect_right
from types import GeneratorType
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
... | python | test | qsol | codeparrot/apps | all |
I found an interesting problem on https://atcoder.jp/contests/abc046/tasks/abc046_a:
AtCoDeer the deer recently bought three paint cans.
The color of the one he bought two days ago is a, the color of the one he bought yesterday is b, and the color of the one he bought today is c.
Here, the color of each paint can is re... | penki=list(map(int,input().split()))
ans=len(set(penki))
print(ans) | python | test | abovesol | codeparrot/apps | all |
Solve in Python:
Bob watches TV every day. He always sets the volume of his TV to $b$. However, today he is angry to find out someone has changed the volume to $a$. Of course, Bob has a remote control that can change the volume.
There are six buttons ($-5, -2, -1, +1, +2, +5$) on the control, which in one press can ei... | T = int(input())
for _ in range(T):
a, b = map(int, input().split())
d = abs(a - b)
ans = (d // 5)
d = d % 5
if d == 1 or d == 2:
ans += 1
if d == 3 or d == 4:
ans += 2
print(ans) | python | train | qsol | codeparrot/apps | all |
I found an interesting problem on https://www.codewars.com/kata/5993e6f701726f0998000030:
# Disclaimer
This Kata is an insane step-up from [GiacomoSorbi's Kata](https://www.codewars.com/kata/total-increasing-or-decreasing-numbers-up-to-a-power-of-10/python),
so I recommend to solve it first before trying this one.
# ... | from functools import reduce
from operator import mul
def insane_inc_or_dec(x):
return (reduce(mul,[x + i + i * (i == 10) for i in range(1, 11)]) // 3628800 - 10 * x - 2) % 12345787 | python | train | abovesol | codeparrot/apps | all |
I found an interesting problem on https://leetcode.com/problems/sequential-digits/:
An integer has sequential digits if and only if each digit in the number is one more than the previous digit.
Return a sorted list of all the integers in the range [low, high] inclusive that have sequential digits.
Example 1:
Input: l... | class Solution:
def sequentialDigits(self, low: int, high: int) -> List[int]:
nums = []
max_digits = 9
for depth in range(2, max_digits + 1):
nums += self.genNum(max_digits, depth)
return [n for n in nums if n >= low and n <= high]
def genNum(self, max_digits, de... | python | train | abovesol | codeparrot/apps | all |
I found an interesting problem on https://atcoder.jp/contests/abc116/tasks/abc116_d:
There are N pieces of sushi. Each piece has two parameters: "kind of topping" t_i and "deliciousness" d_i.
You are choosing K among these N pieces to eat.
Your "satisfaction" here will be calculated as follows:
- The satisfaction is t... | n,k=list(map(int,input().split()))
td=sorted([list(map(int,input().split())) for i in range(n)],reverse=True,key=lambda x:x[1])
ans=0
kl=dict()
for i in range(k):
ans+=td[i][1]
if td[i][0] in kl:
kl[td[i][0]]+=1
else:
kl[td[i][0]]=1
l=len(kl)
ans+=(l**2)
ans_=ans
now=k-1
for i in range(k,n)... | python | test | abovesol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/1191/B:
Tokitsukaze is playing a game derivated from Japanese mahjong. In this game, she has three tiles in her hand. Each tile she owns is a suited tile, which means it has a suit (manzu, pinzu or souzu) and a number (a digit ranged from $1$ t... | t = input().split()
t.sort()
if t.count(t[0]) == 3:
print('0')
elif t.count(t[0]) == 2 or t.count(t[1]) == 2:
print('1')
else:
num = list(map(int, [t[0][0], t[1][0], t[2][0]]))
suit = [t[0][1], t[1][1], t[2][1]]
if len(set(suit)) == 3:
print('2')
elif len(set(suit)) == 1:
if num[1] == num[0] + 1 o... | python | test | abovesol | codeparrot/apps | all |
Solve in Python:
#### Task:
Your job here is to implement a method, `approx_root` in Ruby/Python/Crystal and `approxRoot` in JavaScript/CoffeeScript, that takes one argument, `n`, and returns the approximate square root of that number, rounded to the nearest hundredth and computed in the following manner.
1. Sta... | def approx_root(n):
base = int(n ** 0.5)
diff_gn = n - base ** 2
diff_lg = base * 2 + 1
return round(base + diff_gn / diff_lg, 2) | python | train | qsol | codeparrot/apps | all |
Solve in Python:
Sereja has got an array, consisting of n integers, a_1, a_2, ..., a_{n}. Sereja is an active boy, so he is now going to complete m operations. Each operation will have one of the three forms: Make v_{i}-th array element equal to x_{i}. In other words, perform the assignment a_{v}_{i} = x_{i}. Increas... | import sys
n,m=list(map(int,sys.stdin.readline().split()))
L=list(map(int,sys.stdin.readline().split()))
c=0
Ans=""
for i in range(m):
x=list(map(int,sys.stdin.readline().split()))
if(x[0]==1):
L[x[1]-1]=x[2]-c
elif(x[0]==2):
c+=x[1]
else:
Ans+=str(L[x[1]-1]+c)+"\n"
sys.stdout.w... | python | test | qsol | codeparrot/apps | all |
Solve in Python:
Alena has successfully passed the entrance exams to the university and is now looking forward to start studying.
One two-hour lesson at the Russian university is traditionally called a pair, it lasts for two academic hours (an academic hour is equal to 45 minutes).
The University works in such a way ... | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import re
N = int(input())
S = input()
S = S.replace(" ", "")
S = S.strip("0")
ret = 0
for seg in re.split("00+", S):
ret += len(seg)
print(ret) | python | test | qsol | codeparrot/apps | all |
Solve in Python:
-----Problem Statement-----
Chef studies combinatorics. He tries to group objects by their rang (a positive integer associated with each object). He also gives the formula for calculating the number of different objects with rang N as following:
the number of different objects with rang N = F(N) = A0 ... | # cook your dish here
import sys
mod_val = 1000000007
rang = [0]*101
pow_cache = [0]*102
multisets = {}
def mod_pow(base, pow):
result = 1
while pow:
if pow&1:
result = (result*base) % mod_val
base = (base*base) % mod_val
pow = pow>>1
return result
def precalculate():
for i in range(1, 102):
pow_ca... | python | train | qsol | codeparrot/apps | all |
Solve in Python:
Chef has a number N, Cheffina challenges the chef to check the divisibility of all the permutation of N by 2. If any of the permutations is divisible by 2 then print 1 else print 0.
-----Input:-----
- First-line will contain $T$, the number of test cases. Then the test cases follow.
- Each test case ... | for _ in range(int(input())):
r=int(input())
while(r!=0):
k=r%10
if(k%2==0):
print("1")
break
r=r//10
else:
print("0") | python | train | qsol | codeparrot/apps | all |
I found an interesting problem on https://atcoder.jp/contests/abc059/tasks/arc072_b:
Alice and Brown loves games. Today, they will play the following game.
In this game, there are two piles initially consisting of X and Y stones, respectively.
Alice and Bob alternately perform the following operation, starting from Ali... | # 解説AC
X,Y = map(int, input().split())
print("Alice" if abs(X - Y) > 1 else "Brown") | python | test | abovesol | codeparrot/apps | all |
Solve in Python:
For an integer N, we will choose a permutation \{P_1, P_2, ..., P_N\} of \{1, 2, ..., N\}.
Then, for each i=1,2,...,N, let M_i be the remainder when i is divided by P_i.
Find the maximum possible value of M_1 + M_2 + \cdots + M_N.
-----Constraints-----
- N is an integer satisfying 1 \leq N \leq 10^9.... | n=int(input())
print((n*(n-1)//2)) | python | test | qsol | codeparrot/apps | all |
I found an interesting problem on https://www.hackerrank.com/challenges/py-if-else/problem:
=====Problem Statement=====
Given an integer, n, perform the following conditional actions:
If n is odd, print Weird
If n is even and in the inclusive range of 2 to 5, print Not Weird
If n is even and in the inclusive range of 6... | def __starting_point():
n = int(input())
if n % 2 == 1 or 6 <= n <= 20:
print("Weird")
else:
print("Not Weird")
__starting_point() | python | test | abovesol | codeparrot/apps | all |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.