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/1096/E:
Hasan loves playing games and has recently discovered a game called TopScore. In this soccer-like game there are $p$ players doing penalty shoot-outs. Winner is the one who scores the most. In case of ties, one of the top-scorers will b... | base=998244353;
def power(x, y):
if(y==0):
return 1
t=power(x, y//2)
t=(t*t)%base
if(y%2):
t=(t*x)%base
return t;
def inverse(x):
return power(x, base-2)
f=[1]
iv=[1]
for i in range(1, 5555):
f.append((f[i-1]*i)%base)
iv.append(inverse(f[i]))
def C(n, k):
return (f[n]... | python | test | abovesol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/342/A:
Xenia the mathematician has a sequence consisting of n (n is divisible by 3) positive integers, each of them is at most 7. She wants to split the sequence into groups of three so that for each group of three a, b, c the following conditi... | a=[0 for i in range(8)]
N=int(input())
b=list(map(int, input().split()))
for k in range(N):
a[b[k-1]]=a[b[k-1]]+1;
if a[5] or a[7]:
print(-1)
return
A,C=a[4],a[3]
B=a[6]-C
if A>=0 and B>=0 and C>=0 and A+B==a[2] and A+B+C==a[1]:
for i in range(A):
print("1 2 4")
for i in range(B):
pr... | python | test | abovesol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/1056/D:
There is one apple tree in Arkady's garden. It can be represented as a set of junctions connected with branches so that there is only one way to reach any junctions from any other one using branches. The junctions are enumerated from $1... | # -*- coding:utf-8 -*-
"""
created by shuangquan.huang at 12/14/18
"""
import collections
import sys
N = int(input())
p = [int(x) for x in input().split()]
G = collections.defaultdict(list)
for i, v in enumerate(p):
u = i + 2
G[u].append(v)
G[v].append(u)
root = 1
colors = [0] * (N + 1)
counts = [... | python | test | abovesol | codeparrot/apps | all |
Solve in Python:
You are given two strings a and b. You have to remove the minimum possible number of consecutive (standing one after another) characters from string b in such a way that it becomes a subsequence of string a. It can happen that you will not need to remove any characters at all, or maybe you will have to... | #import sys
#sys.stdin = open('in', 'r')
#n = int(input())
#a = [int(x) for x in input().split()]
#n,m = map(int, input().split())
s1 = input()
s2 = input()
l1 = len(s1)
l2 = len(s2)
dl = {}
dr = {}
i1 = 0
i2 = 0
while i1 < l1 and i2 < l2:
while i1 < l1 and s1[i1] != s2[i2]:
i1 += 1
if i1 < l1:
... | python | test | qsol | codeparrot/apps | all |
I found an interesting problem on https://www.codechef.com/problems/LEMOUSE:
It is well-known that the elephants are afraid of mouses. The Little Elephant from the Zoo of Lviv is not an exception.
The Little Elephant is on a board A of n rows and m columns (0-based numeration). At the beginning he is in cell with coor... | from collections import defaultdict
from itertools import product
def solve(mouse,n,m):
# shadow matrix will contains the count of mice which affect (i,j) position
# if there is a mice at position (i,j) then in shadow matrix it will affect all four adjacent blocks
shadow=[[0 for i in range(m)]for j in ra... | python | train | abovesol | codeparrot/apps | all |
I found an interesting problem on https://www.codewars.com/kata/54b72c16cd7f5154e9000457:
Part of Series 2/3
This kata is part of a series on the Morse code. Make sure you solve the [previous part](/kata/decode-the-morse-code) before you try this one. After you solve this kata, you may move to the [next one](/kata/de... | from re import split
def decodeBits(bits):
unit = min([len(s) for s in split(r'0+',bits.strip('0'))] + [len(s) for s in split(r'1+',bits.strip('0')) if s != ''])
return bits.replace('0'*unit*7,' ').replace('0'*unit*3,' ').replace('1'*unit*3,'-').replace('1'*unit,'.').replace('0','')
def decodeMorse(morseCode... | python | train | abovesol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/1249/B1:
The only difference between easy and hard versions is constraints.
There are $n$ kids, each of them is reading a unique book. At the end of any day, the $i$-th kid will give his book to the $p_i$-th kid (in case of $i = p_i$ the kid w... | tc = int(input())
while tc > 0:
tc -= 1
n = int(input())
p = [0] + list(map(int, input().split()))
ans = [0] * (n + 1)
mk = [False] * (n + 1)
for i in range(1 , n + 1):
if not mk[i]:
sz = 1
curr = p[i]
mk[i] = True
while curr != i:
sz += 1
mk[curr] = True
curr = p[curr]
ans[i] = s... | python | test | abovesol | codeparrot/apps | all |
Solve in Python:
Codehorses has just hosted the second Codehorses Cup. This year, the same as the previous one, organizers are giving T-shirts for the winners.
The valid sizes of T-shirts are either "M" or from $0$ to $3$ "X" followed by "S" or "L". For example, sizes "M", "XXS", "L", "XXXL" are valid and "XM", "Z", "... | n = int(input())
a = []
b = []
for i in range(n):
a.append(input())
for i in range(n):
k = input()
if k in a:
a.remove(k)
else:
b.append(k)
c = [0,0,0,0]
for i in range(len(a)):
c[len(a[i])-1] += 1
print(sum(c)) | python | test | qsol | codeparrot/apps | all |
I found an interesting problem on https://atcoder.jp/contests/abc109/tasks/abc109_c:
There are N cities on a number line. The i-th city is located at coordinate x_i.
Your objective is to visit all these cities at least once.
In order to do so, you will first set a positive integer D.
Then, you will depart from coordina... | n,x = [int(x) for x in input().split()]
a = [int(x) for x in input().split()]
for i in range(n):
a[i] = abs(a[i] - x)
def gcd(x,y):
while y != 0:
x, y = y, x % y
return x
res = a[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/611/C:
They say "years are like dominoes, tumbling one after the other". But would a year fit into a grid? I don't think so.
Limak is a little polar bear who loves to play. He has recently got a rectangular grid with h rows and w columns. Each... | h, w = list(map(int, input().split()))
field = [[c == "." for c in input()] + [False] for i in range(h)]
field.append([False] * (w + 1))
subVerts = [[0] * (w + 1) for i in range(h + 1)]
subHoriz = [[0] * (w + 1) for i in range(h + 1)]
for y in range(h):
subVerts[y][0] = 0
subHoriz[y][0] = 0
for x in range(w)... | python | test | abovesol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/285/E:
Permutation p is an ordered set of integers p_1, p_2, ..., p_{n}, consisting of n distinct positive integers, each of them doesn't exceed n. We'll denote the i-th element of permutation p as p_{i}. We'll call number n the size or the ... | mod=10**9+7
n,k=list(map(int,input().split()))
A=[0]*(n+1)
B=[0]*(n+1)
C=[0]*(n+1)
F=[0]*(n+1)
G=[0]*(n+1)
F[0]=G[0]=1
for i in range(1,n+1):
G[i]=F[i]=F[i-1]*i%mod
G[i]=pow(F[i],(mod-2),mod)
for i in range(0,n):
if i*2>n:
break
B[i]=(F[n-i]*G[i]*G[n-i*2])%mod
for i in range(0,n//2+1):
for j in range(0,n//2+1... | python | test | abovesol | codeparrot/apps | all |
I found an interesting problem on https://www.codechef.com/SPRT2020/problems/STCKSCAM:
$Harshad$ $Mehta$ is planning a new scam with the stocks he is given a stock of integer price S and a number K . $harshad$ has got the power to change the number $S$ at most $K$ times
In order to raise the price of stock and now ca... | # cook your dish here
n,k = map(int, input().split())
n = str(n)
for i in range(len(n)):
if(k == 0):
break
if(n[i]!='9'):
n = n[:i]+'9'+n[i+1:]
k-=1
print(n) | python | train | abovesol | codeparrot/apps | all |
I found an interesting problem on https://leetcode.com/problems/find-words-that-can-be-formed-by-characters/:
You are given an array of strings words and a string chars.
A string is good if it can be formed by characters from chars (each character can only be used once).
Return the sum of lengths of all good strings in... | class Solution:
def countCharacters(self, words: List[str], chars: str) -> int:
charChars = Counter(chars)
counter = 0
for word in words:
countC = Counter(word)
count = 0
for letter in countC.items():
if letter[0] in charChars and charChars... | python | train | abovesol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/1372/B:
In Omkar's last class of math, he learned about the least common multiple, or $LCM$. $LCM(a, b)$ is the smallest positive integer $x$ which is divisible by both $a$ and $b$.
Omkar, having a laudably curious mind, immediately thought of... | import math
from collections import deque
from sys import stdin, stdout
input = stdin.readline
#print = stdout.write
for _ in range(int(input())):
x = int(input())
ind = 2
mn = 99999999999999
while ind * ind <= x:
if x % ind == 0:
mn = min(mn, ind)
mn = min(mn, x // ind... | python | test | abovesol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/1225/E:
You are at the top left cell $(1, 1)$ of an $n \times m$ labyrinth. Your goal is to get to the bottom right cell $(n, m)$. You can only move right or down, one cell per step. Moving right from a cell $(x, y)$ takes you to the cell $(x, ... | def getSum(dp, pos, s, e, type_):
if e < s:
return 0
if type_=='D':
if e==m-1:
return dp[pos][s]
return dp[pos][s]-dp[pos][e+1]
else:
if e==n-1:
return dp[s][pos]
return dp[s][pos]-dp[e+1][pos]
mod = 10**9+7
n, m = map(int, input(... | python | train | abovesol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/767/A:
According to an old legeng, a long time ago Ankh-Morpork residents did something wrong to miss Fortune, and she cursed them. She said that at some time n snacks of distinct sizes will fall on the city, and the residents should build a Sn... | n = int(input())
maxsn = n-1
a = list(map(int, input().split()))
snacks = [0] * 100001
for i in range(n):
snacks[a[i]-1] = 1
while snacks[maxsn] == 1:
snacks[maxsn] = 0
print(maxsn + 1, end=' ')
maxsn -= 1
print() | python | test | abovesol | codeparrot/apps | all |
Solve in Python:
Iahub is a big fan of tourists. He wants to become a tourist himself, so he planned a trip. There are n destinations on a straight road that Iahub wants to visit. Iahub starts the excursion from kilometer 0. The n destinations are described by a non-negative integers sequence a_1, a_2, ..., a_{n}. The ... | import math
n = int(input())
a = list(map(int, input().split()))
a.sort(reverse = True)
k = 0
s1 = 0
s2 = 0
for i in a:
s2 += s1 - k * i
s1 += i
k += 1
s2 *= 2
s2 += sum(a)
gcd = math.gcd(s2, n)
print(s2 // gcd, n // gcd) | python | test | qsol | codeparrot/apps | all |
Solve in Python:
An acrostic is a text in which the first letter of each line spells out a word. It is also a quick and cheap way of writing a poem for somebody, as exemplified below :
Write a program that reads an acrostic to identify the "hidden" word. Specifically, your program will receive a list of words (repre... | def read_out(acrostic):
return "".join( word[0] for word in acrostic ) | python | train | qsol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/1342/E:
Calculate the number of ways to place $n$ rooks on $n \times n$ chessboard so that both following conditions are met:
each empty cell is under attack; exactly $k$ pairs of rooks attack each other.
An empty cell is under attack if ... | def modpow(b, e, mod):
ret = 1
pw = b
while e > 0:
if e % 2 == 1: ret = (ret * pw) % mod
e = e >> 1
pw = (pw * pw) % mod
return ret
n, k = list(map(int, input().split()))
mod = 998244353
inv = [0 for _ in range(n + 1)]
fac = [0 for _ in range(n + 1)]
fac[0] = inv[0] = 1
for i i... | python | test | abovesol | codeparrot/apps | all |
Solve in Python:
You are given a chess board with $n$ rows and $n$ columns. Initially all cells of the board are empty, and you have to put a white or a black knight into each cell of the board.
A knight is a chess piece that can attack a piece in cell ($x_2$, $y_2$) from the cell ($x_1$, $y_1$) if one of the followin... | n = int(input())
mat = [[0 for i in range(n)] for j in range(n)]
for i in range(n):
for j in range(n):
if (i + j) % 2 == 1:
mat[i][j] = 'W'
else:
mat[i][j] = 'B'
for i in range(n):
for j in range(n):
if j < n-1:
print(mat[i][j], end = "")
else:
print(mat[i][j]) | python | test | qsol | codeparrot/apps | all |
Solve in Python:
Bobby has decided to hunt some Parrots. There are n horizontal branch of trees aligned parallel to each other. Branches are numbered 1 to n from top to bottom. On each branch there are some parrots sitting next to each other. Supposed there are a[i]$a[i]$ parrots sitting on the i−th$ i-th$ branch.
So... | n = int(input())
A = list(map(int, input().split()))
m = int(input())
for _ in range(m):
x, y = map(int, input().split())
x -= 1
y -= 1
left = y
right = A[x] - left - 1
A[x] = 0
if x - 1 >= 0:
A[x - 1] += left
if x + 1 < n:
A[x + 1] += right
for a in A:
... | python | train | qsol | codeparrot/apps | all |
Solve in Python:
=====Problem Statement=====
Mr. Anant Asankhya is the manager at the INFINITE hotel. The hotel has an infinite amount of rooms.
One fine day, a finite number of tourists come to stay at the hotel.
The tourists consist of:
→ A Captain.
→ An unknown group of families consisting of K members per group wh... | #!/usr/bin/env python3
def __starting_point():
k = int(input().strip())
numbers = list(map(int, input().strip().split(' ')))
print((sum(set(numbers))*k - sum(numbers))//(k-1))
__starting_point() | python | train | qsol | codeparrot/apps | all |
Solve in Python:
There is a knight - the chess piece - at the origin (0, 0) of a two-dimensional grid.
When the knight is at the square (i, j), it can be moved to either (i+1,j+2) or (i+2, j+1).
In how many ways can the knight reach the square (X, Y)?
Find the number of ways modulo 10^9 + 7.
-----Constraints-----
- 1... | X,Y = map(int,input().split())
mod = 10**9+7
N = (X+Y)//3
M = (N+X-Y)//2
if (X+Y)%3!=0 or M<0 or N<M:
print(0)
else:
ans = 1
for m in range(1,M+1):
ans*=(N-M+m)*pow(m,mod-2,mod)
ans%=mod
print(ans) | python | test | qsol | codeparrot/apps | all |
I found an interesting problem on https://atcoder.jp/contests/arc094/tasks/arc094_b:
10^{10^{10}} participants, including Takahashi, competed in two programming contests.
In each contest, all participants had distinct ranks from first through 10^{10^{10}}-th.
The score of a participant is the product of his/her ranks i... | n = int(input())
for i in range(n):
a,b= list(map(int, input().split( )))
#解説参照
#何度見ても解けない
#どちらかは高橋君より良い
#a<=bとする
#a=b (1~a-1)*2
#a<b c**2<abとする
#c(c+1)>=ab?2c-2 / 2c-1
if a==b:
print((2*a-2))
else:
c = int((a*b)**(1/2))
if c*c==a*b:
c -= 1
... | python | train | abovesol | codeparrot/apps | all |
I found an interesting problem on https://www.codechef.com/problems/TRACE:
Chef is learning linear algebra. Recently, he learnt that for a square matrix $M$, $\mathop{\rm trace}(M)$ is defined as the sum of all elements on the main diagonal of $M$ (an element lies on the main diagonal if its row index and column index ... | # cook your dish here
for i in range(int(input())):
h = int(input())
f = []
ans = []
for j in range(0,h):
f.append(list(map(int,input().split())))
for k in range(0,h):
sum1 = 0
sum2 = 0
for l in range(0,k+1):
sum1 += f[l][h+l-k-1]
sum2 += f[h+l-k-1][l]
ans.append(sum1)
ans.append(sum2)
... | python | train | abovesol | codeparrot/apps | all |
I found an interesting problem on https://www.codewars.com/kata/59e1254d0863c7808d0000ef:
# Fourier transformations are hard. Fouriest transformations are harder.
This Kata is based on the SMBC Comic on fourier transformations.
A fourier transformation on a number is one that converts the number to a base in which it... | def change_base(n, b):
result = ''
while n > 0:
rem = n % b if n % b <=9 else 'x'
result = str(rem) + result
n //= b
return result
def fouriest(n):
bb, br = None, 0
for i in range(2, n):
res = list(change_base(n, i))
nf = res.count('4')
if br ... | python | train | abovesol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/1419/A:
Everyone knows that agents in Valorant decide, who will play as attackers, and who will play as defenders. To do that Raze and Breach decided to play $t$ matches of a digit game...
In each of $t$ matches of the digit game, a positive i... | for _ in range(int(input())):
n=int(input())
s=input()
if n%2==1:
a=[int(i)%2 for i in s[::2]]
if 1 in a:print(1)
else:print(2)
else:
a=[int(i)%2 for i in s[1::2]]
if 0 in a:print(2)
else:print(1) | python | test | abovesol | codeparrot/apps | all |
Solve in Python:
This is a hard version of the problem. The actual problems are different, but the easy version is almost a subtask of the hard version. Note that the constraints and the output format are different.
You are given a string $s$ consisting of $n$ lowercase Latin letters.
You have to color all its charac... | import sys
# inf = open('input.txt', 'r')
# reader = (line.rstrip() for line in inf)
reader = (line.rstrip() for line in sys.stdin)
input = reader.__next__
def ceil(tails, L, R, key):
while L + 1 < R:
m = (L + R) // 2
if key < tails[m]:
L = m
else:
R = m
re... | python | test | qsol | codeparrot/apps | all |
Solve in Python:
A grammar is a set of rules that let us define a language. These are called **production rules** and can be derived into many different tools. One of them is **String Rewriting Systems** (also called Semi-Thue Systems or Markov Algorithms). Ignoring technical details, they are a set of rules that subst... | from collections import defaultdict
def word_problem(rules, from_str, to_str, applications):
d = defaultdict(list)
for x, y in rules:
d[y].append(x)
b, visited = False, set()
def dfs(s, p=0):
nonlocal b
if s == from_str:
b = p <= applications
return
... | python | train | qsol | codeparrot/apps | all |
I found an interesting problem on https://www.codewars.com/kata/5536aba6e4609cc6a600003d:
Once upon a time, a CodeWarrior, after reading a [discussion on what can be the plural](http://www.codewars.com/kata/plural/discuss/javascript), took a look at [this page](http://en.wikipedia.org/wiki/Grammatical_number#Types_of_n... | import re
from functools import partial
def convert(match):
n, s = match.groups()
n = int(n)
if n == 0 or n == 1:
return match.group()
elif n == 2:
return "2 bu{}".format(s[:-1])
elif 3 <= n <= 9 :
return "{} {}zo".format(n, s[:-1])
else:
return "{} ga{}ga".forma... | python | train | abovesol | codeparrot/apps | all |
Solve in Python:
You are given a forest — an undirected graph with $n$ vertices such that each its connected component is a tree.
The diameter (aka "longest shortest path") of a connected undirected graph is the maximum number of edges in the shortest path between any pair of its vertices.
You task is to add some edg... | import math
n,m=map(int,input().split())
neigh=[]
for i in range(n):
neigh.append([])
for i in range(m):
a,b=map(int,input().split())
neigh[a-1].append(b-1)
neigh[b-1].append(a-1)
seen=set()
index=[0]*n
diams=[]
trees=0
for i in range(n):
if i not in seen:
trees+=1
index[i]=trees
... | python | test | qsol | codeparrot/apps | all |
Solve in Python:
Polycarpus loves lucky numbers. Everybody knows that lucky numbers are positive integers, whose decimal representation (without leading zeroes) contain only the lucky digits x and y. For example, if x = 4, and y = 7, then numbers 47, 744, 4 are lucky.
Let's call a positive integer a undoubtedly lucky,... | def cnt(s, p):
ans = 0
if p > s: ans = 0
elif len(p) == len(s):
ans = 1 if len(set(p.lstrip('0'))) <= 2 else 0
elif len(set(p.lstrip('0'))) > 2: ans = 0
elif s[:len(p)] > p:
if len(set(p.lstrip('0'))) == 2:
ans = 2**(len(s)-len(p))
elif len(set(p.lstrip('... | python | test | qsol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/1217/B:
You are fighting with Zmei Gorynich — a ferocious monster from Slavic myths, a huge dragon-like reptile with multiple heads!
$m$
Initially Zmei Gorynich has $x$ heads. You can deal $n$ types of blows. If you deal a blow of the $i$-... | from bisect import bisect_left as bl
from collections import defaultdict as dd
for _ in range(int(input())):
n, x = [int(i) for i in input().split()]
l = []
f = dd(int)
for j in range(n):
d, h = [int(i) for i in input().split()]
l.append(d - h)
f[d] = 1
#print(n, x)
l.sort(reverse = 1)
#print(l)
ans = 1... | python | test | abovesol | codeparrot/apps | all |
Solve in Python:
When a warrior wants to talk with another one about peace or war he uses a smartphone. In one distinct country warriors who spent all time in training kata not always have enough money. So if they call some number they want to know which operator serves this number.
Write a function which **accept... | r = dict(__import__("re").findall(r"(\d{3}).*-\s(.+)",
"""
039 xxx xx xx - Golden Telecom
050 xxx xx xx - MTS
063 xxx xx xx - Life:)
066 xxx xx xx - MTS
067 xxx xx xx - Kyivstar
068 xxx xx xx - Beeline
093 xxx xx xx - Life:)
095 xxx xx xx - MTS
... | python | train | qsol | codeparrot/apps | all |
Solve in Python:
Dima and Inna are doing so great! At the moment, Inna is sitting on the magic lawn playing with a pink pony. Dima wanted to play too. He brought an n × m chessboard, a very tasty candy and two numbers a and b.
Dima put the chessboard in front of Inna and placed the candy in position (i, j) on the boar... | #import math
#n, m = input().split()
#n = int (n)
#m = int (m)
#n, m, k= input().split()
#n = int (n)
#m = int (m)
#k = int (k)
#l = int(l)
#m = int(input())
#s = input()
##t = input()
#a = list(map(char, input().split()))
#a.append('.')
#print(l)
#a = list(map(int, input().split()))
#c = sorted(c)
#x1, y1, x2, y2 =map... | python | test | qsol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/1075/B:
Palo Alto is an unusual city because it is an endless coordinate line. It is also known for the office of Lyft Level 5.
Lyft has become so popular so that it is now used by all $m$ taxi drivers in the city, who every day transport the ... | n, m = map(int, input().split())
dist = list(map(int, input().split()))
taxists = list(map(int, input().split()))
left = [0] * (n + m)
right = [0] * (n + m)
MAX = 10000000000000000000
value = -MAX
cnt = 0
for i in range(n + m):
if taxists[i] == 1:
cnt += 1
value = i
left[i] = value
value = MAX
... | python | test | abovesol | codeparrot/apps | all |
Solve in Python:
Takahashi is going to buy N items one by one.
The price of the i-th item he buys is A_i yen (the currency of Japan).
He has M discount tickets, and he can use any number of them when buying an item.
If Y tickets are used when buying an item priced X yen, he can get the item for \frac{X}{2^Y} (rounded d... | import heapq
N, M = [int(_) for _ in input().split()]
A = [int(_) * -1 for _ in input().split()]
heapq.heapify(A)
for i in range(M):
a = heapq.heappop(A) * -1
heapq.heappush(A, (-1)*(a//2))
print(((-1) * sum(A))) | python | test | qsol | codeparrot/apps | all |
Solve in Python:
Piegirl found the red button. You have one last chance to change the inevitable end.
The circuit under the button consists of n nodes, numbered from 0 to n - 1. In order to deactivate the button, the n nodes must be disarmed in a particular order. Node 0 must be disarmed first. After disarming node i,... | # METO Bot 0.9.9
n=int(input())
if n&1:
print(-1)
else:
D,R=[False]*(10**6),[0]*(10**6)
i,j=0,0
while True:
D[j]=True
R[i]=j
i+=1
if not D[(j+n)>>1]:
j=(j+n)>>1
elif not D[j>>1]:
j=j>>1
else:
break
print(" ".join(str(R[i]) for i in range(n,-1,-1))) | python | test | qsol | codeparrot/apps | all |
Solve in Python:
The professional Russian, Dmitri, from the popular youtube channel FPSRussia has hired you to help him move his arms cache between locations without detection by the authorities. Your job is to write a Shortest Path First (SPF) algorithm that will provide a route with the shortest possible travel time... | def shortestPath(topology, startPoint, endPoint):
graph = {}
for key, value in topology.items():
values=[]
for k, v in value.items():
values.append(k)
graph[key]=values
paths=find_all_paths(graph, startPoint, endPoint)
if len(paths)==0:
return []
... | python | train | qsol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/868/A:
As technologies develop, manufacturers are making the process of unlocking a phone as user-friendly as possible. To unlock its new phone, Arkady's pet dog Mu-mu has to bark the password once. The phone represents a password as a string o... | import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,copy,functools
sys.setrecursionlimit(10**7)
inf = 10**20
eps = 1.0 / 10**15
mod = 10**9+7
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF()... | python | train | abovesol | codeparrot/apps | all |
I found an interesting problem on https://www.codewars.com/kata/5a15a4db06d5b6d33c000018:
Implement a function to calculate the sum of the numerical values in a nested list. For example :
```python
sum_nested([1, [2, [3, [4]]]]) -> 10
```
I tried it in Python, but could not do it. Can you solve it? | def sum_nested(L):
if L == []:
return 0
if type(L[0]) == int:
if len(L) == 1:
return L[0]
else:
return L[0]+sum_nested(L[1:])
else:
return sum_nested(L[0])+sum_nested(L[1:])
#the sum of every numerical value in the list and its sublists | python | train | abovesol | codeparrot/apps | all |
I found an interesting problem on https://www.codewars.com/kata/56f6380a690784f96e00045d:
Alice, Samantha, and Patricia are relaxing on the porch, when Alice suddenly says: _"I'm thinking of two numbers, both greater than or equal to 2. I shall tell Samantha the sum of the two numbers and Patricia the product of the tw... | primes=[2,3,5,7,11,13,17,19,23,29,31]
for i in range(37,500,2):
if all(i%j for j in primes): primes.append(i)
def statement1(s): return s%2 and s-2 not in primes
def statement2(p):
possible_pairs=set()
for i in range(2,int(p**.5)+2):
if p%i==0:
possible_pairs.add((i,p//i))
good_pai... | python | train | abovesol | codeparrot/apps | all |
Solve in Python:
Beroffice text editor has a wide range of features that help working with text. One of the features is an automatic search for typos and suggestions of how to fix them.
Beroffice works only with small English letters (i.e. with 26 letters from a to z). Beroffice thinks that a word is typed with a typo... | s = input()
j = 0
a = ['a', 'e', 'i', 'o', 'u']
for i in range(len(s)):
if (j > 1):
if not(s[i] in a):
if (not(s[i-1] in a) and not(s[i-2] in a) and not(s[i] == s[i-1] == s[i-2])):
print(" ", end = '')
j = 0
j += 1
print(s[i], end = '') | python | test | qsol | codeparrot/apps | all |
Solve in Python:
Print an ordered cross table of a round robin tournament that looks like this:
```
# Player 1 2 3 4 5 6 7 8 9 10 11 12 13 14 Pts SB
==========================================================================
1 Nash King 1 0 = 1 0 = 1 1 0 1 1 1 0 8.0 52... | def crosstable(players, scores):
points, le = {j:sum(k or 0 for k in scores[i]) for i, j in enumerate(players)}, len(players)
SB = {j:sum(points[players[k]] / ([1, 2][l == 0.5]) for k, l in enumerate(scores[i]) if l) for i, j in enumerate(players)}
SORTED, li = [[i, players.index(i)] for i in sorted(player... | python | train | qsol | codeparrot/apps | all |
I found an interesting problem on https://www.codewars.com/kata/5a00a8b5ffe75f8888000080:
Given an array containing only zeros and ones, find the index of the zero that, if converted to one, will make the longest sequence of ones.
For instance, given the array:
```
[1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, 0, ... | def replace_zero(arr):
labels=[]
max=1
ans=-1
# find all the indices that correspond to zero values
for i in range(len(arr)):
if arr[i]==0:
labels.append(i)
# try each index and compute the associated length
for j in range(len(labels)):
arr[labels[j]]=1
co... | python | train | abovesol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/868/C:
Snark and Philip are preparing the problemset for the upcoming pre-qualification round for semi-quarter-finals. They have a bank of n problems, and they want to select any non-empty subset of it as a problemset.
k experienced teams are ... | def test(masks, wanted):
for w in wanted:
if w not in masks:
return False
return True
def any_test(masks, tests):
for t in tests:
if test(masks, t):
return True
return False
def inflate(perm):
count = max(perm)
masks = [[0 for i in range(len(perm))] for ... | python | test | abovesol | codeparrot/apps | all |
Solve in Python:
We have N logs of lengths A_1,A_2,\cdots A_N.
We can cut these logs at most K times in total. When a log of length L is cut at a point whose distance from an end of the log is t (0<t<L), it becomes two logs of lengths t and L-t.
Find the shortest possible length of the longest log after at most K cuts,... | from collections import defaultdict
from collections import deque
from collections import Counter
import math
def readInt():
return int(input())
def readInts():
return list(map(int, input().split()))
def readChar():
return input()
def readChars():
return input().split()
n,k = readInts()
a = readInts()
a.sort(rev... | python | test | qsol | codeparrot/apps | all |
I found an interesting problem on https://www.codewars.com/kata/5b715fd11db5ce5912000019:
Ronny the robot is watching someone perform the Cups and Balls magic trick. The magician has one ball and three cups, he shows Ronny which cup he hides the ball under (b), he then mixes all the cups around by performing multiple t... | def cup_and_balls(b, arr):
for switch in arr:
if b in switch:
b = sum(switch) - b
return b | python | train | abovesol | codeparrot/apps | all |
Solve in Python:
Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.
(i.e., [0,0,1,2,2,5,6] might become [2,5,6,0,0,1,2]).
You are given a target value to search. If found in the array return true, otherwise return false.
Example 1:
Input: nums = [2,5,6,0,0,1,2], target =... | class Solution:
def search(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: bool
"""
low = 0
high = len(nums)-1
while low<=high:
mid = (low+high)//2
if nums[mid]==target:
retur... | python | train | qsol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/734/A:
Anton likes to play chess, and so does his friend Danik.
Once they have played n games in a row. For each game it's known who was the winner — Anton or Danik. None of the games ended with a tie.
Now Anton wonders, who won more games, h... | input()
s = input()
if s.count('D') == s.count('A'):
print('Friendship') # is magic
else:
print(['Anton', 'Danik'][s.count('D') > s.count('A')]) | python | test | abovesol | codeparrot/apps | all |
Solve in Python:
You are given a rectangular field of n × m cells. Each cell is either empty or impassable (contains an obstacle). Empty cells are marked with '.', impassable cells are marked with '*'. Let's call two empty cells adjacent if they share a side.
Let's call a connected component any non-extendible set of ... | from sys import stdin,stdout
st=lambda:list(stdin.readline().strip())
li=lambda:list(map(int,stdin.readline().split()))
mp=lambda:list(map(int,stdin.readline().split()))
inp=lambda:int(stdin.readline())
pr=lambda n: stdout.write(str(n)+"\n")
def valid(x,y):
if x>=n or y>=m or x<0 or y<0:
return False
... | python | test | qsol | codeparrot/apps | all |
Solve in Python:
Implement pow(x, n), which calculates x raised to the power n (xn).
Example 1:
Input: 2.00000, 10
Output: 1024.00000
Example 2:
Input: 2.10000, 3
Output: 9.26100
Example 3:
Input: 2.00000, -2
Output: 0.25000
Explanation: 2-2 = 1/22 = 1/4 = 0.25
Note:
-100.0 < x < 100.0
n is... | class Solution:
def myPow(self, x, n):
"""
:type x: float
:type n: int
:rtype: float
"""
if n == 0 :
return 1.00000
if n < 0 :
return 1 / self.myPow(x , -n)
if n % 2 != 0 :
return x * self.myPow... | python | train | qsol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/1322/D:
A popular reality show is recruiting a new cast for the third season! $n$ candidates numbered from $1$ to $n$ have been interviewed. The candidate $i$ has aggressiveness level $l_i$, and recruiting this candidate will cost the show $s_i... | import sys
input = sys.stdin.readline
n,m=list(map(int,input().split()))
A=list(map(int,input().split()))
C=list(map(int,input().split()))
P=list(map(int,input().split()))
DP=[[-1<<30]*(n+1) for i in range(5001)]
# DP[k][cnt] = Aのmaxがkで, そういう人間がcnt人いるときのprofitの最大値
for i in range(5001):
DP[i][0]=0
for i in range... | python | test | abovesol | codeparrot/apps | all |
I found an interesting problem on https://www.codewars.com/kata/592915cc1fad49252f000006:
Write a function that accepts two parameters (a and b) and says whether a is smaller than, bigger than, or equal to b.
Here is an example code:
var noIfsNoButs = function (a,b) {
if(a > b) return a + " is greater than " + b
e... | def no_ifs_no_buts(a, b):
return ([
'%d is smaller than %d',
'%d is equal to %d',
'%d is greater than %d'
][int(a >= b) + int(a > b)] % (a, b)) | python | train | abovesol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/1249/F:
You are given a tree, which consists of $n$ vertices. Recall that a tree is a connected undirected graph without cycles. [Image] Example of a tree.
Vertices are numbered from $1$ to $n$. All vertices have weights, the weight of the v... | n, k = list(map(int, input().split()))
a = list(map(int, input().split()))
g = {}
def dfs(v, p=-1):
c = [dfs(child, v) for child in g.get(v, set()) - {p}]
c.sort(key=len, reverse=True)
r = []
i = 0
while c:
if i >= len(c[-1]):
c.pop()
else:
o = max(i, k - i - 1)
s = q = 0
for x in c:
if len(x)... | python | test | abovesol | codeparrot/apps | all |
I found an interesting problem on https://www.codewars.com/kata/574c5075d27783851800169e:
#Description
Everybody has probably heard of the animal heads and legs problem from the earlier years at school. It goes:
```“A farm contains chickens and cows. There are x heads and y legs. How many chickens and cows are there?... | def animals(heads, legs):
solution = (2 * heads - legs/2, legs/2 - heads)
return solution if legs % 2 == 0 and solution[0] >= 0 and solution[1] >= 0 else "No solutions" | python | train | abovesol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/1305/F:
Kuroni is very angry at the other setters for using him as a theme! As a punishment, he forced them to solve the following problem:
You have an array $a$ consisting of $n$ positive integers. An operation consists of choosing an element... | import random
n = int(input())
best = n
l = list(map(int, input().split()))
candidates = set()
candidates.add(2)
def gcd(x, y):
while(y):
x, y = y, x % y
return x
def factAdd(n):
for c in candidates:
while n % c == 0:
n //= c
test = 3
while test * test ... | python | test | abovesol | codeparrot/apps | all |
Solve in Python:
There are b blocks of digits. Each one consisting of the same n digits, which are given to you in the input. Wet Shark must choose exactly one digit from each block and concatenate all of those digits together to form one large integer. For example, if he chooses digit 1 from the first block and digit ... | p = 10 ** 9 + 7
n, b, k, x = [int(s) for s in input().split()]
block = [int(s) for s in input().split()]
D = [0 for i in range(10)]
for s in block:
D[s] += 1
A = [[0 for t in range(x)]]
pows = [pow(10, 1<<j, x) for j in range(b.bit_length())]
for i in range(10):
A[0][i%x] += D[i]
for j in range(b.bit_length()-1... | python | test | qsol | codeparrot/apps | all |
Solve in Python:
Given a collection of distinct integers, return all possible permutations.
Example:
Input: [1,2,3]
Output:
[
[1,2,3],
[1,3,2],
[2,1,3],
[2,3,1],
[3,1,2],
[3,2,1]
] | class Solution:
def permute(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
all_permutes = []
self.permute_nums(all_permutes, nums, [])
return all_permutes
def permute_nums(self, all_permutes, nums, cur_permute):
... | python | test | qsol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/746/C:
The tram in Berland goes along a straight line from the point 0 to the point s and back, passing 1 meter per t_1 seconds in both directions. It means that the tram is always in the state of uniform rectilinear motion, instantly turning a... | s, x1, x2 = list(map(int, input().split()))
t1, t2 = list(map(int, input().split()))
p, d = list(map(int, input().split()))
if x2 < x1:
x1, x2 = s - x1, s - x2
d *= -1
p = s - p
if t2 <= t1:
print(t2 * abs(x1 - x2))
return
if p <= x1 and d == 1:
print(min(t2 * abs(x1 - x2), t1* abs(p - x2)))... | python | test | abovesol | codeparrot/apps | all |
Solve in Python:
# One is the loneliest number
## Task
The range of vision of a digit is its own value. `1` can see one digit to the left and one digit to the right,` 2` can see two digits, and so on.
Thus, the loneliness of a digit `N` is the sum of the digits which it can see.
Given a non-negative integer, your f... | def loneliest(number):
if (str(number)).count("1")==0:
return False
if (str(number)).count("1")==len(str(number)):
return True
number=[int(a) for a in str(number)]
score=[]
one=[]
for idx,nr in enumerate(number):
b = idx-nr
f = idx+nr+1
s=0
... | python | train | qsol | codeparrot/apps | all |
Solve in Python:
Given two integer arrays A and B, return the maximum length of an subarray that appears in both arrays.
Example 1:
Input:
A: [1,2,3,2,1]
B: [3,2,1,4,7]
Output: 3
Explanation:
The repeated subarray with maximum length is [3, 2, 1].
Note:
1
0 | class Solution:
def findLength(self, A, B):
def check(length):
seen = {A[i:i+length]
for i in range(len(A) - length + 1)}
return any(B[j:j+length] in seen
for j in range(len(B) - length + 1))
A = ''.join(map(chr, A))
... | python | train | qsol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/1316/B:
Vasya has a string $s$ of length $n$. He decides to make the following modification to the string: Pick an integer $k$, ($1 \leq k \leq n$). For $i$ from $1$ to $n-k+1$, reverse the substring $s[i:i+k-1]$ of $s$. For example, if stri... | import io, sys, atexit, os
import math as ma
from decimal import Decimal as dec
from itertools import permutations
from itertools import combinations
def li():
return list(map(int, sys.stdin.readline().split()))
def num():
return list(map(int, sys.stdin.readline().split()))
def nu():
return int(input(... | python | test | abovesol | codeparrot/apps | all |
Solve in Python:
Maxim wants to buy an apartment in a new house at Line Avenue of Metropolis. The house has n apartments that are numbered from 1 to n and are arranged in a row. Two apartments are adjacent if their indices differ by 1. Some of the apartments can already be inhabited, others are available for sale.
Max... | n, k = map(int, input().split())
if k == n or k == 0:
a = 0
else:
a = 1
b = 0
if n == k or k == 0:
b = 0
else:
b = min(n // 3, k) * 2
k -= min(n // 3, k)
if k != 0:
if n % 3 == 1:
k -= 1
elif n % 3 == 2:
k -= 1
b += 1
b -= k
print(a, b) | python | test | qsol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/815/A:
On the way to school, Karen became fixated on the puzzle game on her phone! [Image]
The game is played as follows. In each level, you have a grid with n rows and m columns. Each cell originally contains the number 0.
One move consists... | """Ввод размера матрицы"""
nm = [int(s) for s in input().split()]
"""Ввод массива"""
a = []
for i in range(nm[0]):
a.append([int(j) for j in input().split()])
rez=[]
def stroka():
nonlocal rez
rez_row=[]
rez_r=0
for i in range(nm[0]):
min_row=501
for j in range(nm[1]):
... | python | test | abovesol | codeparrot/apps | all |
Solve in Python:
There were n groups of students which came to write a training contest. A group is either one person who can write the contest with anyone else, or two people who want to write the contest in the same team.
The coach decided to form teams of exactly three people for this training. Determine the maximu... | # IAWT
n = int(input())
a = list(map(int, input().split()))
x = a.count(1)
y = a.count(2)
z = min(x, y)
x -= z
z += x // 3
print(z) | python | test | qsol | codeparrot/apps | all |
Solve in Python:
You are given a string S consisting of lowercase English letters.
Determine whether we can turn S into a palindrome by repeating the operation of swapping two adjacent characters. If it is possible, find the minimum required number of operations.
-----Constraints-----
- 1 \leq |S| \leq 2 × 10^5
- S ... | from string import ascii_lowercase
class Bit:
def __init__(self, n):
self.size = n
self.tree = [0] * (n + 1)
def sum(self, i):
s = 0
while i > 0:
s += self.tree[i]
i -= i & -i
return s
def add(self, i, x):
while i <= self.size:
... | python | train | qsol | codeparrot/apps | all |
Solve in Python:
Roger recently built a circular race track with length K$K$. After hosting a few races, he realised that people do not come there to see the race itself, they come to see racers crash into each other (what's wrong with our generation…). After this realisation, Roger decided to hold a different kind of ... | import numpy as np
from numba import njit
i8 = np.int64
@njit
def solve(a, b, t, K, N):
t1 = t // K
d = t % K * 2
# b が a から a + d の位置にあれば衝突する
x = 0
y = 0
ans = 0
for c in a:
while b[x] < c:
x += 1
while b[y] <= c + d:
y += 1
... | python | train | qsol | codeparrot/apps | all |
Solve in Python:
# Task:
Given a list of numbers, determine whether the sum of its elements is odd or even.
Give your answer as a string matching `"odd"` or `"even"`.
If the input array is empty consider it as: `[0]` (array with a zero).
## Example:
```
odd_or_even([0]) == "even"
odd_or_even([0, 1, 4]) ... | def odd_or_even(n:list):
if len(n) == 0:
return [0]
elif sum(n) % 2 == 0:
return "even"
else:
return "odd" | python | train | qsol | codeparrot/apps | all |
Solve in Python:
Mrs Jefferson is a great teacher. One of her strategies that helped her to reach astonishing results in the learning process is to have some fun with her students. At school, she wants to make an arrangement of her class to play a certain game with her pupils. For that, she needs to create the arrangem... | def shortest_arrang(n):
r = n // 2 + 2
a = [i for i in range(r, 0, -1)]
for i in range(r):
for j in range(r + 1):
if sum(a[i:j]) == n:
return a[i:j]
return [-1] | python | train | qsol | codeparrot/apps | all |
Solve in Python:
At an arcade, Takahashi is playing a game called RPS Battle, which is played as follows:
- The player plays N rounds of Rock Paper Scissors against the machine. (See Notes for the description of Rock Paper Scissors. A draw also counts as a round.)
- Each time the player wins a round, depending on whi... | n, k = list(map(int, input().split()))
r, s, p = list(map(int, input().split()))
t = input()
tt = list(t)
d = {'r':p, 's': r, 'p':s}
dp = [d[t[i]] for i in range(n)]
for i in range(n-k):
if tt[i]==tt[i+k]:
dp[i+k] = 0
tt[i+k] = 'x'
print((sum(dp))) | python | test | qsol | codeparrot/apps | all |
Solve in Python:
Not so long ago company R2 bought company R1 and consequently, all its developments in the field of multicore processors. Now the R2 laboratory is testing one of the R1 processors.
The testing goes in n steps, at each step the processor gets some instructions, and then its temperature is measured. The... | I=lambda:list(map(int,input().split()))
n,m,N,X=I()
t=I()
r=min(t)!=N
r+=max(t)!=X
print(['C','Inc'][m+r>n or min(t)<N or max(t)>X]+'orrect') | python | test | qsol | codeparrot/apps | all |
I found an interesting problem on https://www.codewars.com/kata/5aa3e2b0373c2e4b420009af:
# Task
Write a function that accepts `msg` string and returns local tops of string from the highest to the lowest.
The string's tops are from displaying the string in the below way:
```
... | def tops(msg):
n = len(msg)
res,i,j,k = "",2,2,7
while i < n:
res = msg[i:i+j] + res
i,j,k=i+k,j+1,k+4
return res | python | train | abovesol | codeparrot/apps | all |
I found an interesting problem on https://www.codechef.com/problems/DIFNEIGH:
You are given an empty grid with $N$ rows (numbered $1$ through $N$) and $M$ columns (numbered $1$ through $M$). You should fill this grid with integers in a way that satisfies the following rules:
- For any three cells $c_1$, $c_2$ and $c_3$... | for _ in range(int(input())):
n, m = list(map(int, input().split()))
ans = [[0 for i in range(m)] for i in range(n)]
k = 0
if n == 1:
for i in range(m):
if i%4 == 0 or i%4 == 1:
t = 1
else:
t = 2
ans[0][i] = t
k = max(k, ans[0][i])
elif m == 1:
for i in range(n):
if i%4 == 0 or i%4 == 1:... | python | train | abovesol | codeparrot/apps | all |
I found an interesting problem on https://www.codewars.com/kata/5bc5cfc9d38567e29600019d:
## Story
Your company migrated the last 20 years of it's *very important data* to a new platform, in multiple phases. However, something went wrong: some of the essential time-stamps were messed up! It looks like that some server... | from datetime import date
def less(d1, d2):
if d1 == None or d2 == None:
return 0
return 1 if d1 <= d2 else 0
def check_dates(records):
correct = recoverable = uncertain = 0
for interval in records:
start = interval[0].split('-')
end = interval[1].split('-')
try:
... | python | train | abovesol | codeparrot/apps | all |
Solve in Python:
Ksenia has an array $a$ consisting of $n$ positive integers $a_1, a_2, \ldots, a_n$.
In one operation she can do the following: choose three distinct indices $i$, $j$, $k$, and then change all of $a_i, a_j, a_k$ to $a_i \oplus a_j \oplus a_k$ simultaneously, where $\oplus$ denotes the bitwise XOR ... | def solve(n, arr):
xor_sum = arr[0]
for i in range(1, n):
xor_sum ^= arr[i]
if n % 2 == 0:
if xor_sum:
print("NO")
return
else:
n -= 1
if n == 3:
print(1)
print(1, 2, 3)
return
print("YES")
print(n-2)
fo... | python | test | qsol | codeparrot/apps | all |
Solve in Python:
Introduction
Mr. Safety loves numeric locks and his Nokia 3310. He locked almost everything in his house. He is so smart and he doesn't need to remember the combinations. He has an algorithm to generate new passcodes on his Nokia cell phone.
Task
Can you crack his numeric locks? Mr. Safety's tr... | table = str.maketrans("abcdefghijklmnopqrstuvwxyz", "22233344455566677778889999")
def unlock(message):
return message.lower().translate(table) | python | train | qsol | codeparrot/apps | all |
Solve in Python:
Nobody knows, but $N$ frogs live in Chef's garden.
Now they are siting on the X-axis and want to speak to each other. One frog can send a message to another one if the distance between them is less or equal to $K$.
Chef knows all $P$ pairs of frogs, which want to send messages. Help him to define can t... | n,k,p=map(int,input().split())
l=list(map(int,input().split()))
t_1=[]
for i in range(n):
t_1.append([i,l[i]])
t_1=sorted(t_1,key=lambda x:x[1],reverse=True)
dis={}
for i in range(n):
if i==0:
dis[i]=t_1[i][1]+k
continue
if (t_1[i-1][1]-t_1[i][1])<=k:
dis[i]=dis[i-1]
else:
dis[i]=t_1[i][1]+k
trans={}
for i... | python | train | qsol | codeparrot/apps | all |
Solve in Python:
Naman owns a very famous Ice Cream parlour in Pune. He has a wide range of flavours with different pricing.
Every flavour costs ₹ X per gram and quantity of each flavour in the parlour is indefinite. Now, Naman has
received an order for a party wherein he is asked to prepare each Ice Cream with N n... | test = int(input())
for i in range(test):
flavor = int(input())
rate = input()
gaf = input()
gaf = gaf.split()
gaf = [int(x) for x in gaf]
rate = rate.split()
rate = [int(x) for x in rate]
rate.sort()
c = gaf[0] - gaf[1]
sum = rate[0]*c
t = True
if gaf[0] < gaf[1]:
t = False
j = 0
while(j<gaf[1] and t):... | python | train | qsol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/1076/A:
You are given a string $s$ consisting of $n$ lowercase Latin letters.
You have to remove at most one (i.e. zero or one) character of this string in such a way that the string you obtain will be lexicographically smallest among all stri... | n=int(input())
s=input()
l=[]
for i in range(1,n):
if(s[i]<s[i-1]):
x=s[:i-1]+s[i:]
print(x)
break
if(i==n-1):
print(s[:n-1])
break | python | test | abovesol | codeparrot/apps | all |
I found an interesting problem on https://www.codechef.com/ICM2020/problems/ICM2003:
Everyone loves short problem statements.
Given a function $ f(x) $ find its minimum value over the range $ 0 < x < π/2$
$
f(x) = ( x^2 + b*x + c ) / sin( x )
$
-----Input:-----
- First-line will contain $T$, the number of test cases. ... | import sys
import math
input=sys.stdin.readline
def binary(l,r,co,b,c):
x=(l+r)/2
#print(x)
val1=(2*x+b)*math.sin(x)
val2=(x**2+b*x+c)*math.cos(x)
x=(l+r)/2
val=val1-val2
if(abs(val)<.0000001 or co==150):
return (l+r)/2
if(val<0):
return binary((l+r)/2,r,co+1,b,c)
else:
return binary(l,(l+r)/2,co+1,b,c)
... | python | train | abovesol | codeparrot/apps | all |
I found an interesting problem on https://atcoder.jp/contests/abc060/tasks/abc060_b:
We ask you to select some number of positive integers, and calculate the sum of them.
It is allowed to select as many integers as you like, and as large integers as you wish.
You have to follow these, however: each selected integer nee... | a, b, c = list(map(int, input().split()))
for i in range(a, (a * b) + 1, a):
if i % b == c:
print("YES")
return
print("NO") | python | test | abovesol | codeparrot/apps | all |
I found an interesting problem on https://www.codechef.com/problems/BUCKETS:
There are $N$ buckets numbered $1$ through $N$. The buckets contain balls; each ball has a color between $1$ and $K$. Let's denote the number of balls with color $j$ that are initially in bucket $i$ by $a_{i, j}$.
For each $i$ from $1$ to $N-1... | """
Url: https://www.codechef.com/problems/BUCKETS
"""
__author__ = "Ronald Kaiser"
__email__ = "raios dot catodicos at gmail dot com"
N, K = list(map(int, input().split()))
a = list(map(int, input().split()))
s = sum(a)
p = list([v/s for v in a])
for _ in range(N-1):
a = list(map(int, input().split()))
sa = ... | python | train | abovesol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/590/A:
A schoolboy named Vasya loves reading books on programming and mathematics. He has recently read an encyclopedia article that described the method of median smoothing (or median filter) and its many applications in science and engineerin... | import sys
input=sys.stdin.readline
n=int(input())
a=list(map(int,input().split()))
d=[]
e=[]
for i in range(1,n-1):
if a[i]!=a[i-1] and a[i]!=a[i+1]:
e.append([a[i],i])
else:
if e!=[]:
d.append(e)
e=[]
if e!=[]:
d.append(e)
if len(d)==0:
print(0)
print(*a)
e... | python | train | abovesol | codeparrot/apps | all |
Solve in Python:
An integer X is called a Harshad number if X is divisible by f(X), where f(X) is the sum of the digits in X when written in base 10.
Given an integer N, determine whether it is a Harshad number.
-----Constraints-----
- 1?N?10^8
- N is an integer.
-----Input-----
Input is given from Standard Input i... | #!/usr/bin/env python3
import sys
sys.setrecursionlimit(10**6)
n = int(input())
fx = sum([int(i) for i in str(n)])
if n % fx == 0:
print("Yes")
else:
print("No") | python | test | qsol | codeparrot/apps | all |
Solve in Python:
Arkady is playing Battleship. The rules of this game aren't really important.
There is a field of $n \times n$ cells. There should be exactly one $k$-decker on the field, i. e. a ship that is $k$ cells long oriented either horizontally or vertically. However, Arkady doesn't know where it is located. F... | n, k = list(map(int, input().split()))
m = [list(input()) for _ in range(n)]
p = [[0 for _ in range(n)] for _ in range(n)]
for i in range(n):
for j in range(n):
s = True
if i + k - 1 < n:
for l in range(k):
if m[i + l][j] != '.':
s = False
... | python | test | qsol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/1368/D:
Gottfried learned about binary number representation. He then came up with this task and presented it to you.
You are given a collection of $n$ non-negative integers $a_1, \ldots, a_n$. You are allowed to perform the following operatio... | n=int(input())
a=list(map(int,input().split()))
x=[0]*20
for i in range(n):
s="{0:b}".format(a[i])
b=[]
for j in range(len(s)):
b.append(s[j])
b.reverse()
for j in range(20-len(s)):
b.append('0')
b.reverse()
for j in range(20):
if b[j]=='1':
x[j]+=1
ans=0
for i in range(n):
s=[]
for ... | python | test | abovesol | codeparrot/apps | all |
Solve in Python:
You went shopping to buy cakes and donuts with X yen (the currency of Japan).
First, you bought one cake for A yen at a cake shop.
Then, you bought as many donuts as possible for B yen each, at a donut shop.
How much do you have left after shopping?
-----Constraints-----
- 1 \leq A, B \leq 1 000
- A... | X = int(input())
A = int(input())
B = int(input())
print((X - A) % B) | python | test | qsol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/1030/E:
Vasya has a sequence $a$ consisting of $n$ integers $a_1, a_2, \dots, a_n$. Vasya may pefrom the following operation: choose some number from the sequence and swap any pair of bits in its binary representation. For example, Vasya can tr... | #!/usr/bin/env python3
import sys
def rint():
return list(map(int, sys.stdin.readline().split()))
#lines = stdin.readlines()
def get_num1(i):
cnt = 0
while i:
if i%2:
cnt +=1
i //=2
return cnt
n = int(input())
a = list(rint())
b = [get_num1(aa) for aa in a]
ans = 0
#S0[... | python | test | abovesol | codeparrot/apps | all |
Solve in Python:
Nian is a monster which lives deep in the oceans. Once a year, it shows up on the land, devouring livestock and even people. In order to keep the monster away, people fill their villages with red colour, light, and cracking noise, all of which frighten the monster out of coming.
Little Tommy has n lan... | n, m = map(int, input().split())
l1 = list(map(int, input().split()))
l2 = list(map(int, input().split()))
ans1 = []
for i in range(n):
ans = -10 ** 18 - 1
for j in range(n):
if j != i:
for q in range(m):
if ans < l1[j] * l2[q]:
ans = l1[j] * l2[q]
ans... | python | test | qsol | codeparrot/apps | all |
Solve in Python:
# Story&Task
There are three parties in parliament. The "Conservative Party", the "Reformist Party", and a group of independants.
You are a member of the “Conservative Party” and you party is trying to pass a bill. The “Reformist Party” is trying to block it.
In order for a bill to pass, it must h... | def pass_the_bill(par, con, ref):
return -1 if ref >= (par / 2) else max(0, par // 2 + 1 - con) | python | train | qsol | codeparrot/apps | all |
I found an interesting problem on https://www.codechef.com/ZCOPRAC/problems/ZCO12001:
Zonal Computing Olympiad 2012, 26 Nov 2011
A sequence of opening and closing brackets is well-bracketed if we can pair up each opening bracket with a matching closing bracket in the usual sense. For instance, the sequences (), (()) ... | # cook your dish here
import sys
n=int(input().strip())
stringa=input().strip().split()
stringa=''.join(stringa)
counter=0
max_width=0
max_depth=0
for i in range(n):
if stringa[i]=='1':
if counter==0:
start=i
counter+=1
else:
if counter>max_depth:
max_depth=count... | python | train | abovesol | codeparrot/apps | all |
Solve in Python:
=====Problem Statement=====
The itertools module standardizes a core set of fast, memory efficient tools that are useful by themselves or in combination. Together, they form an iterator algebra making it possible to construct specialized tools succinctly and efficiently in pure Python.
You are given a... | #!/usr/bin/env python3
import string
symbols = string.ascii_lowercase
from itertools import combinations
def __starting_point():
n = int(input().strip())
arr = list(map(str, input().strip().split(' ')))
times = int(input().strip())
cmbts = list(combinations(sorted(arr), times))
print(("{:.4f... | python | train | qsol | codeparrot/apps | all |
I found an interesting problem on https://www.codewars.com/kata/565b112d09c1adfdd500019c:
Complete the function that takes an array of words.
You must concatenate the `n`th letter from each word to construct a new word which should be returned as a string, where `n` is the position of the word in the list.
For exampl... | def nth_char(w):
return ''.join(w[i][i] for i in range(len(w))) | python | train | abovesol | codeparrot/apps | all |
I found an interesting problem on https://www.codechef.com/problems/CLPNT:
You may have helped Chef and prevented Doof from destroying the even numbers. But, it has only angered Dr Doof even further. However, for his next plan, he needs some time. Therefore, Doof has built $N$ walls to prevent Chef from interrupting hi... | import sys
from sys import stdin,stdout
from bisect import bisect_right
from os import path
#cin=sys.stdin.readline
cout=sys.stdout.write
if (path.exists('input.txt')):
#------------------Sublime--------------------------------------#
sys.stdin=open('input.txt','r');sys.stdout=open('output.txt','w');
def cinN():ret... | python | train | abovesol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/394/A:
When new students come to the Specialized Educational and Scientific Centre (SESC) they need to start many things from the beginning. Sometimes the teachers say (not always unfairly) that we cannot even count. So our teachers decided to ... | import re
s = input()
l = re.compile('[|]+').findall(s)
diff = len(l[0]) + len(l[1]) - len(l[2])
if diff == 0:
print(s)
elif diff == -2:
print(l[0]+'|+' + l[1] + '=' + l[2][:-1])
elif diff == 2:
l[2] += '|'
if len(l[0]) == 1:
l[1] = l[1][:-1]
else:
l[0] = l[0][:-1]
print(l[0]+... | python | test | abovesol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/909/F:
Given an integer N, find two permutations: Permutation p of numbers from 1 to N such that p_{i} ≠ i and p_{i} & i = 0 for all i = 1, 2, ..., N. Permutation q of numbers from 1 to N such that q_{i} ≠ i and q_{i} & i ≠ 0 for all i = 1, 2... | from math import log2, floor
n=int(input())
# n=100
if n%2:
print('NO')
else:
print("YES")
k=floor(log2(n))+1
res = [0 for i in range(n)]
occupied = [0 for i in range(n)]
switch = 0
for i in range(n,0,-1):
val = 2**k-1-i
if val > n:
k-=1
val = 2**k-1-i
if occupied[val-1]:
while occupied[val-1]:
... | python | test | abovesol | codeparrot/apps | all |
I found an interesting problem on https://www.codewars.com/kata/595ddfe2fc339d8a7d000089:
# Introduction
Hamsters are rodents belonging to the subfamily Cricetinae. The subfamily contains about 25 species, classified in six or seven genera. They have become established as popular small house pets, and, partly because... | from string import ascii_lowercase
id = {c:i for i,c in enumerate(ascii_lowercase)}
char = (ascii_lowercase+ascii_lowercase).__getitem__
def hamster_me(code, message):
res, L = {}, sorted(map(id.get, code))
for i,j in zip(L, L[1:]+[26+L[0]]):
start = char(i)
for k,x in enumerate(map(char, range... | python | train | abovesol | codeparrot/apps | all |
I found an interesting problem on https://www.codewars.com/kata/5600e00e42bcb7b9dc00014e:
The image shows how we can obtain the Harmonic Conjugated Point of three aligned points A, B, C.
- We choose any point L, that is not in the line with A, B and C. We form the triangle ABL
- Then we draw a line from point C that ... | def harmon_pointTrip(a, b, c):
return round((a*c + b*c - 2*a*b) / (2*c - a - b), 4) | python | train | abovesol | codeparrot/apps | all |
Solve in Python:
Mohit's girlfriend is playing a game with Nicky. The description of the game is as follows:
- Initially on a table Player 1 will put N gem-stones.
- Players will play alternatively, turn by turn.
- At each move a player can take at most M gem-stones (at least 1 gem-stone must be taken) from the availab... | n,m = list(map(int,input().split()))
l = [ [1],
[1,2],
[2,2,3],
[1,2,3,4],
[4,3,3,4,5] ]
print(l[n-1][m-1]) | python | train | qsol | codeparrot/apps | all |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.