Dataset Viewer
Auto-converted to Parquet Duplicate
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://www.codechef.com/ENDE2020/problems/ENCDEC2: You are the principal of the Cake school in chefland and today is your birthday. You want to treat each of the children with a small cupcake which is made by you. But there is a problem, You don't know how many students are present to...
# cook your dish here t=int(input()) for i in range(t): l=list(map(int,input().split())) r=l[0] c=l[1] print(r*c)
python
train
abovesol
codeparrot/apps
all
Solve in Python: Simon has a prime number x and an array of non-negative integers a_1, a_2, ..., a_{n}. Simon loves fractions very much. Today he wrote out number $\frac{1}{x^{a} 1} + \frac{1}{x^{a_{2}}} + \ldots + \frac{1}{x^{a_{n}}}$ on a piece of paper. After Simon led all fractions to a common denominator and summ...
n, x = map(int, input().split()) t = list(map(int, input().split())) b = max(t) k = t.count(b) r = sum(t) s = r - b while k % x == 0: b -= 1 s += 1 k = k // x + t.count(b) print(pow(x, min(r, s), 1000000007))
python
test
qsol
codeparrot/apps
all
Solve in Python: During the quarantine, Sicromoft has more free time to create the new functions in "Celex-2021". The developers made a new function GAZ-GIZ, which infinitely fills an infinite table to the right and down from the upper left corner as follows: [Image] The cell with coordinates $(x, y)$ is at the inte...
import sys input = sys.stdin.readline def value(x,y): ANS=(x+y-2)*(x+y-1)//2 return ANS+x t=int(input()) for tests in range(t): x1,y1,x2,y2=list(map(int,input().split())) print(1+(x2-x1)*(y2-y1))
python
test
qsol
codeparrot/apps
all
Solve in Python: Recently, Olya received a magical square with the size of $2^n\times 2^n$. It seems to her sister that one square is boring. Therefore, she asked Olya to perform exactly $k$ splitting operations. A Splitting operation is an operation during which Olya takes a square with side $a$ and cuts it into 4 e...
import sys import math input = sys.stdin.readline testcase=int(input()) T=[list(map(int,input().split())) for i in range(testcase)] def bi(n,k): MIN=0 MAX=n while MAX>MIN+1: bn=(MIN+MAX)//2 if math.log2(k+2+bn)<bn+1: MAX=bn elif math.log2(k+2+bn)==bn+1: ret...
python
test
qsol
codeparrot/apps
all
Solve in Python: Recently you have received two positive integer numbers $x$ and $y$. You forgot them, but you remembered a shuffled list containing all divisors of $x$ (including $1$ and $x$) and all divisors of $y$ (including $1$ and $y$). If $d$ is a divisor of both numbers $x$ and $y$ at the same time, there are tw...
n = int(input()) a = list(map(int, input().split())) x = max(a) b = [] for i in range(1, x + 1) : if x % i == 0 : b.append(i) for i in range(len(b)) : a.remove(b[i]) print(x, max(a))
python
test
qsol
codeparrot/apps
all
I found an interesting problem on https://www.codechef.com/problems/ADTRI: Rupsa really loves triangles. One day she came across an equilateral triangle having length of each side as an integer N. She started wondering if it was possible to transform the triangle keeping two sides fixed and alter the third side such th...
t=int(input()) import math for i in range(t): b=[] n=int(input()) for p in range(n+1,2*n): if p%2==0: a= math.sqrt(n**2 - (p/2)**2) if a-int(a)==0: b.append(i) if len(b)==0: print("NO") elif len(b)!=0: print("YES")
python
train
abovesol
codeparrot/apps
all
I found an interesting problem on https://codeforces.com/problemset/problem/1392/F: Omkar is standing at the foot of Celeste mountain. The summit is $n$ meters away from him, and he can see all of the mountains up to the summit, so for all $1 \leq j \leq n$ he knows that the height of the mountain at the point $j$ mete...
n = int(input());tot = sum(map(int, input().split()));extra = (n * (n - 1))//2;smol = (tot - extra) // n;out = [smol + i for i in range(n)] for i in range(tot - sum(out)):out[i] += 1 print(' '.join(map(str,out)))
python
test
abovesol
codeparrot/apps
all
I found an interesting problem on https://www.codewars.com/kata/5ae8e14c1839f14b2c00007a: # Idea In the world of graphs exists a structure called "spanning tree". It is unique because it's created not on its own, but based on other graphs. To make a spanning tree out of a given graph you should remove all the edges wh...
def make_spanning_tree(edges, t): edges.sort(reverse=True) last_node = ord(edges[0][0][0]) - 65 edges.sort() edges.sort(key=lambda edges: edges[1]) if(t == 'max'): edges.reverse() nonlocal parent parent = [int(x) for x in range(last_node+10000)] result = [] for edge in...
python
train
abovesol
codeparrot/apps
all
Solve in Python: Consider a football tournament where n teams participate. Each team has two football kits: for home games, and for away games. The kit for home games of the i-th team has color x_{i} and the kit for away games of this team has color y_{i} (x_{i} ≠ y_{i}). In the tournament, each team plays exactly one...
n = int( input() ) x, y = [0] * n, [0] * n for i in range( n ): x[i], y[i] = map( int, input().split() ) ans = [0] * 100001 for elm in x: ans[elm] += 1 for elm in y: print( n - 1 + ans[elm], n - 1 - ans[elm] )
python
test
qsol
codeparrot/apps
all
Solve in Python: In this kata, you have to define a function named **func** that will take a list as input. You must try and guess the pattern how we get the output number and return list - **[output number,binary representation,octal representation,hexadecimal representation]**, but **you must convert that specific n...
def binary(x): result = [] while True: remainder = x % 2 result.append(str(remainder)) x = x // 2 if x == 0: break result.reverse() return "".join(result) def octal(x): result = [] while True: remainder = x % 8 result.append(str(rema...
python
train
qsol
codeparrot/apps
all
I found an interesting problem on https://codeforces.com/problemset/problem/424/A: Pasha has many hamsters and he makes them work out. Today, n hamsters (n is even) came to work out. The hamsters lined up and each hamster either sat down or stood up. For another exercise, Pasha needs exactly $\frac{n}{2}$ hamsters to ...
n, t = int(input()), input() a, b = 'x', 'X' k = t.count(a) - n // 2 if k: t = list(t) if k < 0: a, b, k = b, a, -k print(k) for i, c in enumerate(t): if c == a: t[i] = b k -= 1 if k == 0: break print(''.join(t)) else: print('0\n' + t)
python
test
abovesol
codeparrot/apps
all
I found an interesting problem on https://www.codewars.com/kata/5c765a4f29e50e391e1414d4: [Haikus](https://en.wikipedia.org/wiki/Haiku_in_English) are short poems in a three-line format, with 17 syllables arranged in a 5–7–5 pattern. Your task is to check if the supplied text is a haiku or not. ### About syllables [...
def is_haiku(s,v='aeiouy'): C=[] for x in[a.strip('.;:!?,').split()for a in s.lower().split('\n')]: t='' for y in x: if y.endswith('e')and any(c in y[:-1]for c in v):y=y[:-1] for c in y:t+=c if c in v else' 'if t and t[-1]!=' 'else'' t+=' ' C+=[len(t.s...
python
train
abovesol
codeparrot/apps
all
Solve in Python: Takahashi has K 500-yen coins. (Yen is the currency of Japan.) If these coins add up to X yen or more, print Yes; otherwise, print No. -----Constraints----- - 1 \leq K \leq 100 - 1 \leq X \leq 10^5 -----Input----- Input is given from Standard Input in the following format: K X -----Output----- If ...
a,b=input().split();print('YNeos'[eval(a+'*500<'+b)::2])
python
test
qsol
codeparrot/apps
all
I found an interesting problem on https://codeforces.com/problemset/problem/1364/D: Given a connected undirected graph with $n$ vertices and an integer $k$, you have to either: either find an independent set that has exactly $\lceil\frac{k}{2}\rceil$ vertices. or find a simple cycle of length at most $k$. An indepen...
import sys input = sys.stdin.readline from collections import deque class Graph(object): """docstring for Graph""" def __init__(self,n,d): # Number of nodes and d is True if directed self.n = n self.graph = [[] for i in range(n)] self.parent = [-1 for i in range(n)] self.directed = d def addEdge(self,x,y...
python
test
abovesol
codeparrot/apps
all
I found an interesting problem on https://codeforces.com/problemset/problem/1108/B: Recently you have received two positive integer numbers $x$ and $y$. You forgot them, but you remembered a shuffled list containing all divisors of $x$ (including $1$ and $x$) and all divisors of $y$ (including $1$ and $y$). If $d$ is a...
n = int(input()) a = list(map(int, input().split())) x = max(a) b = [] for i in range(1, x + 1) : if x % i == 0 : b.append(i) for i in range(len(b)) : a.remove(b[i]) print(x, max(a))
python
test
abovesol
codeparrot/apps
all
Solve in Python: The only difference between easy and hard versions is the number of elements in the array. You are given an array $a$ consisting of $n$ integers. In one move you can choose any $a_i$ and divide it by $2$ rounding down (in other words, in one move you can set $a_i := \lfloor\frac{a_i}{2}\rfloor$). You...
from collections import * n,k = [int(i) for i in input().split()] A = [int(i) for i in input().split()] A.sort() d = defaultdict(lambda: [0,0]) for i in A: num = i stp = 0 while num>0: if d[num][0]<k: d[num][0]+=1 d[num][1]+=stp num = num//2 stp +=1 if d[num][0]<k: d[num][0]+=1 d[num][1]+=stp mn ...
python
test
qsol
codeparrot/apps
all
I found an interesting problem on https://codeforces.com/problemset/problem/445/B: DZY loves chemistry, and he enjoys mixing chemicals. DZY has n chemicals, and m pairs of them will react. He wants to pour these chemicals into a test tube, and he needs to pour them in one by one, in any order. Let's consider the dan...
n, m = map(int, input().split()) p = list(range(n + 1)) s = [{i} for i in p] for i in range(m): x, y = map(int, input().split()) x, y = p[x], p[y] if x != y: if len(s[x]) < len(s[y]): for k in s[x]: p[k] = y s[y].add(k) s[x].clear() els...
python
test
abovesol
codeparrot/apps
all
Solve in Python: Alice and Bob have participated to a Rock Off with their bands. A jury of true metalheads rates the two challenges, awarding points to the bands on a scale from 1 to 50 for three categories: Song Heaviness, Originality, and Members' outfits. For each one of these 3 categories they are going to be awar...
def solve(a, b): count_a = 0 count_b = 0 for i in range(len(a)): if a[i] > b[i]: count_a +=1 elif a[i] < b[i]: count_b +=1 return f'{count_a}, {count_b}: that looks like a "draw"! Rock on!' if count_a == count_b else f'{count_a}, {count_b}: Alice made "Kurt" proud...
python
train
qsol
codeparrot/apps
all
Solve in Python: Little girl Tanya is learning how to decrease a number by one, but she does it wrong with a number consisting of two or more digits. Tanya subtracts one from a number by the following algorithm: if the last digit of the number is non-zero, she decreases the number by one; if the last digit of the num...
n,k = list(map(int,input().split())) for i in range(k): if n%10 == 0: n//=10 else: n -=1 print(n)
python
test
qsol
codeparrot/apps
all
Solve in Python: Today on a lecture about strings Gerald learned a new definition of string equivalency. Two strings a and b of equal length are called equivalent in one of the two cases: They are equal. If we split string a into two halves of the same size a_1 and a_2, and string b into two halves of the same size ...
def F(s): if len(s)%2==1:return s s1 = F(s[:len(s)//2]) s2 = F(s[len(s)//2:]) if s1 < s2:return s1 + s2 return s2 + s1 if F(input()) == F(input()): print("YES") else: print("NO")
python
test
qsol
codeparrot/apps
all
Solve in Python: Recall that MEX of an array is a minimum non-negative integer that does not belong to the array. Examples: for the array $[0, 0, 1, 0, 2]$ MEX equals to $3$ because numbers $0, 1$ and $2$ are presented in the array and $3$ is the minimum non-negative integer not presented in the array; for the array ...
import sys input = sys.stdin.readline q,x=list(map(int,input().split())) seg_el=1<<((x+1).bit_length()) SEG=[0]*(2*seg_el) def add1(n,seg_el): i=n+seg_el SEG[i]+=1 i>>=1 while i!=0: SEG[i]=min(SEG[i*2],SEG[i*2+1]) i>>=1 def getvalues(l,r): L=l+seg_el R=r+seg_el ...
python
test
qsol
codeparrot/apps
all
Solve in Python: You are given a tree with $N$ vertices (numbered $1$ through $N$) and a bag with $N$ markers. There is an integer written on each marker; each of these integers is $0$, $1$ or $2$. You must assign exactly one marker to each vertex. Let's define the unattractiveness of the resulting tree as the maximum ...
# cook your dish here import numpy as np tests = int(input()) for _ in range(tests): n = int(input()) weights = [int(j) for j in input().split()] edges = [[0] for _ in range(n-1)] for i in range(n-1): edges[i] = [int(j)-1 for j in input().split()] vertex_set = [[] for _ in range(n)] for i in ran...
python
train
qsol
codeparrot/apps
all
I found an interesting problem on https://www.codewars.com/kata/5416f1834c24604c46000696: In computer science, cycle detection is the algorithmic problem of finding a cycle in a sequence of iterated function values. For any function ƒ, and any initial value x0 in S, the sequence of iterated function values x0,x1=...
def cycle(sequence): memo = {} for i, item in enumerate(sequence): if item in memo: return [memo[item], i - memo[item]] memo[item] = i return []
python
train
abovesol
codeparrot/apps
all
I found an interesting problem on https://codeforces.com/problemset/problem/1204/D2: The only difference between easy and hard versions is the length of the string. You can hack this problem if you solve it. But you can hack the previous problem only if you solve both problems. Kirk has a binary string $s$ (a string w...
S = list(map(int,input().strip())) N = len(S) stack = [] for i in range(N): s = S[i] if s == 0 and stack and stack[-1][0] == 1: stack.pop() else: stack.append((s, i)) T = S[:] if stack: for i in tuple(map(list, zip(*stack)))[1]: T[i] = 0 print(''.join(map(str, T)))
python
test
abovesol
codeparrot/apps
all
Solve in Python: You are given an array $a$ consisting of $n$ integers. You have to find the length of the smallest (shortest) prefix of elements you need to erase from $a$ to make it a good array. Recall that the prefix of the array $a=[a_1, a_2, \dots, a_n]$ is a subarray consisting several first elements: the prefix...
def solve(): n = int(input()) a = list(map(int, input().split())) prev = a[-1] cnt = 1 status = 0 for i in range(n - 2, -1, -1): v = a[i] if status == 0: if v < prev: status = 1 cnt += 1 prev = v continue eli...
python
train
qsol
codeparrot/apps
all
I found an interesting problem on https://codeforces.com/problemset/problem/1342/B: Let's say string $s$ has period $k$ if $s_i = s_{i + k}$ for all $i$ from $1$ to $|s| - k$ ($|s|$ means length of string $s$) and $k$ is the minimum positive integer with this property. Some examples of a period: for $s$="0101" the per...
def read_int(): return int(input()) def read_ints(): return list(map(int, input().split(' '))) t = read_int() for case_num in range(t): a = input() n = len(a) one = 0 for c in a: if c == '1': one += 1 if one == 0 or one == n: print(a) else: print('...
python
test
abovesol
codeparrot/apps
all
Solve in Python: Zonal Computing Olympiad 2013, 10 Nov 2012 Little Red Riding Hood is carrying a basket with berries through the forest to her grandmother's house. The forest is arranged in the form of a square N × N grid of cells. The top left corner cell, where Little Red Riding Hood starts her journey, is numbere...
def main(): from sys import stdin, stdout rl = stdin.readline n, m = (int(x) for x in rl().split()) grid = [[int(x) for x in rl().split()] for _ in range(n)] charms = [[int(x) for x in rl().split()] for _ in range(m)] n_inf = -9999 dp = [[n_inf] * n for _ in range(n)] for c in charms: c[0] -= 1...
python
train
qsol
codeparrot/apps
all
Solve in Python: Kira likes to play with strings very much. Moreover he likes the shape of 'W' very much. He takes a string and try to make a 'W' shape out of it such that each angular point is a '#' character and each sides has same characters. He calls them W strings. For example, the W string can be formed from "aaa...
def frequency(s,n): f=[[0 for i in range(26)]for j in range(n+1)] count=0 for i in range(n): if s[i]!="#": f[count][ord(s[i])-97]+=1 else: count+=1 for j in range(26): f[count][j]=f[count-1][j] return (f,count) def solve(s): n=...
python
train
qsol
codeparrot/apps
all
I found an interesting problem on https://codeforces.com/problemset/problem/1157/G: You are given a binary matrix $a$ of size $n \times m$. A binary matrix is a matrix where each element is either $0$ or $1$. You may perform some (possibly zero) operations with this matrix. During each operation you can inverse the ro...
import sys input = sys.stdin.readline n,m=list(map(int,input().split())) A=[list(map(int,input().split())) for i in range(n)] for i in range(m): #一行目をi-1まで0にする ANSR=[0]*n ANSC=[0]*m for j in range(i): if A[0][j]==1: ANSC[j]=1 for j in range(i,m): if A[0][j]==0: ...
python
test
abovesol
codeparrot/apps
all
I found an interesting problem on https://www.codewars.com/kata/58a6a56942fd72afdd000161: # Task In a black and white image we can use `1` instead of black pixels and `0` instead of white pixels. For compression image file we can reserve pixels by consecutive pixels who have the same color. Your task is to det...
from re import findall def black_and_white(height, width, compressed): compr = ''.join(('0' if i % 2 else '1') * v for i, v in enumerate(compressed)) res = [] for i in range(0, len(compr), width): row, temp, black = compr[i: i + width], [], True m = [(c, len(g)) for...
python
train
abovesol
codeparrot/apps
all
I found an interesting problem on https://codeforces.com/problemset/problem/646/A: Три брата договорились о встрече. Пронумеруем братьев следующим образом: пусть старший брат имеет номер 1, средний брат имеет номер 2, а младший брат — номер 3. Когда пришло время встречи, один из братьев опоздал. По заданным номерам д...
a, b = [int(x) for x in input().split()] for i in range(1, 4): if i != a and i != b: print(i)
python
test
abovesol
codeparrot/apps
all
I found an interesting problem on https://www.codechef.com/LTIME39/problems/ALPHABET: Not everyone probably knows that Chef has younder brother Jeff. Currently Jeff learns to read. He knows some subset of the letter of Latin alphabet. In order to help Jeff to study, Chef gave him a book with the text consisting of N wo...
S = input() N = int(input()) while N != 0: W = input() flag = 0 for i in range(0, len(W)): if W[i] in S: continue else: flag = 1 break if flag == 0: print("Yes") else: print("No") N -= 1
python
train
abovesol
codeparrot/apps
all
I found an interesting problem on https://www.codewars.com/kata/559379505c859be5a9000034: < PREVIOUS KATA NEXT KATA > ## Task: You have to write a function `pattern` which returns the following Pattern(See Examples) upto desired number of rows. * Note:`Returning` the pattern is not the same as `Printing` the patter...
def pattern(n, y=1, *_): if n < 1: return '' ans, p, y = [], [], max(y, 1) for i in range(1, n+1): t = [' '] * (n * 2 - 1) t[i - 1] = t[n * 2 - 1 - 1 - i + 1] = str(i % 10) p.append(''.join(t)) p += p[:-1][::-1] for _ in range(y): ans += p[1:] if ans else p ...
python
train
abovesol
codeparrot/apps
all
I found an interesting problem on https://leetcode.com/problems/minimum-number-of-flips-to-convert-binary-matrix-to-zero-matrix/: Given a m x n binary matrix mat. In one step, you can choose one cell and flip it and all the four neighbours of it if they exist (Flip is changing 1 to 0 and 0 to 1). A pair of cells are ca...
class Solution: def minFlips(self, mat: List[List[int]]) -> int: m = len(mat) n = len(mat[0]) start = sum(val << (i*n + j) for i, row in enumerate(mat) for j, val in enumerate(row)) queue = collections.deque([(start, 0)]) seen = { start } di...
python
train
abovesol
codeparrot/apps
all
Solve in Python: Mahmoud and Ehab play a game called the even-odd game. Ehab chooses his favorite integer n and then they take turns, starting from Mahmoud. In each player's turn, he has to choose an integer a and subtract it from n such that: 1 ≤ a ≤ n. If it's Mahmoud's turn, a has to be even, but if it's Ehab's tu...
def li(): return list(map(int, input().split())) n = int(input()) if n % 2 == 0: print('Mahmoud') else: print('Ehab')
python
test
qsol
codeparrot/apps
all
Solve in Python: Imagine a city with n horizontal streets crossing m vertical streets, forming an (n - 1) × (m - 1) grid. In order to increase the traffic flow, mayor of the city has decided to make each street one way. This means in each horizontal street, the traffic moves only from west to east or only from east to ...
def main(): n, m = map(int, input().split()) nm = n * m neigh = [[] for _ in range(nm)] for y, c in enumerate(input()): for x in range(y * m + 1, y * m + m): if c == '<': neigh[x].append(x - 1) else: neigh[x - 1].append(x) for x, c in e...
python
test
qsol
codeparrot/apps
all
Solve in Python: Hi guys, welcome to introduction to DocTesting. The kata is composed of two parts; in part (1) we write three small functions, and in part (2) we write a few doc tests for those functions. Lets talk about the functions first... The reverse_list function takes a list and returns the reverse of it...
def reverse_list(a): """Takes an list and returns the reverse of it. If x is empty, return []. >>> reverse_list([1]) [1] >>> reverse_list([]) [] """ return a[::-1] def sum_list(a): """Takes a list, and returns the sum of that list. If x is empty list, return 0. >>> su...
python
train
qsol
codeparrot/apps
all
Solve in Python: Given a string, return the minimal number of parenthesis reversals needed to make balanced parenthesis. For example: ```Javascript solve(")(") = 2 Because we need to reverse ")" to "(" and "(" to ")". These are 2 reversals. solve("(((())") = 1 We need to reverse just one "(" parenthesis to make it b...
class Stack: def __init__(self): self.items = [] def is_empty(self): return self.items == [] def push(self, item): self.items.append(item) def pop(self): return self.items.pop() def peek(self): return self.items[-1] def size(self): return len(...
python
train
qsol
codeparrot/apps
all
Solve in Python: In some other world, today is Christmas. Mr. Takaha decides to make a multi-dimensional burger in his party. A level-L burger (L is an integer greater than or equal to 0) is the following thing: - A level-0 burger is a patty. - A level-L burger (L \geq 1) is a bun, a level-(L-1) burger, a patty, anot...
n,x=map(int,input().split()) def func(m,y): if y==0:return 0 ret=0 t=4*pow(2,m)-3 if y>=t-1: ret=pow(2,m+1)-1 elif y==(t-1)//2: ret=pow(2,m)-1 elif y==(t-1)//2+1: ret=pow(2,m) elif y>(t-1)//2+1: ret=pow(2,m) ret+=func(m-1,y-(t-1)//2-1) else: ret=func(m-1,y-1) return ret print...
python
test
qsol
codeparrot/apps
all
Solve in Python: An Ironman Triathlon is one of a series of long-distance triathlon races organized by the World Triathlon Corporaion (WTC). It consists of a 2.4-mile swim, a 112-mile bicycle ride and a marathon (26.2-mile) (run, raced in that order and without a break. It hurts... trust me. Your task is to take a dis...
def i_tri(s): out = 'Starting Line... Good Luck!' if s>0.0 and s<=2.4 : out = {'Swim': f'{140.6 - s:.2f} to go!'} if s>2.4 and s<=114.4 : out = {'Bike': f'{140.6 - s:.2f} to go!'} if s>114.4 and s<130.6 : out = {'Run' : f'{140.6 - s:.2f} to go!'} if s>=130.6 and s<140.6 : out = {'Run' : '...
python
train
qsol
codeparrot/apps
all
Solve in Python: Recently, a start up by two students of a state university of city F gained incredible popularity. Now it's time to start a new company. But what do we call it? The market analysts came up with a very smart plan: the name of the company should be identical to its reflection in a mirror! In other words...
good = set('AHIMOTUVWXY') in_str = input("") str_len = len(in_str) result = "" i = 0 while(i < str_len/2): if((in_str[i] in good) and (in_str[i] == in_str[-1-i])): i += 1 else: result = "NO" break if(result != "NO"): result = "YES" print(result)
python
test
qsol
codeparrot/apps
all
I found an interesting problem on https://www.codewars.com/kata/5b7bae02402fb702ce000159: Assume we take a number `x` and perform any one of the following operations: ```Pearl a) Divide x by 3 (if it is divisible by 3), or b) Multiply x by 2 ``` After each operation, we write down the result. If we start with `9`, we c...
def solve(lst): return sorted(lst, key=factors_count) def factors_count(n): result = [] for k in (2, 3): while n % k == 0: n //= k result.append(k) return -result.count(3), result.count(2)
python
train
abovesol
codeparrot/apps
all
I found an interesting problem on https://codeforces.com/problemset/problem/1430/E: You are given a string $s$. You have to reverse it — that is, the first letter should become equal to the last letter before the reversal, the second letter should become equal to the second-to-last letter before the reversal — and so o...
N = int(input()) S = input() T = S[::-1] from collections import defaultdict dic = defaultdict(lambda: []) for i,t in enumerate(T): dic[t].append(i) for k in list(dic.keys()): dic[k].reverse() arr = [] for c in S: arr.append(dic[c].pop()) def inversion(inds): bit = [0] * (N+1) def bit_add(x,w): ...
python
test
abovesol
codeparrot/apps
all
Solve in Python: 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 of choosing one row or column, and adding 1 to all of the cells i...
"""Ввод размера матрицы""" 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
qsol
codeparrot/apps
all
I found an interesting problem on https://www.codewars.com/kata/588e27b7d1140d31cb000060: Write a function `generatePairs` that accepts an integer argument `n` and generates an array containing the pairs of integers `[a, b]` that satisfy the following conditions: ``` 0 <= a <= b <= n ``` The pairs should be sorted by ...
from itertools import combinations_with_replacement def generate_pairs(n): return [list(a) for a in combinations_with_replacement(range(n + 1), 2)]
python
train
abovesol
codeparrot/apps
all
I found an interesting problem on https://www.codewars.com/kata/55b6a3a3c776ce185c000021: *You are a composer who just wrote an awesome piece of music. Now it's time to present it to a band that will perform your piece, but there's a problem! The singers vocal range doesn't stretch as your piece requires, and you have ...
sharp = ['A', 'A#', 'B', 'C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#'] flat = ['A', 'Bb', 'B', 'C', 'Db', 'D', 'Eb', 'E', 'F', 'Gb', 'G', 'Ab'] def transpose(song, interval): return [sharp[((sharp.index(note) if note in sharp else flat.index(note)) + interval) % 12] for note in song]
python
train
abovesol
codeparrot/apps
all
I found an interesting problem on https://www.codechef.com/COOK23/problems/NOKIA: To protect people from evil, a long and tall wall was constructed a few years ago. But just a wall is not safe, there should also be soldiers on it, always keeping vigil. The wall is very long and connects the left and the right tower...
import sys first = True memmin = {} memmax = {} def fmax(n): if n == 1: return 2 if n == 0: return 0 if n in memmax: return memmax[n] res = 0 for i in range(n): cur = i + 1 + n - i + fmax(i) + fmax(n-i-1) if cur > res: res = cur memmax[n] = res return res def fmin(n): if n == 1: return 2 if n == 0: ret...
python
train
abovesol
codeparrot/apps
all
I found an interesting problem on https://www.codewars.com/kata/5912701a89fc3d0a6a000169: # Task Given array of integers `sequence` and some integer `fixedElement`, output the number of `even` values in sequence before the first occurrence of `fixedElement` or `-1` if and only if `fixedElement` is not contained in sequ...
def even_numbers_before_fixed(sequence, fixed_element): try: return sum(elem % 2 == 0 for elem in sequence[:sequence.index(fixed_element)]) except ValueError: return -1
python
train
abovesol
codeparrot/apps
all
Solve in Python: A necklace can be described as a string of links ('-') and pearls ('o'), with the last link or pearl connected to the first one. $0$ You can remove a link or a pearl and insert it between two other existing links or pearls (or between a link and a pearl) on the necklace. This process can be repeated ...
s=input() b=s.count('o') n=s.count('-') if n==0 or b==0: print('YES') else: if n%b==0: print('YES') else: print('NO')
python
test
qsol
codeparrot/apps
all
Solve in Python: Let S be the concatenation of 10^{10} copies of the string 110. (For reference, the concatenation of 3 copies of 110 is 110110110.) We have a string T of length N. Find the number of times T occurs in S as a contiguous substring. -----Constraints----- - 1 \leq N \leq 2 \times 10^5 - T is a string of...
n=int(input()) s='110' t=input() sn=s*((n+2)//3+1) ret=0 for i in range(3): if sn[i:i+n]==t: ret += pow(10,10)-(i+n-1)//3 print(ret)
python
test
qsol
codeparrot/apps
all
I found an interesting problem on https://codeforces.com/problemset/problem/805/B: In the beginning of the new year Keivan decided to reverse his name. He doesn't like palindromes, so he changed Naviek to Navick. He is too selfish, so for a given n he wants to obtain a string of n characters, each of which is either '...
n=int(input()) c=n // 4 if n%4 == 1: print('aabb' * c,'a',sep='') if n%4 == 2: print('aabb' * c,'aa',sep='') if n%4 == 3: print('aabb' * c,'aab',sep='') if n%4 == 0: print('aabb' * c)
python
test
abovesol
codeparrot/apps
all
I found an interesting problem on https://codeforces.com/problemset/problem/1374/D: You are given an array $a$ consisting of $n$ positive integers. Initially, you have an integer $x = 0$. During one move, you can do one of the following two operations: Choose exactly one $i$ from $1$ to $n$ and increase $a_i$ by $x$ ...
t = int(input()) from collections import Counter for case in range(t): n, k = list(map(int, input().split())) a = [int(x) for x in input().split()] w = Counter(x % k for x in a) v = 0 for x, freq in list(w.items()): if x == 0: continue if freq == 0: continue r = (-x...
python
test
abovesol
codeparrot/apps
all
I found an interesting problem on https://www.codechef.com/BRBG2020/problems/FTNUM: A prime number is number x which has only divisors as 1 and x itself. Harsh is playing a game with his friends, where his friends give him a few numbers claiming that they are divisors of some number x but divisor 1 and the number x its...
# cook your dish here import math def findX(list, int): # Sort the given array list.sort() # Get the possible X x = list[0]*list[int-1] # Container to store divisors vec = [] # Find the divisors of x i = 2 while(i * i <= x): # Check if divisor if(x % i == 0)...
python
train
abovesol
codeparrot/apps
all
I found an interesting problem on https://www.codewars.com/kata/58b3c2bd917a5caec0000017: # Task Given an array of integers, sum consecutive even numbers and consecutive odd numbers. Repeat the process while it can be done and return the length of the final array. # Example For `arr = [2, 1, 2, 2, 6, 5, 0, 2, 0, 5, ...
from itertools import groupby def sum_groups(arr): while True: n = len(arr) arr = [sum(grp) for key, grp in groupby(arr, key=lambda x: x % 2)] if len(arr) == n: return n
python
train
abovesol
codeparrot/apps
all
I found an interesting problem on https://www.codewars.com/kata/587731fda577b3d1b0001196: ```if-not:swift Write simple .camelCase method (`camel_case` function in PHP, `CamelCase` in C# or `camelCase` in Java) for strings. All words must have their first letter capitalized without spaces. ``` ```if:swift Write a simple...
def camel_case(string): #a = [string.split()] a = list(string) for i in range(0, len(a)): if i==0 or a[i-1]==' ': a[i] = a[i].upper() return ''.join(a).replace(' ','')
python
train
abovesol
codeparrot/apps
all
I found an interesting problem on https://codeforces.com/problemset/problem/732/C: Vasiliy spent his vacation in a sanatorium, came back and found that he completely forgot details of his vacation! Every day there was a breakfast, a dinner and a supper in a dining room of the sanatorium (of course, in this order). Th...
b, d, s = map(int, input().split()) if b >= d and b >= s: ans = max(0, b - d - 1) + max(0, b - s - 1) elif d >= s and d >= b: ans = max(0, d - s - 1) + max(0, d - b - 1) else: ans = max(0, s - d - 1) + max(0, s - b - 1) print(ans)
python
test
abovesol
codeparrot/apps
all
I found an interesting problem on https://www.codewars.com/kata/525d9b1a037b7a9da7000905: While developing a website, you detect that some of the members have troubles logging in. Searching through the code you find that all logins ending with a "\_" make problems. So you want to write a function that takes an array of...
def search_names(x): return([['bar_', 'bar@bar.com']])
python
train
abovesol
codeparrot/apps
all
Solve in Python: Moscow is hosting a major international conference, which is attended by n scientists from different countries. Each of the scientists knows exactly one language. For convenience, we enumerate all languages of the world with integers from 1 to 10^9. In the evening after the conference, all n scientist...
from sys import stdin, stdout n = int(stdin.readline()) d = {} languages = list(map(int, stdin.readline().split())) for l in languages: if l not in d: d[l] = 1 else: d[l] += 1 m = int(stdin.readline()) movies = [] voice = list(map(int, stdin.readline().split())) for i in range(m): if voice[...
python
test
qsol
codeparrot/apps
all
Solve in Python: Mandarin chinese , Russian and Vietnamese as well. Let's denote $S(x)$ by the sum of prime numbers that divides $x$. You are given an array $a_1, a_2, \ldots, a_n$ of $n$ numbers, find the number of pairs $i, j$ such that $i \neq j$, $a_i$ divides $a_j$ and $S(a_i)$ divides $S(a_j)$. -----Input:----- ...
p=10**4+5 def Sieve(): l=[True]*p s=[0]*p for i in range(2,p): if l[i]: for j in range(i,p,i): s[j]+=i l[j]=False i+=1 l[0]=l[1]=False return l,s isprime,s=Sieve() from collections import defaultdict good=defaultdict(list) for i in range(2,p): for j in range(i,p,i): if s[j]%s[i]==0: good...
python
train
qsol
codeparrot/apps
all
I found an interesting problem on https://codeforces.com/problemset/problem/459/B: Pashmak decided to give Parmida a pair of flowers from the garden. There are n flowers in the garden and the i-th of them has a beauty number b_{i}. Parmida is a very strange girl so she doesn't want to have the two most beautiful flower...
import fileinput import math for line in fileinput.input(): inp = [ int(i) for i in line.split()] N = len(inp) #case 1, all inputs are the same if len(set(inp)) == 1: print(0,(N*(N-1))//2) else: minN = inp[0] maxN = inp[0] for i in inp: if i < minN: minN = i if i ...
python
test
abovesol
codeparrot/apps
all
I found an interesting problem on https://codeforces.com/problemset/problem/915/A: Luba thinks about watering her garden. The garden can be represented as a segment of length k. Luba has got n buckets, the i-th bucket allows her to water some continuous subsegment of garden of length exactly a_{i} each hour. Luba can't...
n, k = list(map(int, input().split())) tab = [int(x) for x in input().split()] best = 1 for i in tab: if k % i == 0: best = max([i, best]) print(k // best)
python
test
abovesol
codeparrot/apps
all
Solve in Python: Programmers' kids solve this riddle in 5-10 minutes. How fast can you do it? -----Input----- The input contains a single integer n (0 ≤ n ≤ 2000000000). -----Output----- Output a single integer. -----Examples----- Input 11 Output 2 Input 14 Output 0 Input 61441 Output 2 Input 571576 Outp...
d = { '0': 1, '1': 0, '2': 0, '3': 0, '4': 1, '5': 0, '6': 1, '7': 0, '8': 2, '9': 1, 'a': 1, 'b': 2, 'c': 0, 'd': 1, 'e': 0, 'f': 0, } print(sum(d[c] for c in hex(int(input()))[2:]))
python
test
qsol
codeparrot/apps
all
Solve in Python: Write a class called User that is used to calculate the amount that a user will progress through a ranking system similar to the one Codewars uses. ##### Business Rules: * A user starts at rank -8 and can progress all the way to 8. * There is no 0 (zero) rank. The next rank after -1 is 1. * Users w...
class User(object): def __init__(self): self.ranks, self.cur_rank, self.progress = [-8, -7, -6, -5, -4, -3, -2, -1, 1, 2, 3, 4, 5, 6, 7, 8], 0, 0 def get_rank(self): return self.ranks[self.cur_rank] def set_rank(self, arg): '''Nope''' rank = property(get_rank, set_rank) def inc_progress(self, k_ra...
python
train
qsol
codeparrot/apps
all
Solve in Python: Write a function that outputs the transpose of a matrix - a new matrix where the columns and rows of the original are swapped. For example, the transpose of: | 1 2 3 | | 4 5 6 | is | 1 4 | | 2 5 | | 3 6 | The input to your function will be an array of matrix rows. You can ass...
def transpose(matrix): return list(map(list, zip(*matrix)))
python
train
qsol
codeparrot/apps
all
I found an interesting problem on https://codeforces.com/problemset/problem/501/A: Misha and Vasya participated in a Codeforces contest. Unfortunately, each of them solved only one problem, though successfully submitted it at the first attempt. Misha solved the problem that costs a points and Vasya solved the problem t...
def Points(P,T): return max((3*P/10),P-(P/250)*T) Inpts=list(map(int,input().split())) if Points(Inpts[0],Inpts[2])>Points(Inpts[1],Inpts[3]): print("Misha") if Points(Inpts[0],Inpts[2])<Points(Inpts[1],Inpts[3]): print("Vasya") if Points(Inpts[0],Inpts[2])==Points(Inpts[1],Inpts[3]): print("Tie")
python
test
abovesol
codeparrot/apps
all
I found an interesting problem on https://www.codewars.com/kata/58545549b45c01ccab00058c: Create a function that returns the total of a meal including tip and tax. You should not tip on the tax. You will be given the subtotal, the tax as a percentage and the tip as a percentage. Please round your result to two decimal...
def calculate_total(subtotal, tax, tip): return round(subtotal * ( 1 + tax / 100.0 + tip /100.0), 2)
python
train
abovesol
codeparrot/apps
all
I found an interesting problem on https://codeforces.com/problemset/problem/931/C: Anya and Kirill are doing a physics laboratory work. In one of the tasks they have to measure some value n times, and then compute the average value to lower the error. Kirill has already made his measurements, and has got the following...
n=int(input()) x=input().split() x=[int(k) for k in x] rem=[] x.sort() mn = x[0] mx = x[-1] if (mx-mn<=1): print(len(x)) for k in x: print(k, end=' ') print() else: avg=mn+1 expsum = avg*len(x) sm=0 countmn=0 countavg=0 countmx=0 for k in x: sm+=k if (sm-expsum)>0: rem=x[len(x)-(sm-expsum):len(x)] ...
python
test
abovesol
codeparrot/apps
all
Solve in Python: _Friday 13th or Black Friday is considered as unlucky day. Calculate how many unlucky days are in the given year._ Find the number of Friday 13th in the given year. __Input:__ Year as an integer. __Output:__ Number of Black Fridays in the year as an integer. __Examples:__ unluckyDays(2015)...
def unlucky_days(y): count = 0 # Clean & Pure Math Example for m in range(3,15): if m == 13: y-=1 if (y%100+(y%100//4)+(y//100)//4-2*(y//100)+26*(m+1)//10+12)%7==5: count += 1 return count
python
train
qsol
codeparrot/apps
all
I found an interesting problem on https://codeforces.com/problemset/problem/1319/B: Tanya wants to go on a journey across the cities of Berland. There are $n$ cities situated along the main railroad line of Berland, and these cities are numbered from $1$ to $n$. Tanya plans her journey as follows. First of all, she w...
n = int(input()) a = list(map(int, input().split())) d = dict() for i in range(n): d[a[i] - i] = 0 maxi = 0 for i in range(n): d[a[i] - i] += a[i] if d[a[i] - i] > maxi: maxi = d[a[i] - i] print(maxi)
python
test
abovesol
codeparrot/apps
all
I found an interesting problem on https://www.codewars.com/kata/59b844528bcb7735560000a0: A `Nice array` is defined to be an array where for every value `n` in the array, there is also an element `n-1` or `n+1` in the array. example: ``` [2,10,9,3] is Nice array because 2=3-1 10=9+1 3=2+1 9=10-1 ``` Write a function...
def is_nice(arr): s = set(arr) return bool(arr) and all( n+1 in s or n-1 in s for n in s)
python
train
abovesol
codeparrot/apps
all
I found an interesting problem on https://atcoder.jp/contests/abc127/tasks/abc127_f: There is a function f(x), which is initially a constant function f(x) = 0. We will ask you to process Q queries in order. There are two kinds of queries, update queries and evaluation queries, as follows: - An update query 1 a b: Give...
from heapq import * import sys sys.setrecursionlimit(10 ** 6) int1 = lambda x: int(x) - 1 p2D = lambda x: print(*x, sep="\n") def II(): return int(sys.stdin.readline()) def MI(): return map(int, sys.stdin.readline().split()) def LI(): return list(map(int, sys.stdin.readline().split())) def LLI(rows_number): return [LI...
python
test
abovesol
codeparrot/apps
all
Solve in Python: A tree is a graph with n vertices and exactly n - 1 edges; this graph should meet the following condition: there exists exactly one shortest (by number of edges) path between any pair of its vertices. A subtree of a tree T is a tree with both vertices and edges as subsets of vertices and edges of T. ...
n = int(input()) r = [[] for i in range(n + 1)] r[1] = [0] for i in range(n - 1): a, b = map(int, input().split()) r[a].append(b) r[b].append(a) t = list(map(int, input().split())) u, v = [0] * (n + 1), [0] * (n + 1) for i, j in enumerate(t, 1): if j < 0: u[i] = - j else: v[i] = j t, p = [1], [0] * ...
python
train
qsol
codeparrot/apps
all
I found an interesting problem on https://leetcode.com/problems/maximum-number-of-coins-you-can-get/: There are 3n piles of coins of varying size, you and your friends will take piles of coins as follows: In each step, you will choose any 3 piles of coins (not necessarily consecutive). Of your choice, Alice will pick ...
from collections import deque class Solution: def maxCoins(self, piles: List[int]) -> int: coins = deque(sorted(piles, reverse=True)) share = 0 while coins: coins.pop() coins.popleft() share+=coins.popleft() return share
python
train
abovesol
codeparrot/apps
all
Solve in Python: # Task You have some people who are betting money, and they all start with the same amount of money (this number>0). Find out if the given end-state of amounts is possible after the betting is over and money is redistributed. # Input/Output - `[input]` integer array arr the proposed end-stat...
def learn_charitable_game(arr): return sum(arr) % len(arr) == 0 and sum(arr) > 0
python
train
qsol
codeparrot/apps
all
I found an interesting problem on https://codeforces.com/problemset/problem/1106/D: Lunar New Year is approaching, and Bob decides to take a wander in a nearby park. The park can be represented as a connected graph with $n$ nodes and $m$ bidirectional edges. Initially Bob is at the node $1$ and he records $1$ on his n...
from heapq import heapify, heappush, heappop def solve(): n, m = [int(x) for x in input().split()] adjs = [[] for _ in range(n)] for _ in range(m): a, b = [int(x) for x in input().split()] a -= 1 b -= 1 adjs[a].append(b) adjs[b].append(a) seq = [1] visited...
python
test
abovesol
codeparrot/apps
all
I found an interesting problem on https://codeforces.com/problemset/problem/776/D: Moriarty has trapped n people in n distinct rooms in a hotel. Some rooms are locked, others are unlocked. But, there is a condition that the people in the hotel can only escape when all the doors are unlocked at the same time. There are ...
import sys import collections n, m = list(map(int, input().split())) r = tuple(map(int, input().split())) controls = [tuple(map(int, input().split()))[1:] for i in range(m)] class DSU: def __init__(self): self.parent = None self.has_zero = False self.has_one = False self.size =...
python
test
abovesol
codeparrot/apps
all
Solve in Python: Create a function that returns an array containing the first `l` digits from the `n`th diagonal of [Pascal's triangle](https://en.wikipedia.org/wiki/Pascal's_triangle). `n = 0` should generate the first diagonal of the triangle (the 'ones'). The first number in each diagonal should be 1. If `l = 0`, ...
def generate_diagonal(d, l): result = [1] if l else [] for k in range(1, l): result.append(result[-1] * (d+k) // k) return result
python
train
qsol
codeparrot/apps
all
I found an interesting problem on https://atcoder.jp/contests/abc151/tasks/abc151_d: Takahashi has a maze, which is a grid of H \times W squares with H horizontal rows and W vertical columns. The square at the i-th row from the top and the j-th column is a "wall" square if S_{ij} is #, and a "road" square if S_{ij} is ...
h,w = map(int,input().split()) C = [list(input()) for i in range(h)] startls = [] for i in range(h): for j in range(w): if C[i][j] == '.': startls.append([i,j]) dy_dx = [[1,0],[0,1],[-1,0],[0,-1]] ans = 0 for start in startls: visited = [[-1 for i in range(w)] for i in range(h)...
python
test
abovesol
codeparrot/apps
all
I found an interesting problem on https://www.codewars.com/kata/56782b25c05cad45f700000f: The Binomial Form of a polynomial has many uses, just as the standard form does. For comparison, if p(x) is in Binomial Form and q(x) is in standard form, we might write p(x) := a0 \* xC0 + a1 \* xC1 + a2 \* xC2 + ... + aN \* xC...
def aCb(a, b): result = 1.0 for i in range(b): result = result * (a - i) / (i + 1) return result def value_at(poly_spec, x): answer = 0 l = len(poly_spec) for i, coeff in enumerate(poly_spec): answer += coeff * aCb(x, l - i - 1) return round(answer, 2)
python
train
abovesol
codeparrot/apps
all
Solve in Python: The Chef has prepared the appetizers in the shapes of letters to spell a special message for the guests. There are n appetizers numbered from 0 to n-1 such that if the appetizers are arrayed in this order, they will display the message. The Chef plans to display them in this order on a table that can b...
t=int(input()) def reversebinary(bits,n): bStr='' for i in range(bits): if n>0: bStr=bStr+str(n%2) else: bStr=bStr+'0' n=n>>1 return int(bStr,2) for i in range(t): k,msg=input().split() k=int(k) newmsg=[] for j in msg: newmsg.a...
python
train
qsol
codeparrot/apps
all
I found an interesting problem on https://atcoder.jp/contests/abc167/tasks/abc167_c: Takahashi, who is a novice in competitive programming, wants to learn M algorithms. Initially, his understanding level of each of the M algorithms is 0. Takahashi is visiting a bookstore, where he finds N books on algorithms. The i-th ...
def main(): n, m, x = list(map(int, input().split())) sofar = 10 ** 5 + 1 cl = list(list(map(int, input().split())) for _ in range(n)) # print(cl) ans = float('inf') for i in range(2 ** n): tmp = [0] * m cost = 0 for j in range(n): # print(bin(j), i, bin(i >> ...
python
test
abovesol
codeparrot/apps
all
Solve in Python: =====Problem Statement===== ABC is a right triangle, 90°, at B. Therefore, ANGLE{ABC} = 90°. Point M is the midpoint of hypotenuse AC. You are given the lengths AB and BC. Your task is to find ANGLE{MBC} (angle θ°, as shown in the figure) in degrees. =====Input Format===== The first contains the lengt...
#!/usr/bin/env python3 from math import atan from math import degrees def __starting_point(): ab = int(input().strip()) bc = int(input().strip()) print("{}°".format(int(round(degrees(atan(ab/bc)))))) __starting_point()
python
train
qsol
codeparrot/apps
all
Solve in Python: Suppose there is a $h \times w$ grid consisting of empty or full cells. Let's make some definitions: $r_{i}$ is the number of consecutive full cells connected to the left side in the $i$-th row ($1 \le i \le h$). In particular, $r_i=0$ if the leftmost cell of the $i$-th row is empty. $c_{j}$ is the...
from collections import defaultdict,deque import sys,heapq,bisect,math,itertools,string,queue,copy,time sys.setrecursionlimit(10**8) INF = float('inf') mod = 10**9+7 eps = 10**-7 def inp(): return int(sys.stdin.readline()) def inpl(): return list(map(int, sys.stdin.readline().split())) def inpl_str(): return list(sys.s...
python
test
qsol
codeparrot/apps
all
Solve in Python: We are given a sequence of coplanar points and see all the possible triangles that may be generated which all combinations of three points. We have the following list of points with the cartesian coordinates of each one: ``` Points [x, y] A [1, 2] B [3, 3] C [4, 1] D [1, 1] E ...
from itertools import combinations def count_rect_triang(points): n=0 points_set=set() for p in points: points_set.add(tuple(p)) for (x1,y1),(x2,y2),(x3,y3) in combinations(points_set,3): l1,l2,l3=sorted([(x2-x1)**2+(y2-y1)**2,(x3-x2)**2+(y3-y2)**2,(x1-x3)**2+(y1-y3)**2]) if l1+l...
python
train
qsol
codeparrot/apps
all
I found an interesting problem on https://codeforces.com/problemset/problem/1353/C: You are given a board of size $n \times n$, where $n$ is odd (not divisible by $2$). Initially, each cell of the board contains one figure. In one move, you can select exactly one figure presented in some cell and move it to one of the...
t = int(input()) while t: n = int(input()) ans = 0 if n==1: print(0) else: for i in range(1, n//2 + 1): ans += 8*i*i print(ans) t -= 1
python
test
abovesol
codeparrot/apps
all
I found an interesting problem on https://www.codewars.com/kata/5254bd1357d59fbbe90001ec: Have a look at the following numbers. ``` n | score ---+------- 1 | 50 2 | 150 3 | 300 4 | 500 5 | 750 ``` Can you find a pattern in it? If so, then write a function `getScore(n)`/`get_score(n)`/`GetScore(n)` which re...
def get_score(n): return 25 * n * (n + 1)
python
train
abovesol
codeparrot/apps
all
Solve in Python: During quarantine chef’s friend invented a game. In this game there are two players, player 1 and Player 2. In center of garden there is one finish circle and both players are at different distances respectively $X$ and $Y$ from finish circle. Between finish circle and Player 1 there are $X$ number of ...
import sys input = sys.stdin.readline T = int(input().strip()) for _ in range(T): X,Y = list(map(int,input().split())) x = X+1 y = Y +1 def bit(x): a = [] while x>0: a.append(x&1) x = x//2 return sum(a) count_x = bit(x) count_y = bit(y) # while(x>0): # n = bit(x) # # print('n_x ' , n) #...
python
train
qsol
codeparrot/apps
all
Solve in Python: Gru wants to distribute $N$ bananas to $K$ minions on his birthday. Gru does not like to just give everyone the same number of bananas, so instead, he wants to distribute bananas in such a way that each minion gets a $distinct$ amount of bananas. That is, no two minions should get the same number of ba...
def factors(x): result = [] i = 1 while i*i <= x: if x % i == 0: result.append(i) if x//i != i: result.append(x//i) i += 1 return result t = int(input()) for _ in range(t): n, k = map(int, input().split()) a = factors(n) an = -1 for i in a: c = ((i*k*(k+1))//2) if (c%i==0 and c<=n): an=max...
python
train
qsol
codeparrot/apps
all
I found an interesting problem on https://www.codewars.com/kata/5aff237c578a14752d0035ae: My grandfather always predicted how old people would get, and right before he passed away he revealed his secret! In honor of my grandfather's memory we will write a function using his formula! * Take a list of ages when each of...
def predict_age(*age): return sum(a*a for a in age)**0.5//2
python
train
abovesol
codeparrot/apps
all
Solve in Python: =====Function Descriptions===== Python has built-in string validation methods for basic data. It can check if a string is composed of alphabetical characters, alphanumeric characters, digits, etc. str.isalnum() This method checks if all the characters of a string are alphanumeric (a-z, A-Z and 0-9). ...
# Enter your code here. Read input from STDIN. Print output to STDOUT inputStr=input() resalnum = False resalpha = False resdigit = False reslower = False resupper = False for i in inputStr: if(i.isalnum()): resalnum=True if(i.isalpha()): resalpha=True if(i.isdigit()): resdigit=True ...
python
train
qsol
codeparrot/apps
all
End of preview. Expand in Data Studio

Can be loaded via e.g.:

from datasets import load_dataset
d = load_dataset("Muennighoff/xP3x-sample", "apps")

1,000 rows from random languages and splits of xP3x for each of the multilingual datasets represented in xP3x.

Downloads last month
795