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:
Alyona decided to go on a diet and went to the forest to get some apples. There she unexpectedly found a magic rooted tree with root in the vertex 1, every vertex and every edge of which has a number written on.
The girl noticed that some of the tree's vertices are sad, so she decided to play with the... | def subtree_count():
stack = [0]
while len(stack):
v = stack[-1]
size = 1
for u, _ in edge[v]:
if u in subtree:
size += subtree[u]
else:
stack.append(u)
if stack[-1] is v:
stack.pop()
subtree[v] = s... | python | test | qsol | codeparrot/apps | all |
Solve in Python:
In an array, a $block$ is a maximal sequence of identical elements. Since blocks are maximal, adjacent blocks have distinct elements, so the array breaks up into a series of blocks. For example, given the array $[3, 3, 2, 2, 2, 1, 5, 8, 4, 4]$, there are 6 blocks: $[3, 3], [2, 2, 2], [1], [5], [8], [4... | # cook your dish here
mod = 10 ** 8 + 7
def dic_add(dic, k1, v):
if k1 <= k:
if k1 in dic:
dic[k1] = (dic[k1]+v) % mod
else:
dic[k1] = v
for _ in range(int(input())):
n, m, k = list(map(int, input().split()))
a_l = list(map(int, input().split()))
b_l = list(map(int, input().split()))
# 0: m end, 1: n... | python | train | qsol | codeparrot/apps | all |
I found an interesting problem on https://www.codewars.com/kata/57096af70dad013aa200007b:
Your task is to calculate logical value of boolean array. Test arrays are one-dimensional and their size is in the range 1-50.
Links referring to logical operations: [AND](https://en.wikipedia.org/wiki/Logical_conjunction), [OR](... | def logical_calc(array, op):
if op == "AND":
return all(boolian for boolian in array)
elif op == "OR":
return any(boolian for boolian in array)
else:
return sum(array) % 2 | python | train | abovesol | codeparrot/apps | all |
Solve in Python:
The lockdown hasn’t been great for our chef as his restaurant business got sabotaged because of lockdown, nevertheless no worries our chef is a multi-talented guy. Chef has decided to be a freelancer and work remotely. According to chef’s maths, he should be able to work on maximum tasks assuming that ... | ans=[]
#code on gfg
def printMaxActivities(s, f):
n = len(f)
# The first activity is always selected
i = 0
ans.append(i)
# Consider rest of the activities
for j in range(n):
# If this activity has start time greater than
# or equal to the finish time of previously
# selec... | python | test | qsol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/437/A:
Once upon a time a child got a test consisting of multiple-choice questions as homework. A multiple-choice question consists of four choices: A, B, C and D. Each choice has a description, and the child should find out the only one that i... | v = [input()[2:] for i in range(4)]
l = [(len(s),s) for s in v]
min_l, min_s = min(l)[0], min(l)[1]
max_l, max_s = max(l)[0], max(l)[1]
min_ind = 0
max_ind = 0
for i in range(4):
if i != v.index(min_s) and len(v[i]) / min_l >= 2:
min_ind += 1
if i != v.index(max_s) and max_l / len(v[i]) >= 2:
... | python | test | abovesol | codeparrot/apps | all |
Solve in Python:
Vus the Cossack holds a programming competition, in which $n$ people participate. He decided to award them all with pens and notebooks. It is known that Vus has exactly $m$ pens and $k$ notebooks.
Determine whether the Cossack can reward all participants, giving each of them at least one pen and at le... | import math
import sys
#imgur.com/Pkt7iIf.png
def ii(): return int(input())
def mi(): return map(int, input().split())
def li(): return list(map(int, input().split()))
n, m, k = mi()
if min(m,k) >= n:
print('Yes')
else:
print('No') | python | test | qsol | codeparrot/apps | all |
I found an interesting problem on https://atcoder.jp/contests/abc170/tasks/abc170_d:
Given is a number sequence A of length N.
Find the number of integers i \left(1 \leq i \leq N\right) with the following property:
- For every integer j \left(1 \leq j \leq N\right) such that i \neq j , A_j does not divide A_i.
-----C... | n=int(input())
a=list(map(int,input().split()))
ans=0
a.sort()
num=a[-1]
dp=[True]*num
seen=[0]*num
for i in range(n):
num2=a[i]
if dp[num2-1]==True:
if seen[num2-1]==1:
dp[num2-1]=False
for j in range(2,num//num2+1):
dp[j*num2-1]=False
seen[a[i]-1]=1
ans=0
for i in r... | python | test | abovesol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/399/B:
User ainta has a stack of n red and blue balls. He can apply a certain operation which changes the colors of the balls inside the stack.
While the top ball inside the stack is red, pop the ball from the top of the stack. Then replace... | n = int(input())
s = input().strip()
ans = 0
for i in range(len(s)):
if s[i] == "B":
ans += 2 ** i
print(ans) | python | test | abovesol | codeparrot/apps | all |
I found an interesting problem on https://www.codechef.com/problems/DPAIRS:
Chef has two integer sequences $A_1, A_2, \ldots, A_N$ and $B_1, B_2, \ldots, B_M$. You should choose $N+M-1$ pairs, each in the form $(A_x, B_y)$, such that the sums $A_x + B_y$ are all pairwise distinct.
It is guaranteed that under the given ... | N,M = [int(i) for i in input().split()]
A = [int(i) for i in input().split()]
B = [int(i) for i in input().split()]
ans = []
seen = {}
flag = False
for i in range(N):
for j in range(M):
if(len(ans)==N+M-1):
flag = True
break
if(A[i]+B[j] not in seen):
ans.appen... | python | train | abovesol | codeparrot/apps | all |
I found an interesting problem on https://www.codewars.com/kata/5aca48db188ab3558e0030fa:
You have to create a function which receives 3 arguments: 2 numbers, and the result of an unknown operation performed on them (also a number).
Based on those 3 values you have to return a string, that describes which operation wa... | def calc_type(a, b, res):
return {a + b: "addition", a - b: "subtraction", a * b: "multiplication", a / b: "division"}[res] | python | train | abovesol | codeparrot/apps | all |
Solve in Python:
Little Dima misbehaved during a math lesson a lot and the nasty teacher Mr. Pickles gave him the following problem as a punishment.
Find all integer solutions x (0 < x < 10^9) of the equation:x = b·s(x)^{a} + c,
where a, b, c are some predetermined constant values and function s(x) determines the ... | a, b, c = map(int, input().split())
def s(x):
xStr = str(x)
sum = 0
for c in xStr:
sum += int(c)
return sum
rightSide = []
M = 9*9+1
for k in range(1,M):
rightSide.append(b*k**a + c)
myList = []
sol = 0
for x in rightSide:
if(x>0 and x<int(1e9) and x==b*s(x)**a + c):
sol += 1... | python | test | qsol | codeparrot/apps | all |
I found an interesting problem on https://www.codewars.com/kata/52dbae61ca039685460001ae:
Create a function which accepts one arbitrary string as an argument, and return a string of length 26.
The objective is to set each of the 26 characters of the output string to either `'1'` or `'0'` based on the fact whether the ... | def change(stg):
chars = set(stg.lower())
return "".join(str(int(c in chars)) for c in "abcdefghijklmnopqrstuvwxyz") | python | train | abovesol | codeparrot/apps | all |
I found an interesting problem on https://www.codewars.com/kata/588dd9c3dc49de0bd400016d:
Hello! Your are given x and y and 2D array size tuple (width, height) and you have to:
Calculate the according index in 1D space (zero-based).
Do reverse operation.
Implement:
to_1D(x, y, size):
--returns index in 1D space
to_... | def to_1D(x, y, size):
return size[0] * y + x
def to_2D(n, size):
return divmod(n, size[0])[::-1] | python | train | abovesol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/935/B:
Two neighboring kingdoms decided to build a wall between them with some gates to enable the citizens to go from one kingdom to another. Each time a citizen passes through a gate, he has to pay one silver coin.
The world can be represent... | def getCoord(x, y, t):
if t == 'U':
return (x, y + 1)
return (x + 1, y)
n = int(input())
s = input()
x, y = getCoord(0, 0, s[0])
t = 1
if x < y:
t = 0
ans = 0
for ch in s[1:]:
x, y = getCoord(x, y, ch)
if x == y:
continue
nt = 1
if x < y:
nt = 0
if t != nt:
t = nt
ans += 1
print(ans) | python | test | abovesol | codeparrot/apps | all |
Solve in Python:
You are given two strings $s$ and $t$. The string $s$ consists of lowercase Latin letters and at most one wildcard character '*', the string $t$ consists only of lowercase Latin letters. The length of the string $s$ equals $n$, the length of the string $t$ equals $m$.
The wildcard character '*' in the... | n, m = (int(x) for x in input().split())
a = input()
b = input()
if '*' not in a:
if a == b:
print('YES')
else:
print('NO')
quit()
l, r = a.split('*')
if len(b) >= len(a) - 1:
if l == b[:len(l)] and r == b[len(b) - len(r):]:
print('YES')
else:
print('NO')
else:
pr... | python | test | qsol | codeparrot/apps | all |
Solve in Python:
You are given $4n$ sticks, the length of the $i$-th stick is $a_i$.
You have to create $n$ rectangles, each rectangle will consist of exactly $4$ sticks from the given set. The rectangle consists of four sides, opposite sides should have equal length and all angles in it should be right. Note that eac... | N = int(input())
for i in range(N):
A = int(input())
B = list(map(int,input().split()))
B.sort()
flag = True
for i in range(2*A):
if B[2*i] != B[2*i+1]:
flag = False
break
S = B[0]*B[-1]
for i in range(A):
if B[i*2] * B[-i*2-1] != S:
flag =... | python | test | qsol | codeparrot/apps | all |
Solve in Python:
There's a tree and every one of its nodes has a cost associated with it. Some of these nodes are labelled special nodes. You are supposed to answer a few queries on this tree. In each query, a source and destination node (SNODE$SNODE$ and DNODE$DNODE$) is given along with a value W$W$. For a walk betwe... | # cook your dish here
# cook your dish here
import numpy as np
n, s, q = [int(j) for j in input().split()]
edges = [int(j)-1 for j in input().split()]
costs = [int(j) for j in input().split()]
special = [int(j)-1 for j in input().split()]
queries = [[0] * 3 for _ in range(q)]
for i in range(q):
queries[i] = [int(j)-... | python | train | qsol | codeparrot/apps | all |
Solve in Python:
You are playing a computer game. In this game, you have to fight $n$ monsters.
To defend from monsters, you need a shield. Each shield has two parameters: its current durability $a$ and its defence rating $b$. Each monster has only one parameter: its strength $d$.
When you fight a monster with streng... | import sys,bisect
r=lambda:map(int,sys.stdin.readline().split())
M=998244353
f=lambda b:pow(b,M-2,M)
n,m=r()
d=sorted(r())
p=[0]
for v in d:p+=[p[-1]+v]
for _ in range(m):a,b=r();i=bisect.bisect(d,b-1);v=n-i;print([(p[i]*a*f(v+v*v)-p[-1]*(a*f(v)-1))%M,0][a>v]) | python | test | qsol | codeparrot/apps | all |
Solve in Python:
You are given an array x of n positive numbers. You start at point (0,0) and moves x[0] metres to the north, then x[1] metres to the west,
x[2] metres to the south,
x[3] metres to the east and so on. In other words, after each move your direction changes
counter-clockwise.
Write a one... | class Solution:
def isSelfCrossing(self, x):
"""
:type x: List[int]
:rtype: bool
"""
l = (len(x))
iscross = False
if l < 4: return False
for i in range(3, l):
#情况1
if x[i-3]>=x[i-1] and x[i-2]<=x[i]:
... | python | train | qsol | codeparrot/apps | all |
Solve in Python:
Ksusha the Squirrel is standing at the beginning of a straight road, divided into n sectors. The sectors are numbered 1 to n, from left to right. Initially, Ksusha stands in sector 1.
Ksusha wants to walk to the end of the road, that is, get to sector n. Unfortunately, there are some rocks on the roa... | n, k = map(int, input().split())
j = 0
for i in input():
if i == '.':
j = 0
else:
j += 1
if j >= k:
print("NO")
break
else:
print("YES") | python | test | qsol | codeparrot/apps | all |
I found an interesting problem on https://atcoder.jp/contests/abc155/tasks/abc155_c:
We have N voting papers. The i-th vote (1 \leq i \leq N) has the string S_i written on it.
Print all strings that are written on the most number of votes, in lexicographical order.
-----Constraints-----
- 1 \leq N \leq 2 \times 10^5
... | n = int(input())
S = dict()
for i in range(n):
s = input()
if s in S: S[s] += 1
else: S[s] = 1
ans = []
cnt = 0
for k,v in S.items():
if v >= cnt:
if v > cnt: ans = []
ans.append(k)
cnt = v
print(*sorted(ans), sep='\n') | python | test | abovesol | codeparrot/apps | all |
Solve in Python:
"I'm a fan of anything that tries to replace actual human contact." - Sheldon.
After years of hard work, Sheldon was finally able to develop a formula which would diminish the real human contact.
He found k$k$ integers n1,n2...nk$n_1,n_2...n_k$ . Also he found that if he could minimize the value of m... | t = int(input())
def conv(n):
k = bin(n)
k = k[2:]
z = len(k)
c = '1'*z
if c == k:
return False
def find(n):
x = bin(n)[2:]
str = ''
for i in x[::-1]:
if i == '0':
str+='1'
break
else:
str+='0'
return int(str[::-1],2)
for i in range(t):
n = ... | python | train | qsol | codeparrot/apps | all |
Solve in Python:
Rebel spy Heidi has just obtained the plans for the Death Star from the Empire and, now on her way to safety, she is trying to break the encryption of the plans (of course they are encrypted – the Empire may be evil, but it is not stupid!). The encryption has several levels of security, and here is how... | n, p = map(int, input().split())
a = [int(x) for x in input().split()]
s = sum(a)
ans = -1; psum = 0
for i in a:
psum += i
ans = max(ans, psum % p + (s - psum) % p)
print(ans) | python | test | qsol | codeparrot/apps | all |
Solve in Python:
Chef was bored staying at home in the lockdown. He wanted to go out for a change. Chef and Chefu are fond of eating Cakes,so they decided to go the Cake shop where cakes of all possible price are available .
They decided to purchase cakes of equal price and each of them will pay for their cakes. Chef o... | from math import gcd
def lcm(a,b):
return int((a*b/gcd(a,b)))
t=int(input())
while (t!=0):
n,m=list(map(int,input().split()))
ans=lcm(n,m)
print(ans)
t=t-1 | python | train | qsol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/520/C:
Vasya became interested in bioinformatics. He's going to write an article about similar cyclic DNA sequences, so he invented a new method for determining the similarity of cyclic sequences.
Let's assume that strings s and t have the sam... | n = int(input())
s = input()
lst = {'A' : 0, 'C' : 0, 'G' : 0, 'T' : 0}
k, l = 0, 1
for i in s:
lst[i] += 1
if k < lst[i]:
k = lst[i]
l = 1
else:
if k == lst[i]:
l += 1
print(l ** n % (10 ** 9 + 7)) | python | test | abovesol | codeparrot/apps | all |
Solve in Python:
Chef is multi-talented. He has developed a cure for coronavirus called COVAC-19. Now that everyone in the world is infected, it is time to distribute it throughout the world efficiently to wipe out coronavirus from the Earth. Chef just cooks the cure, you are his distribution manager.
In the world, the... | for _ in range(int(input())):
n,x=map(int,input().split())
a=list(map(int,input().split()))
a.sort()
count=0
for i in range(n):
if a[i]>=x/2:
break
# count+=1
count=i
while 1:
if a[i]<=x:
count+=1
x=2*a[i]
else:
while a[i]>x:
x=2*x
count+=1
x=2*a[i]
count+=1
i+=1
if i... | python | train | qsol | codeparrot/apps | all |
Solve in Python:
There are $n$ left boots and $n$ right boots. Each boot has a color which is denoted as a lowercase Latin letter or a question mark ('?'). Thus, you are given two strings $l$ and $r$, both of length $n$. The character $l_i$ stands for the color of the $i$-th left boot and the character $r_i$ stands for... | n = int(input())
l = input()
r = input()
li = [0] * 27
li2 = [[] for i in range(27)]
ri = [0] * 27
ri2 = [[] for i in range(27)]
alth = "qwertyuiopasdfghjklzxcvbnm?"
for i in range(n):
i1 = alth.find(l[i])
i2 = alth.find(r[i])
li[i1] += 1
ri[i2] += 1
li2[i1] += [i]
ri2[i2] += [i]
for i in r... | python | test | qsol | codeparrot/apps | all |
I found an interesting problem on https://www.codechef.com/COOK29/problems/DIRECTI:
Chef recently printed directions from his home to a hot new restaurant across the town, but forgot to print the directions to get back home. Help Chef to transform the directions to get home from the restaurant.
A set of directions cons... | cases = int(input())
for case in range (cases):
N = int(input())
A = []
B = []
for n in range (N):
x,y = input().split(" on ")
A.append(x)
B.append(y)
x = n
y = n-1
print(A[0],'on',B[n])
for y in range (N-1,0,-1):
if (A[x] == "Right"):
print("L... | python | train | abovesol | codeparrot/apps | all |
Solve in Python:
Captain Flint and his crew keep heading to a savage shore of Byteland for several months already, drinking rum and telling stories. In such moments uncle Bogdan often remembers his nephew Denis. Today, he has told a story about how Denis helped him to come up with an interesting problem and asked the c... | import math
T=int(input())
for t in range(T):
n=int(input())
rem=math.ceil(n/4)
ans=''
for i in range(n-rem):
ans+='9'
for i in range(rem):
ans+='8'
print(ans) | python | test | qsol | codeparrot/apps | all |
I found an interesting problem on https://atcoder.jp/contests/abc161/tasks/abc161_d:
A positive integer X is said to be a lunlun number if and only if the following condition is satisfied:
- In the base ten representation of X (without leading zeros), for every pair of two adjacent digits, the absolute difference of t... | # import itertools
# import math
# from functools import reduce
# import sys
# sys.setrecursionlimit(500*500)
# import numpy as np
# import heapq
# from collections import deque
K = int(input())
# S = input()
# n, *a = map(int, open(0))
# N, M = map(int, input().split())
# A = list(map(int, input().split()))
# B = lis... | python | test | abovesol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/1369/B:
Lee was cleaning his house for the party when he found a messy string under the carpets. Now he'd like to make it clean accurately and in a stylish way...
The string $s$ he found is a binary string of length $n$ (i. e. string consists ... | from itertools import groupby as gb
t = int(input())
for _ in range(t):
n = int(input())
s = input()
if s.count('10') == 0:
print(s)
continue
res = ""
suf = ""
l = [(k, len(list(v))) for k, v in gb(s)]
if len(l) > 0 and l[0][0] == '0':
res += l[0][0] * l[0][1]
... | python | train | abovesol | codeparrot/apps | all |
I found an interesting problem on https://www.codechef.com/problems/THEATRE:
Chef's friend Alex runs a movie theatre. Due to the increasing number of platforms for watching movies online, his business is not running well. As a friend, Alex asked Chef to help him maximise his profits. Since Chef is a busy person, he nee... | def maximizing(array):
cpy = array[:]
final_list = []
for i in range(len(array)):
new_list = [array[i]]
for t in range(len(cpy)):
for j in range(len(new_list)):
if cpy[t][0] == new_list[j][0] or cpy[t][1] == new_list[j][1]:
break
else:
new_list.append(cpy[t])
cpy.remove(array[i])
final_... | python | train | abovesol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/385/B:
The bear has a string s = s_1s_2... s_{|}s| (record |s| is the string's length), consisting of lowercase English letters. The bear wants to count the number of such pairs of indices i, j (1 ≤ i ≤ j ≤ |s|), that string x(i, j) = s_{i}s_{i... | s = input()
k = 0
l = 0
sstr = -2
count = 0
while sstr != -1:
sstr = s.find("bear")
if sstr == -1 :
break
else :
if sstr == 0 or sstr == len(s) - 1:
k += (len(s) - 3)
else:
z = ((sstr + 1) * (len(s) - sstr - 3))
k += z
s = s[(sstr + 1):len... | python | test | abovesol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/1152/B:
Cat Furrier Transform is a popular algorithm among cat programmers to create longcats. As one of the greatest cat programmers ever exist, Neko wants to utilize this algorithm to create the perfect longcat.
Assume that we have a cat wit... | x = int(input())
ans = []
cnt = 0
while x & (x + 1) != 0:
bn = str(bin(x)[2:])
cnt += 1
ret = -1
for i in range(len(bn)):
if bn[i] == '0':
ret = i
break
if ret == -1:
break
x ^= 2 ** (len(bn) - ret) - 1
ans.append(len(bn) - ret)
if x & (x + ... | python | test | abovesol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/835/A:
Two boys decided to compete in text typing on the site "Key races". During the competition, they have to type a text consisting of s characters. The first participant types one character in v_1 milliseconds and has ping t_1 milliseconds.... | def chop():
return (int(i) for i in input().split())
s,v1,v2,t1,t2=chop()
a1=s*v1+t1*2
a2=s*v2+t2*2
if a1==a2:
print('Friendship')
elif a1<a2:
print('First')
else:
print('Second') | python | test | abovesol | codeparrot/apps | all |
Solve in Python:
There are n Imperial stormtroopers on the field. The battle field is a plane with Cartesian coordinate system. Each stormtrooper is associated with his coordinates (x, y) on this plane.
Han Solo has the newest duplex lazer gun to fight these stormtroopers. It is situated at the point (x_0, y_0). In o... | n,x,y=list(map(int,input().split()))
s=set()
for i in range(n):
a,b=list(map(int,input().split()))
s.add((a-x)/(b-y) if b-y!=0 else float("INF"))
print(len(s)) | python | test | qsol | codeparrot/apps | all |
I found an interesting problem on https://www.hackerrank.com/challenges/np-concatenate/problem:
=====Function Descriptions=====
Concatenate
Two or more arrays can be concatenated together using the concatenate function with a tuple of the arrays to be joined:
import numpy
array_1 = numpy.array([1,2,3])
array_2 = num... | import numpy
n, m, p = [int(x) for x in input().strip().split()]
arr1 = []
arr2 = []
for _ in range(n):
arr1.append([int(x) for x in input().strip().split()] )
for _ in range(m):
arr2.append([int(x) for x in input().strip().split()] )
arr1 = numpy.array(arr1)
arr2 = numpy.array(arr2)
print(numpy.co... | python | train | abovesol | codeparrot/apps | all |
I found an interesting problem on https://www.codechef.com/problems/UNBAL:
A balanced parenthesis string is defined as follows:
- The empty string is balanced
- If P is balanced, (P) is also
- If P and Q are balanced, PQ is also balanced
You are given two even integers n$n$ and k$k$. Find any balanced paranthesis stri... | a = int(input())
while a!=0:
b,c = map(int,input().split())
p = c-2
if p==0 or p==2 or b==c:
print(-1)
else:
q = b//p
r = b%p
k=0
if p+r == c:
print("(", end="")
while k != q:
for i in range(1, p + 1):
... | python | train | abovesol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/415/A:
Mashmokh works in a factory. At the end of each day he must turn off all of the lights.
The lights on the factory are indexed from 1 to n. There are n buttons in Mashmokh's room indexed from 1 to n as well. If Mashmokh pushes button wi... | n,m=map(int,input().split())
a=list(map(int,input().split()))
b=[0]*n
for i in range(m):
num=a[i]
while num<=len(b) and b[num-1]==0:
b[num-1]=a[i]
num+=1
for i in range(len(b)):
print(b[i],end=' ') | python | test | abovesol | codeparrot/apps | all |
Solve in Python:
We have N weights indexed 1 to N. The mass of the weight indexed i is W_i.
We will divide these weights into two groups: the weights with indices not greater than T, and those with indices greater than T, for some integer 1 \leq T < N. Let S_1 be the sum of the masses of the weights in the former group... | n = int(input())
w = list(map(int, input().split()))
s = sum(w)
ans = float('inf')
for i in range(n):
ans = min(ans, abs(sum(w[:i]) - sum(w[i:])))
print(ans) | python | test | qsol | codeparrot/apps | all |
Solve in Python:
Given an array of integers arr. Return the number of sub-arrays with odd sum.
As the answer may grow large, the answer must be computed modulo 10^9 + 7.
Example 1:
Input: arr = [1,3,5]
Output: 4
Explanation: All sub-arrays are [[1],[1,3],[1,3,5],[3],[3,5],[5]]
All sub-arrays sum are [1,4,9,3,8,5].
Od... | class Solution:
def numOfSubarrays(self, arr: List[int]) -> int:
res = odd = even = 0
for x in arr:
even += 1
if x % 2:
odd, even = even, odd
res = (res + odd) % 1000000007
return res | python | train | qsol | codeparrot/apps | all |
Solve in Python:
Ivan is developing his own computer game. Now he tries to create some levels for his game. But firstly for each level he needs to draw a graph representing the structure of the level.
Ivan decided that there should be exactly n_{i} vertices in the graph representing level i, and the edges have to be b... | #! /usr/bin/env python
# http://codeforces.com/problemset/problem/818/F
# Problem name ::: F. Level Generation
# submission number
#212055293
#508427854
def newest_approach(n):
from math import floor, ceil, sqrt
quad_solv = sqrt(2*n+1/4)-1/2
x = floor(quad_solv)
y = ceil(quad_solv)
xed = int(x... | python | test | qsol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/1311/D:
You are given three integers $a \le b \le c$.
In one move, you can add $+1$ or $-1$ to any of these integers (i.e. increase or decrease any number by one). You can perform such operation any (possibly, zero) number of times, you can ev... | import sys
input = sys.stdin.readline
for _ in range(int(input())):
a, b, c = list(map(int, input().split()))
ans = 10**18
index = [0, 0, 0]
for x in range(1, c+1):
for y in range(x, c+100, x):
cost = abs(a-x) + abs(b-y)
if c % y < y - (c % y):
z = c - (... | python | test | abovesol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/409/C:
Salve, mi amice.
Et tu quidem de lapis philosophorum. Barba non facit philosophum. Labor omnia vincit. Non potest creatio ex nihilo. Necesse est partibus.
Rp:
I Aqua Fortis
I Aqua Regia
II Amalgama
VII Minium
I... | from math import floor
nums = list(map(int, input().split()))
seq = [1, 1, 2, 7, 4]
min_c = 10000000000
for i in range(len(nums)):
if floor(nums[i] / seq[i]) < min_c:
min_c = floor(nums[i] / seq[i])
print(min_c) | python | test | abovesol | codeparrot/apps | all |
I found an interesting problem on https://www.codewars.com/kata/5d16af632cf48200254a6244:
A strongness of an even number is the number of times we can successively divide by 2 until we reach an odd number starting with an even number n.
For example, if n = 12, then
* 12 / 2 = 6
* 6 / 2 = 3
So we divided successively ... | from math import log
from math import floor
def strongest_even(n,m):
a=2**floor(log(m)/log(2));b=1;
while a*b<n or a*b>m:
a /= 2;
b += 2;
while a*b<=m:
if a*b>=n:
return a*b
b +=2
return a*b
#strongest_even(33,47) | python | train | abovesol | codeparrot/apps | all |
Solve in Python:
Snuke loves puzzles.
Today, he is working on a puzzle using S- and c-shaped pieces.
In this puzzle, you can combine two c-shaped pieces into one S-shaped piece, as shown in the figure below:
Snuke decided to create as many Scc groups as possible by putting together one S-shaped piece and two c-shaped p... | n, m = map(int, input().split())
ans = min(n, m // 2)
m -= ans * 2
ans += max(0, m // 4)
print(ans) | python | test | qsol | codeparrot/apps | all |
I found an interesting problem on https://www.codewars.com/kata/57f8ff867a28db569e000c4a:
Modify the `kebabize` function so that it converts a camel case string into a kebab case.
Notes:
- the returned string should only contain lowercase letters
I tried it in Python, but could not do it. Can you solve it? | import re
def kebabize(s):
return re.sub('\B([A-Z])', r'-\1', re.sub('\d', '', s)).lower() | python | train | abovesol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/532/C:
Polycarp and Vasiliy love simple logical games. Today they play a game with infinite chessboard and one pawn for each player. Polycarp and Vasiliy move in turns, Polycarp starts. In each turn Polycarp can move his pawn from cell (x, y) t... | def main():
def dist(x1, y1, x2, y2):
return max(abs(x1 - x2), abs(y1 - y2))
xp, yp, xv, yv = [int(i) for i in input().split()]
win = -1
while True:
if xp == 0:
yp -= 1
elif yp == 0:
xp -= 1
elif dist(xp - 1, yp, xv, yv) < dist(xp, yp - 1... | python | test | abovesol | codeparrot/apps | all |
Solve in Python:
One day Alice was cleaning up her basement when she noticed something very curious: an infinite set of wooden pieces! Each piece was made of five square tiles, with four tiles adjacent to the fifth center tile: [Image] By the pieces lay a large square wooden board. The board is divided into $n^2$ cel... | n=int(input())
tab=[]
for i in range(n):
a=list(input())
tab.append(a)
for i in range(i):
for j in range(n):
if 0<i<n-1 and 0<j<n-1 and tab[i-1][j]==tab[i+1][j]==tab[i][j+1]==tab[i][j-1]==tab[i][j]=='.':
tab[i][j]='#'
tab[i-1][j]='#'
tab[i+1][j]='#'
ta... | python | test | qsol | codeparrot/apps | all |
Solve in Python:
# Solve For X
You will be given an equation as a string and you will need to [solve for X](https://www.mathplacementreview.com/algebra/basic-algebra.php#solve-for-a-variable) and return x's value. For example:
```python
solve_for_x('x - 5 = 20') # should return 25
solve_for_x('20 = 5 * x - 5') # sho... | import re
def solve_for_x(equation):
left,right = equation.split("=")
answer = False
TrialAndErrorRipMs = -1000
while answer == False:
FinalLeft = re.sub("x", str(TrialAndErrorRipMs), left)
FinalRight = re.sub("x", str(TrialAndErrorRipMs), right)
if eval(FinalLeft) == eval(FinalR... | python | train | qsol | codeparrot/apps | all |
Solve in Python:
Daniel has a string s, consisting of lowercase English letters and period signs (characters '.'). Let's define the operation of replacement as the following sequence of steps: find a substring ".." (two consecutive periods) in string s, of all occurrences of the substring let's choose the first one, an... | import sys; sys.setrecursionlimit(1000000)
def solve():
n, m, = rv()
s = list(input())
res = [0] * m
#replace dot:
#dot had nothing on left or right: nothing changes
#dot had one on left or right: -1
#dot had two on left or right: -2
#replace char:
#if had two chars on left and righ... | python | test | qsol | codeparrot/apps | all |
Solve in Python:
The snakes want to build a temple for Lord Cobra. There are multiple strips of land that they are looking at, but not all of them are suitable. They need the strip of land to resemble a coiled Cobra. You need to find out which strips do so.
Formally, every strip of land, has a length. Suppose the lengt... | # cook your dish here
t = int(input())
for z in range(t) :
n = int(input())
a = [int(x) for x in input().split()]
if n%2==1 and a[0]==1 :
x = list(reversed(a))
for i in range((len(a)-1)//2) :
if a[i] + 1 == x[i+1] :
c = 0
else:
c = 1
break
if c==1 :
print("no")
else:
print("yes")
el... | python | train | qsol | codeparrot/apps | all |
I found an interesting problem on https://www.codewars.com/kata/5921c0bc6b8f072e840000c0:
A series or sequence of numbers is usually the product of a function and can either be infinite or finite.
In this kata we will only consider finite series and you are required to return a code according to the type of sequence:
... | def sequence_classifier(arr):
f,l=0,len(arr)-1
for i in range(0,l): f|= 1 if arr[i]<arr[i+1] else 2 if arr[i]==arr[i+1] else 4
return [0,1,5,2,3,0,4,0][f] | python | train | abovesol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/1031/B:
When Masha came to math classes today, she saw two integer sequences of length $n - 1$ on the blackboard. Let's denote the elements of the first sequence as $a_i$ ($0 \le a_i \le 3$), and the elements of the second sequence as $b_i$ ($0... | n = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
for i in range(n-1):
if a[i] == 3:
a[i] = '11'
elif a[i] == 2:
a[i] = '10'
elif a[i] == 1:
a[i] = '01'
elif a[i] == 0:
a[i] = '00'
for i in range(n-1):
if b[i] == 3:
b[i... | python | test | abovesol | codeparrot/apps | all |
Solve in Python:
There are N piles of stones arranged in a row. The i-th pile has stones[i] stones.
A move consists of merging exactly K consecutive piles into one pile, and the cost of this move is equal to the total number of stones in these K piles.
Find the minimum cost to merge all piles of stones into one pile. ... | class Solution:
def mergeStones(self, stones: List[int], K: int) -> int:
n = len(stones)
dp = [[[math.inf for k in range(K + 1)] for j in range(n)] for i in range(n)]
# dp[i][j][k]: min cost of merging from i to j (inclusive) and finally having k piles
for i in range(n):
... | python | train | qsol | codeparrot/apps | all |
I found an interesting problem on https://www.codechef.com/problems/CHEFEZQ:
Chef published a blog post, and is now receiving many queries about it. On day $i$, he receives $Q_i$ queries. But Chef can answer at most $k$ queries in a single day.
Chef always answers the maximum number of questions that he can on any giv... | def calFirstFreeDay(r, k, count):
if((r-k)<k):
print(count+2)
else:
calFirstFreeDay(r-k, k, count+1)
T = int(input())
for i in range(0, T):
list = input().split()
n = int(list[0])
k = int(list[1])
pq = 0
outputDone=False;
arr = input().split()
for j in range(0, n):
q = int(arr[j])
if((q+pq)<k):
p... | python | train | abovesol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/1335/B:
You are given three positive integers $n$, $a$ and $b$. You have to construct a string $s$ of length $n$ consisting of lowercase Latin letters such that each substring of length $a$ has exactly $b$ distinct letters. It is guaranteed tha... | t = int(input(''))
c = []
for i in range(97,123,1):
c.append(chr(i))
for _ in range(t):
n,a,b = list(map(int,input('').split(' ')))
s = ''
for i in range(n):
s = s+c[i%b]
print(s) | python | test | abovesol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/1364/A:
Ehab loves number theory, but for some reason he hates the number $x$. Given an array $a$, find the length of its longest subarray such that the sum of its elements isn't divisible by $x$, or determine that such subarray doesn't exist.
... | for testcase in range(int(input())):
n, x = map(int, input().split())
arr = list(map(int, input().split()))
start = 0
for i in arr:
if not i % x:
start += 1
else:
break
end = 0
for i in arr[::-1]:
if not i % x:
end += 1
else:
... | python | test | abovesol | codeparrot/apps | all |
Solve in Python:
Each floating-point number should be formatted that only the first two decimal places are returned. You don't need to check whether the input is a valid number because only valid numbers are used in the tests.
Don't round the numbers! Just cut them after two decimal places!
```
Right examples:
32.... | def two_decimal_places(number):
number = str(number)
return float(number[:number.index('.') + 3]) | python | train | qsol | codeparrot/apps | all |
Solve in Python:
You are given a tree consisting of $n$ vertices. A tree is an undirected connected acyclic graph. [Image] Example of a tree.
You have to paint each vertex into one of three colors. For each vertex, you know the cost of painting it in every color.
You have to paint the vertices so that any path consi... | from collections import defaultdict, deque
from itertools import permutations
class Graph:
def __init__(self):
self.E = {}
self.V = defaultdict(list)
def put(self, v1, v2):
if v1 not in self.E:
self.E[v1] = 1
if v2 not in self.E:
self.E[v2] = 1
... | python | test | qsol | codeparrot/apps | all |
Solve in Python:
There are N students and M checkpoints on the xy-plane.
The coordinates of the i-th student (1 \leq i \leq N) is (a_i,b_i), and the coordinates of the checkpoint numbered j (1 \leq j \leq M) is (c_j,d_j).
When the teacher gives a signal, each student has to go to the nearest checkpoint measured in Ma... | n, m = list(map(int,input().split()))
s_x_plus_y = []
s_x_minus_y = []
p_x_plus_y = []
p_x_minus_y = []
for student in range(n):
x, y = list(map(int,input().split()))
s_x_plus_y.append(x + y)
s_x_minus_y.append(x - y)
for i in range(m):
x, y = list(map(int,input().split()))
p_x_plus_y.append(x + y... | python | test | qsol | codeparrot/apps | all |
I found an interesting problem on https://leetcode.com/problems/find-the-city-with-the-smallest-number-of-neighbors-at-a-threshold-distance/:
There are n cities numbered from 0 to n-1. Given the array edges where edges[i] = [fromi, toi, weighti] represents a bidirectional and weighted edge between cities fromi and toi,... | class Solution:
def dfs(self, q, D, V, k):
Q = [q]
V[q] = 0
while Q:
T = []
for nd in Q:
W = V[nd]
for n,w in D[nd]:
cl = W + w
cr = V[n]
if cl < cr and cl <= k... | python | train | abovesol | codeparrot/apps | all |
Solve in Python:
There are quite a lot of ways to have fun with inflatable balloons. For example, you can fill them with water and see what happens.
Grigory and Andrew have the same opinion. So, once upon a time, they went to the shop and bought $n$ packets with inflatable balloons, where $i$-th of them has exactly $a... | # python3
def readline(): return list(map(int, input().split()))
def main():
n, = readline()
a = tuple(readline())
if n == 1 or n == 2 and a[0] == a[1]:
print(-1)
else:
print(1)
print(a.index(min(a)) + 1)
main() | python | test | qsol | codeparrot/apps | all |
Solve in Python:
Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).
For example:
Given binary tree [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
return its level order traversal as:
[
[3],
[9,20],
[15,7]
] | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def traverse(self, root, ordered, level=0):
if root.left:
self.traverse(root.left, ordered, level=level+1)
... | python | train | qsol | codeparrot/apps | all |
Solve in Python:
A student of z-school found a kind of sorting called z-sort. The array a with n elements are z-sorted if two conditions hold:
a_{i} ≥ a_{i} - 1 for all even i, a_{i} ≤ a_{i} - 1 for all odd i > 1.
For example the arrays [1,2,1,2] and [1,1,1,1] are z-sorted while the array [1,2,3,4] isn’t z-sorted... | n = int(input())
l = list(map(int, input().split()))
l.sort(reverse = True)
mas = [0 for i in range(n)]
t = 0
for i in range(1, n, 2):
mas[i] = l[t]
t += 1
for i in range(0, n, 2):
mas[i] = l[t]
t += 1
print(*mas) | python | test | qsol | codeparrot/apps | all |
Solve in Python:
Once Max found an electronic calculator from his grandfather Dovlet's chest. He noticed that the numbers were written with seven-segment indicators (https://en.wikipedia.org/wiki/Seven-segment_display). [Image]
Max starts to type all the values from a to b. After typing each number Max resets the cal... | char = [6, 2, 5, 5, 4, 5, 6, 3, 7, 6]
a, b = map(int, input().split())
cnt = 0
for i in range(a, b + 1):
for f in list(str(i)):
cnt += char[int(f)]
print(cnt) | python | test | qsol | codeparrot/apps | all |
Solve in Python:
ATMs of a well-known bank of a small country are arranged so that they can not give any amount of money requested by the user. Due to the limited size of the bill dispenser (the device that is directly giving money from an ATM) and some peculiarities of the ATM structure, you can get at most k bills fr... | f = lambda: list(map(int, input().split()))
n, k = f()
t = list(f())
d = {0: 0}
for q in t:
for i in range(1, k + 1): d[q * i] = i
for j in range(int(input())):
a = int(input())
p = [i + d[a - b] for b, i in list(d.items()) if a - b in d]
print(min(p) if p and min(p) <= k else -1) | python | test | qsol | codeparrot/apps | all |
Solve in Python:
Igor has fallen in love with Tanya. Now Igor wants to show his feelings and write a number on the fence opposite to Tanya's house. Igor thinks that the larger the number is, the more chance to win Tanya's heart he has.
Unfortunately, Igor could only get v liters of paint. He did the math and conclude... | n = int(input())
ai = [int(x) for x in input().split()]
mcDigit = 0
for i in range (9):
if ai[i] <= ai[mcDigit]:
mcDigit = i
di = [ x-mcDigit for x in ai]
resLen = n // ai[mcDigit]
res = [mcDigit] * resLen
remain = n - resLen * ai[mcDigit]
for i in range(resLen):
if remain <= 0:
break
d = 8... | python | test | qsol | codeparrot/apps | all |
I found an interesting problem on https://www.codechef.com/IARCSJUD/problems/LEAFEAT:
As we all know caterpillars love to eat leaves. Usually, a caterpillar sits on leaf, eats as much of it as it can (or wants), then stretches out to its full length to reach a new leaf with its front end, and finally "hops" to it by co... | from math import gcd
n, k = list(map(int, input().split()))
a = []
for i in range(k):
try:
a += list(map(int, input().split()))
except:
pass
ans = n
for i in range(1, 2**k):
b = bin(i)[2:].rjust(k, "0")
c = []
for j in range(k):
if(b[j] == '1'):
c.ap... | python | train | abovesol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/981/A:
A string is a palindrome if it reads the same from the left to the right and from the right to the left. For example, the strings "kek", "abacaba", "r" and "papicipap" are palindromes, while the strings "abb" and "iq" are not.
A substri... | # python3
from operator import eq
def is_palindrome(string):
half = len(string) // 2 + 1
return all(map(eq, string[:half], reversed(string)))
def main():
string = input()
first = string[0]
if all(symbol == first for symbol in string):
print(0)
else:
print(len(string) - 1 if ... | python | test | abovesol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/985/D:
You are going to the beach with the idea to build the greatest sand castle ever in your head! The beach is not as three-dimensional as you could have imagined, it can be decribed as a line of spots to pile up sand pillars. Spots are numb... | n,h = list(map(int, input().split()));
def g(d):
if (d < h):
return (d*(d+1))//2
d = d-h+1;
dd = d//2;
p = 2*((h-1)*dd + (dd*(dd+1))//2)
if (d%2 == 1):
p+= (h-1 + dd+1)
return ((h-1)*((h-1)+1))//2 + p;
#for i in range(0,20):
#print (i, g(i))
a = 0
b = 10**20
while (a!=b)... | python | test | abovesol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/629/C:
As Famil Door’s birthday is coming, some of his friends (like Gabi) decided to buy a present for him. His friends are going to buy a string consisted of round brackets since Famil Door loves string of brackets of length n more than any o... | n, m = list(map(int, input().split()))
s = input()
mod = 10 ** 9 + 7
c = b = 0
for x in s:
c += (x == '(') * 2 - 1
b = min(c, b)
d = [[1]]
for i in range(n - m):
nd = d[-1][1:] + [0] * 2
for j in range(1, i + 2):
nd[j] = (nd[j] + d[-1][j-1]) % mod
d.append(nd)
ans = 0
for i in range(n - m + ... | python | test | abovesol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/1100/C:
NN is an experienced internet user and that means he spends a lot of time on the social media. Once he found the following image on the Net, which asked him to compare the sizes of inner circles: [Image]
It turned out that the circles... | import math
n, r = [int(i) for i in input().split()]
t = math.sin(math.pi/n)
res = r*t/(1-t)
print(res) | python | test | abovesol | codeparrot/apps | all |
Solve in Python:
There are N children standing in a line. Each child is assigned a rating value.
You are giving candies to these children subjected to the following requirements:
Each child must have at least one candy.
Children with a higher rating get more candies than their neighbors.
What is the ... | class Solution:
def candy(self, ratings):
"""
:type ratings: List[int]
:rtype: int
"""
current_min = 1
current_max = 1
desc_len = 1
cnt = 1
for i in range(1, len(ratings)):
if ratings[i] < ratings[i - 1]:
... | python | train | qsol | codeparrot/apps | all |
Solve in Python:
Petya learned a new programming language CALPAS. A program in this language always takes one non-negative integer and returns one non-negative integer as well.
In the language, there are only three commands: apply a bitwise operation AND, OR or XOR with a given constant to the current integer. A progr... | n = int(input())
queries = list(input().split() for _ in range(n))
a, b = 0, (1<<10) - 1
for c, x in queries:
x = int(x)
if c == '|':
a, b = a | x, b | x
elif c == '&':
a, b = a & x, b & x
elif c == '^':
a, b = a ^ x, b ^ x
x, y, z = 0, (1<<10) - 1, 0
for i in range(10):
a_... | python | train | qsol | codeparrot/apps | all |
Solve in Python:
Ivan is playing a strange game.
He has a matrix a with n rows and m columns. Each element of the matrix is equal to either 0 or 1. Rows and columns are 1-indexed. Ivan can replace any number of ones in this matrix with zeroes. After that, his score in the game will be calculated as follows:
Initial... | m,n,k=list(map(int, input().split()))
a=[]
res=[0 for a in range(n)]
c=[0 for a in range(n)]
for i in range(n+1):
a.append([])
for i in range(m):
s=input()
for p in range(n):
a[p].append(int(s[p*2]))
for i in range(n):
for j in range(m):
if a[i][j]==1:
r=sum(a[i][j:min(k,m-j+... | python | test | qsol | codeparrot/apps | all |
Solve in Python:
Fennec is fighting with N monsters.
The health of the i-th monster is H_i.
Fennec can do the following two actions:
- Attack: Fennec chooses one monster. That monster's health will decrease by 1.
- Special Move: Fennec chooses one monster. That monster's health will become 0.
There is no way other th... | N, K = map(int, input().split(' '))
H_ls = list(map(int, input().split(' ')))
H_ls.sort(reverse=True)
print(sum(H_ls[K:])) | python | test | qsol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/1183/C:
Vova is playing a computer game. There are in total $n$ turns in the game and Vova really wants to play all of them. The initial charge of his laptop battery (i.e. the charge before the start of the game) is $k$.
During each turn Vova ... | for f in range(int(input())):
k,n,a,b = [int(i) for i in input().split()]
k -= 1
q = (k - n*b)
if q < 0:
print(-1)
else:
print(min(q // (a-b), n)) | python | test | abovesol | codeparrot/apps | all |
Solve in Python:
# Task
Let's call `product(x)` the product of x's digits. Given an array of integers a, calculate `product(x)` for each x in a, and return the number of distinct results you get.
# Example
For `a = [2, 8, 121, 42, 222, 23]`, the output should be `3`.
Here are the products of the array's elements:... | unique_digit_products = lambda a, r=__import__("functools").reduce: len({r(int.__mul__, map(int, str(e))) for e in a}) | python | train | qsol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/645/D:
While Farmer John rebuilds his farm in an unfamiliar portion of Bovinia, Bessie is out trying some alternative jobs. In her new gig as a reporter, Bessie needs to know about programming competition results as quickly as possible. When sh... | n, m = [int(i) for i in input().split()]
n += 1 # one-indexed
A = [[int(i) for i in input().split()] for j in range(m)]
m += 1
def check(upper):
p = [[] for i in range(n)]
d = [0] * n #record num of parents
for u, v in A[:upper]:
p[u].append(v) # form arc from u to v
d[v] += 1
if d.coun... | python | test | abovesol | codeparrot/apps | all |
Solve in Python:
How many integer sequences A_1,A_2,\ldots,A_N of length N satisfy all of the following conditions?
- 0 \leq A_i \leq 9
- There exists some i such that A_i=0 holds.
- There exists some i such that A_i=9 holds.
The answer can be very large, so output it modulo 10^9 + 7.
-----Constraints-----
- 1 \le... | N = int(input())
MOD = 10**9+7
print((10**N-(9**N+9**N-8**N))%MOD) | python | test | qsol | codeparrot/apps | all |
Solve in Python:
We have an array with string digits that occurrs more than once, for example, ```arr = ['1', '2', '2', '2', '3', '3']```. How many different string numbers can be generated taking the 6 elements at a time?
We present the list of them below in an unsorted way:
```
['223213', '312322', '223312', '22213... | from collections import Counter
from operator import floordiv
from functools import reduce
from math import factorial
def proc_arr(arr):
count = reduce(floordiv, map(factorial, Counter(arr).values()), factorial(len(arr)))
mini = int(''.join(sorted(arr)))
maxi = int(''.join(sorted(arr, reverse=True)))
r... | python | train | qsol | codeparrot/apps | all |
Solve in Python:
Mike decided to teach programming to children in an elementary school. He knows that it is not an easy task to interest children in that age to code. That is why he decided to give each child two sweets.
Mike has $n$ sweets with sizes $a_1, a_2, \ldots, a_n$. All his sweets have different sizes. That ... | n = int(input())
a = list(map(int, input().split()))
sm = []
for i in range(n):
for j in range(i + 1, n):
sm.append(a[i] + a[j])
cnt = dict()
ans = 0
for i in sm:
if i not in cnt.keys():
cnt[i] = 1
else:
cnt[i] += 1
for i in sm:
ans = max(cnt[i], ans)
print(ans) | python | test | qsol | codeparrot/apps | all |
I found an interesting problem on https://www.codechef.com/SCAT2020/problems/SC_04:
-----Problem Statement-----
Harry Potter has one biscuit and zero rupee in his pocket. He will perform the following operations exactly $K$ times in total, in the order he likes:
- Hit his pocket, which magically increases the number of... | import sys
# sys.stdin = open('input.txt', 'r')
# sys.stdout = open('output.txt', 'w')
import math
import collections
from sys import stdin,stdout,setrecursionlimit
import bisect as bs
setrecursionlimit(2**20)
M = 10**9+7
# T = int(stdin.readline())
T = 1
for _ in range(T):
# n = int(stdin.readl... | python | train | abovesol | codeparrot/apps | all |
Solve in Python:
##Task:
You have to write a function **pattern** which creates the following pattern upto n number of rows. *If the Argument is 0 or a Negative Integer then it should return "" i.e. empty string.*
##Examples:
pattern(4):
1234
234
34
4
pattern(6):
123456
23456
3... | pattern = lambda n: "\n".join(["".join([str(y) for y in range(x + 1, n + 1)]) for x in range(n)]); | python | train | qsol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/1245/E:
Hyakugoku has just retired from being the resident deity of the South Black Snail Temple in order to pursue her dream of becoming a cartoonist. She spent six months in that temple just playing "Cat's Cradle" so now she wants to try a di... | 3
import array
from fractions import Fraction
import functools
import itertools
import math
import os
import sys
def main():
H = [read_ints() for _ in range(10)]
print(solve(H))
def pos_idx(x, y):
i = y * 10
if y % 2 == 0:
i += x
else:
i += 9 - x
return i
def idx_pos(i):
... | python | test | abovesol | codeparrot/apps | all |
I found an interesting problem on https://www.codewars.com/kata/5897d94dd07028546c00009d:
# Task
Let's call `product(x)` the product of x's digits. Given an array of integers a, calculate `product(x)` for each x in a, and return the number of distinct results you get.
# Example
For `a = [2, 8, 121, 42, 222, 23]`, t... | unique_digit_products = lambda a, r=__import__("functools").reduce: len({r(int.__mul__, map(int, str(e))) for e in a}) | python | train | abovesol | codeparrot/apps | all |
Solve in Python:
Berland year consists of $m$ months with $d$ days each. Months are numbered from $1$ to $m$. Berland week consists of $w$ days. The first day of the year is also the first day of the week. Note that the last week of the year might be shorter than $w$ days.
A pair $(x, y)$ such that $x < y$ is ambiguou... | import sys
readline = sys.stdin.readline
readlines = sys.stdin.readlines
ns = lambda: readline().rstrip()
ni = lambda: int(readline().rstrip())
nm = lambda: map(int, readline().split())
nl = lambda: list(map(int, readline().split()))
prn = lambda x: print(*x, sep='\n')
def gcd(a, b):
while b:
a, b = b, a%... | python | train | qsol | codeparrot/apps | all |
Solve in Python:
Given a positive integer num, write a function which returns True if num is a perfect square else False.
Note: Do not use any built-in library function such as sqrt.
Example 1:
Input: 16
Returns: True
Example 2:
Input: 14
Returns: False
Credits:Special thanks to @elmirap for adding this pro... | class Solution:
def isPerfectSquare(self, num):
"""
:type num: int
:rtype: bool
"""
p, r = 1, (num>>1) + 1
while p <= r:
mid = (p + r) >> 1
sq = mid*mid
if sq == num:
return True
if sq >= num:... | python | train | qsol | codeparrot/apps | all |
Solve in Python:
Let us denote by f(x, m) the remainder of the Euclidean division of x by m.
Let A be the sequence that is defined by the initial value A_1=X and the recurrence relation A_{n+1} = f(A_n^2, M).
Find \displaystyle{\sum_{i=1}^N A_i}.
-----Constraints-----
- 1 \leq N \leq 10^{10}
- 0 \leq X < M \leq 10^5... | from collections import deque
n, x, m = map(int, input().split())
A = deque()
G = [-1 for i in range(m)]
t = 0
total = 0
while G[x] == -1:
A.append(x)
G[x] = t
t += 1
total += x
x = (x*x) % m
cycle = t - G[x]
s = 0
for i in range(cycle):
s += A[G[x] + i]
ans = 0
if n < t:
for i in range(... | python | test | qsol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/1388/C:
Uncle Bogdan is in captain Flint's crew for a long time and sometimes gets nostalgic for his homeland. Today he told you how his country introduced a happiness index.
There are $n$ cities and $n−1$ undirected roads connecting pairs of ... | from sys import stdin
import sys
sys.setrecursionlimit(300000)
def dfs(v,pa):
good = 0
bad = 0
for nex in lis[v]:
if nex != pa:
nans,ng,nb = dfs(nex,v)
if not nans:
return nans,0,0
good += ng
bad += nb
num = good + bad + p[v]
... | python | test | abovesol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/602/A:
After seeing the "ALL YOUR BASE ARE BELONG TO US" meme for the first time, numbers X and Y realised that they have different bases, which complicated their relations.
You're given a number X represented in base b_{x} and a number Y repr... | z1 = list(map(int,input().split()))
x = list(map(int,input().split()))
z2 = list(map(int,input().split()))
y= list(map(int,input().split()))
n1, b1 = z1[0],z1[1]
n2, b2 = z2[0],z2[1]
ansx = ansy = 0
for i in range(n1):
ansx+= x[n1-i-1]*(b1**i)
for i in range(n2):
ansy+= y[n2-i-1]*(b2**i)
if ansx == ansy... | python | test | abovesol | codeparrot/apps | all |
Solve in Python:
# Task
You are given a string `s`. Every letter in `s` appears once.
Consider all strings formed by rearranging the letters in `s`. After ordering these strings in dictionary order, return the middle term. (If the sequence has a even length `n`, define its middle term to be the `(n/2)`th term.)
#... | def middle_permutation(s):
s = ''.join(sorted(s))
m = int(len(s) / 2)
x = s[m-1:m+1] if len(s) % 2 else s[m-1]
return (s.replace(x, '') + x)[::-1] | python | train | qsol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/1167/C:
In some social network, there are $n$ users communicating with each other in $m$ groups of friends. Let's analyze the process of distributing some news between users.
Initially, some user $x$ receives the news from some source. Then he... | import sys
input = sys.stdin.readline
class Union_Find():
def __init__(self, num):
self.par = [-1]*(num+1)
self.siz = [1]*(num+1)
def same_checker(self, x, y):
return self.find(x) == self.find(y)
def find(self, x):
if self.par[x] < 0:
return x
else:
... | python | test | abovesol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/1055/B:
Alice's hair is growing by leaps and bounds. Maybe the cause of it is the excess of vitamins, or maybe it is some black magic...
To prevent this, Alice decided to go to the hairdresser. She wants for her hair length to be at most $l$ c... | gcd = lambda a, b: gcd(b, a % b) if b else a
def main():
n, m, l = list(map(int, input().split()))
arr = list(map(int, input().split()))
brr = [i > l for i in arr]
total = 0
for i in range(len(brr)):
if brr[i] and (not i or not brr[i - 1]):
total += 1
for i in range(m):
... | python | test | abovesol | codeparrot/apps | all |
I found an interesting problem on https://www.codechef.com/SIC2016/problems/SANTA:
It's Christmas time and Santa is in town. There are N children each having a bag with a mission to fill in as many toffees as possible. They are accompanied by a teacher whose ulterior motive is to test their counting skills. The toffees... | import numpy as np
N=10**6+1
t=eval(input())
inp = ()
t1=ord('z')
#bag=[[0 for _ in xrange(t1)] for _ in xrange(N+1)]
bag=np.zeros((N+1,t1),dtype=np.int)
#print bag
while t:
t-=1
inp=input().split()
t2=ord(inp[3]) - ord('a')
t3=int(inp[1])
t4=int(inp[2]) + 1
if inp[0]=="1":
#print "enter"
bag[t3][t2]+=int(... | python | train | abovesol | codeparrot/apps | all |
Solve in Python:
The chef is trying to solve some pattern problems, Chef wants your help to code it. Chef has one number K(odd) to form a new pattern. Help the chef to code this pattern problem.
-----Input:-----
- First-line will contain $T$, the number of test cases. Then the test cases follow.
- Each test case cont... | t=int(input())
while(t):
n=int(input())
p=int(n/2)
p=p+1
for i in range(0,p):
for j in range(0,i):
if(j>=0):
print(end=" ")
print("*")
p=p-2
for i in range(p,0,-1):
for j in range(0,i):
print(end=" ")
print("*")
if(... | python | train | qsol | codeparrot/apps | all |
I found an interesting problem on https://www.codewars.com/kata/59841e5084533834d6000025:
Iahub got bored, so he invented a game to be played on paper.
He writes n integers a1, a2, ..., an. Each of those integers can be either 0 or 1. He's allowed to do exactly one move: he chooses two indices i and j (1 ≤ i ≤ j ≤ n) ... | def flipping_game(num):
all_pairs = ((i, j) for i in range(len(num)) for j in range(i + 1, len(num) + 1))
ones = (sum(num[:i]) + j - i - sum(num[i:j]) + sum(num[j:]) for i, j in all_pairs)
return max(ones) | python | train | abovesol | codeparrot/apps | all |
Solve in Python:
For this problem you must create a program that says who ate the last cookie. If the input is a string then "Zach" ate the cookie. If the input is a float or an int then "Monica" ate the cookie. If the input is anything else "the dog" ate the cookie. The way to return the statement is:
"Who ate the las... | def cookie(x):
if isinstance(x, bool): return "Who ate the last cookie? It was the dog!"
if isinstance(x, str): return "Who ate the last cookie? It was Zach!"
if isinstance(x, (int,float)): return "Who ate the last cookie? It was Monica!"
return "Who ate the last cookie? It was the dog!" | python | train | qsol | codeparrot/apps | all |
Solve in Python:
Jzzhu has picked n apples from his big apple tree. All the apples are numbered from 1 to n. Now he wants to sell them to an apple store.
Jzzhu will pack his apples into groups and then sell them. Each group must contain two apples, and the greatest common divisor of numbers of the apples in each grou... | """
Codeforces Round 257 Div 1 Problem C
Author : chaotic_iak
Language: Python 3.3.4
"""
def read(mode=2):
# 0: String
# 1: List of strings
# 2: List of integers
inputs = input().strip()
if mode == 0:
return inputs
if mode == 1:
return inputs.split()
if mode == 2:
... | 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.