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/problems/URCALC:
Write a program to obtain 2 numbers $($ $A$ $and$ $B$ $)$ and an arithmetic operator $(C)$ and then design a $calculator$ depending upon the operator entered by the user.
So for example if C="+", you have to sum the two numbers.
If C="-", you h... | # cook your dish here
a=int(input())
b=int(input())
c=input()
if c=="+":
print(a+b)
elif c=="-":
print(a-b)
elif c=="*":
print(a*b)
elif c=="/":
print(a/b) | python | test | abovesol | codeparrot/apps | all |
I found an interesting problem on https://atcoder.jp/contests/abc173/tasks/abc173_e:
Given are N integers A_1,\ldots,A_N.
We will choose exactly K of these elements. Find the maximum possible product of the chosen elements.
Then, print the maximum product modulo (10^9+7), using an integer between 0 and 10^9+6 (inclusiv... | # -*- coding: utf-8 -*-
import sys
def main():
N,K = list(map(int, sys.stdin.readline().split()))
A_list = list(map(int, sys.stdin.readline().split()))
A_list.sort(key=lambda x: -abs(x))
mod = 10**9 + 7
L_plus = R_plus = -1 # the Index of plus value
L_minus = R_minus = -1 # the Index of mi... | python | test | abovesol | codeparrot/apps | all |
I found an interesting problem on https://leetcode.com/problems/maximum-length-of-pair-chain/:
You are given n pairs of numbers. In every pair, the first number is always smaller than the second number.
Now, we define a pair (c, d) can follow another pair (a, b) if and only if b < c. Chain of pairs can be formed in ... | import operator
class Solution:
def findLongestChain(self, pairs):
"""
:type pairs: List[List[int]]
:rtype: int
"""
pairs.sort(key=operator.itemgetter(1, 0))
maxNum = -float('inf')
ret = 0
for pair in pairs:
if pair[0] > maxNum:
... | python | train | abovesol | codeparrot/apps | all |
I found an interesting problem on https://www.codechef.com/problems/GUESSNUM:
Chef is playing a game with his brother Chefu. He asked Chefu to choose a positive integer $N$, multiply it by a given integer $A$, then choose a divisor of $N$ (possibly $N$ itself) and add it to the product. Let's denote the resulting integ... | T = int(input())
import math
for i in range(T):
list = []
A,M = input().split()
A = int(A)
M = int(M)
L1 = M//A
L2 = math.ceil(M/(A+1))
while L2 <= L1 :
N = L2
if M - N*A !=0 and N%(M - N*A) == 0 :
list.append(L2)
L2 += 1
print(len(list))
if len(list) > 0:
for j in range(len(list)-1):
print(list... | python | train | abovesol | codeparrot/apps | all |
Solve in Python:
The look and say sequence is a sequence in which each number is the result of a "look and say" operation on the previous element.
Considering for example the classical version startin with `"1"`: `["1", "11", "21, "1211", "111221", ...]`. You can see that the second element describes the first as `"1(... | from itertools import groupby
def look_and_say_sequence(seq, n):
if seq == "22":
return "22"
for _ in range(1, n):
seq = "".join(f"{len(list(b))}{a}" for a, b in groupby(seq))
return seq | python | train | qsol | codeparrot/apps | all |
Solve in Python:
# Task
A common way for prisoners to communicate secret messages with each other is to encrypt them. One such encryption algorithm goes as follows.
You take the message and place it inside an `nx6` matrix (adjust the number of rows depending on the message length) going from top left to bottom right... | from itertools import zip_longest
def six_column_encryption(msg):
return ' '.join(map(''.join,
zip_longest(*(msg[i:i+6].replace(' ', '.') for i in range(0, len(msg), 6)), fillvalue='.')
)) | python | train | qsol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/1203/D2:
The only difference between easy and hard versions is the length of the string.
You are given a string $s$ and a string $t$, both consisting only of lowercase Latin letters. It is guaranteed that $t$ can be obtained from $s$ by removi... | S = input()
T = input()
N, M = len(S), len(T)
def calc(s, t):
X = [0] * len(s)
j = 0
for i in range(len(s)):
if j >= len(t):
X[i] = j
elif s[i] == t[j]:
X[i] = j+1
j += 1
else:
X[i] = X[i-1]
return [0] + X
A, B = calc(S, ... | python | test | abovesol | codeparrot/apps | all |
Solve in Python:
One upon a time there were three best friends Abhinav, Harsh, and Akash decided to form a
team and take part in ICPC from KIIT. Participants are usually offered several problems during
the programming contest. Long before the start, the friends decided that they will implement a
problem if at least ... | # cook your dish here
n = int(input())
s = 0
for i in range(n):
lst = list(map(int,input().split()))
if sum(lst)>=2:
s += 1
print(s) | python | train | qsol | codeparrot/apps | all |
Solve in Python:
A restaurant received n orders for the rental. Each rental order reserve the restaurant for a continuous period of time, the i-th order is characterized by two time values — the start time l_{i} and the finish time r_{i} (l_{i} ≤ r_{i}).
Restaurant management can accept and reject orders. What is the ... | r = lambda: map(int, input().split())
n, = r()
a = sorted(tuple(r()) for _ in range(n))[::-1]
ret, left = 0, 10**9 + 1
for l, r in a:
if r < left:
ret += 1
left = l
print(ret) | python | test | qsol | codeparrot/apps | all |
I found an interesting problem on https://www.codewars.com/kata/589436311a8808bf560000f9:
# Task
Given an integer `product`, find the smallest positive integer the product of whose digits is equal to product. If there is no such integer, return -1 instead.
# Example
For `product = 1`, the output should be `11`;
... | from math import gcd, log
from operator import mul
from functools import reduce
def digits_product(product):
if product <= 1: return 10 + product
count = lambda p: round(log(gcd(product, p ** 9), p))
n2, n3, n5, n7 = map(count, [2, 3, 5, 7])
digits = [5] * n5 + [7] * n7 + [8] * (n2 // 3) + [9] * (n3 //... | python | train | abovesol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/873/C:
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 tha... | 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 | abovesol | codeparrot/apps | all |
Solve in Python:
Tenten runs a weapon shop for ninjas. Today she is willing to sell $n$ shurikens which cost $1$, $2$, ..., $n$ ryo (local currency). During a day, Tenten will place the shurikens onto the showcase, which is empty at the beginning of the day. Her job is fairly simple: sometimes Tenten places another shu... | import sys
import heapq
input = sys.stdin.readline
def main():
N = int(input())
S = [[x for x in input().split()] for _ in range(2 * N)]
q = []
ans = []
for s in S[::-1]:
if s[0] == "-":
heapq.heappush(q, int(s[1]))
else:
if q:
c = heapq.hea... | python | test | qsol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/733/C:
There was an epidemic in Monstropolis and all monsters became sick. To recover, all monsters lined up in queue for an appointment to the only doctor in the city.
Soon, monsters became hungry and began to eat each other.
One monster ca... | import sys
a = [0,]
b = [0,]
ans1 = []
ans2 = []
n = int(input())
s = input()
nums = s.split()
for i in range(0, n):
a.append(int(nums[i]))
k = int(input())
s = input()
nums = s.split()
for i in range(0, k):
b.append(int(nums[i]))
def f(x, y, z):
#print(x,y,z)
pos1 = x
pos2 = x
if x == y:
... | python | test | abovesol | codeparrot/apps | all |
I found an interesting problem on https://atcoder.jp/contests/abc077/tasks/arc084_a:
The season for Snuke Festival has come again this year. First of all, Ringo will perform a ritual to summon Snuke. For the ritual, he needs an altar, which consists of three parts, one in each of the three categories: upper, middle and... | import bisect
N = int(input())
A = list(map(int, input().split()))
B = list(map(int, input().split()))
C = list(map(int, input().split()))
A.sort()
B.sort()
C.sort()
ans = 0
for b in B:
a_count = bisect.bisect_left(A, b)
c_count = N - bisect.bisect_right(C, b)
ans += a_count * c_count
print(ans) | python | test | abovesol | codeparrot/apps | all |
Solve in Python:
Beaches are filled with sand, water, fish, and sun. Given a string, calculate how many times the words `"Sand"`, `"Water"`, `"Fish"`, and `"Sun"` appear without overlapping (regardless of the case).
## Examples
```python
sum_of_a_beach("WAtErSlIde") ==> 1
sum_of_a_beach("GolDeNSan... | def sum_of_a_beach(beach):
return sum([beach.lower().count(element) for element in ['sand', 'water', 'fish', 'sun']]) | python | train | qsol | codeparrot/apps | all |
Solve in Python:
There are $n$ points on a plane. The $i$-th point has coordinates $(x_i, y_i)$. You have two horizontal platforms, both of length $k$. Each platform can be placed anywhere on a plane but it should be placed horizontally (on the same $y$-coordinate) and have integer borders. If the left border of the pl... | from bisect import bisect_left as lower_bound,bisect_right as upper_bound
for _ in range(int(input())):
n,k=map(int,input().split())
x=sorted(map(int,input().split()))
input()
mxr=[0]*n
for i in range(n-1,-1,-1):
mxr[i]=i-lower_bound(x,x[i]-k)+1
ans=1
cmxr=mxr[0]
for i in range(1... | python | test | qsol | codeparrot/apps | all |
Solve in Python:
Write a function called "filterEvenLengthWords".
Given an array of strings, "filterEvenLengthWords" returns an array containing only the elements of the given array whose length is an even number.
var output = filterEvenLengthWords(['word', 'words', 'word', 'words']);
console.log(output); // --> ['w... | def filter_even_length_words(words):
return [w for w in words if len(w) % 2 == 0] | python | train | qsol | codeparrot/apps | all |
I found an interesting problem on https://www.codewars.com/kata/5b74e28e69826c336e00002a:
We have the integer `9457`.
We distribute its digits in two buckets having the following possible distributions (we put the generated numbers as strings and we add the corresponding formed integers for each partition):
```
- one... | from functools import reduce
from itertools import count
coefs = [
[22, 13, 4],
[365, 167, 50, 14],
[5415, 2130, 627, 177, 51],
[75802, 27067, 7897, 2254, 661, 202],
[1025823, 343605, 100002, 28929, 8643, 2694, 876]
]
def f(n): return sum(c*int(d) for c,d in zip(coefs[len(str(n))-3], str(n)))
def f... | python | train | abovesol | codeparrot/apps | all |
Solve in Python:
This is an easier version of the next problem. In this version, $q = 0$.
A sequence of integers is called nice if its elements are arranged in blocks like in $[3, 3, 3, 4, 1, 1]$. Formally, if two elements are equal, everything in between must also be equal.
Let's define difficulty of a sequence as a... | import sys
input = sys.stdin.readline
n,q=list(map(int,input().split()))
A=list(map(int,input().split()))
if max(A)==min(A):
print(0)
return
L=max(A)
MM=[[200005,-1,i] for i in range(L+1)]
COUNT=[0]*(L+1)
for i in range(n):
a=A[i]
MM[a][0]=min(MM[a][0],i)
MM[a][1]=max(MM[a][1],i)
COUNT[a]+... | python | train | qsol | codeparrot/apps | all |
I found an interesting problem on https://www.codewars.com/kata/5941c545f5c394fef900000c:

Create a class called `Warrior` which calculates and keeps track of their level and skills, and ranks them as the warrior they'... | class Warrior():
def __init__(self) :
self.level = 1
self.experience = 100
self.rank = "Pushover"
self.achievements = []
self.max_level = 100
self.available_ranks = ["Pushover", "Novice", "Fighter", "Warrior", "Veteran", "Sage", "Elite", "Conqueror", "Champion", "Mas... | python | train | abovesol | codeparrot/apps | all |
Solve in Python:
The teacher gave Anton a large geometry homework, but he didn't do it (as usual) as he participated in a regular round on Codeforces. In the task he was given a set of n lines defined by the equations y = k_{i}·x + b_{i}. It was necessary to determine whether there is at least one point of intersection... | n = int(input())
x1, x2 = list(map(int, input().split(" ")))
def intercepts(k, b):
y1 = k*x1+b
y2 = k*x2+b
return [y1, y2]
inter=[]
for i in range (n):
k, b = list(map(int, input().split(" ")))
inter += [intercepts(k, b)]
inter.sort()
right=[]
for i in range (n):
intercept = inter[i]
rig... | python | test | qsol | codeparrot/apps | all |
Solve in Python:
You are given a string $s$. And you have a function $f(x)$ defined as:
f(x) = 1, if $x$ is a vowel
f(x) = 0, if $x$ is a constant
Your task is to apply the above function on all the characters in the string s and convert
the obtained binary string in decimal number $M$.
Since the number $M$ can be ve... | for _ in range(int(input())):
a=input()
b=[]
for i in a:
if i in ['a','e','i','o','u']:b.append(1)
else:b.append(0)
c=0
l=len(a)
for i in range(l):
if b[-i-1]:c+=1<<i
print(c) | python | train | qsol | codeparrot/apps | all |
Solve in Python:
There are two infinite sources of water: hot water of temperature $h$; cold water of temperature $c$ ($c < h$).
You perform the following procedure of alternating moves: take one cup of the hot water and pour it into an infinitely deep barrel; take one cup of the cold water and pour it into an in... | import sys
input = sys.stdin.readline
T = int(input())
for _ in range(T):
h, c, t = list(map(int, input().split()))
if h + c >= 2 * t:
print(2)
else:
diff2 = 2*t - (h + c)
hDiff2 = 2*h - (h + c)
kDown = (hDiff2//diff2 - 1)//2
kUp = kDown + 1
diffDown = abs(d... | python | test | qsol | codeparrot/apps | all |
Solve in Python:
You are given an array with several `"even"` words, one `"odd"` word, and some numbers mixed in.
Determine if any of the numbers in the array is the index of the `"odd"` word. If so, return `true`, otherwise `false`. | def odd_ball(arr):
return int(arr.index('odd')) in arr | python | train | qsol | codeparrot/apps | all |
I found an interesting problem on https://www.codewars.com/kata/557592fcdfc2220bed000042:
### Task:
You have to write a function `pattern` which creates the following pattern (See Examples) upto desired number of rows.
If the Argument is `0` or a Negative Integer then it should return `""` i.e. empty string.
### Exa... | from collections import deque
def pattern(n):
result = []
line = deque([str(num) for num in range(1, n + 1)])
for i in range(n):
result.append("".join(line))
line.rotate(-1)
return "\n".join(result) | python | train | abovesol | codeparrot/apps | all |
Solve in Python:
You are given a chessboard of size $n \times n$. It is filled with numbers from $1$ to $n^2$ in the following way: the first $\lceil \frac{n^2}{2} \rceil$ numbers from $1$ to $\lceil \frac{n^2}{2} \rceil$ are written in the cells with even sum of coordinates from left to right from top to bottom. The r... | import sys
n,q=map(int,sys.stdin.readline().strip().split())
nc=n
# print(n,q)
if(n%2==0):
n2=int((n*n)/2)
else:
n2=int((n*n)/2)+1
n1=int(n/2)
if(1==1):
for i in range(q):
x,y=map(int,sys.stdin.readline().strip().split())
# print(n,q,x,y)
x1=int(x/2)
y1=int(y/2)
... | python | test | qsol | codeparrot/apps | all |
Solve in Python:
A sequence a=\{a_1,a_2,a_3,......\} is determined as follows:
- The first term s is given as input.
- Let f(n) be the following function: f(n) = n/2 if n is even, and f(n) = 3n+1 if n is odd.
- a_i = s when i = 1, and a_i = f(a_{i-1}) when i > 1.
Find the minimum integer m that satisfies the followi... | s = int(input())
ans_list = [s]
curr_value = s
index = 1
while(True):
if curr_value%2==0:
curr_value = int(curr_value/2)
else:
curr_value = 3*curr_value + 1
index += 1
if curr_value in ans_list:
break
else:
ans_list.append(curr_value)
print(index) | python | test | qsol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/1184/B1:
Heidi and Doctor Who hopped out of the TARDIS and found themselves at EPFL in 2018. They were surrounded by stormtroopers and Darth Vader was approaching. Miraculously, they managed to escape to a nearby rebel base but the Doctor was v... | from bisect import bisect_right
def find_le(a, x):
'Find rightmost value less than or equal to x'
i = bisect_right(a, x)
if i:
return i-1
return -1
s, b = list(map(int,input().split()))
v = []
a = list(map(int,input().split()))
for i in range(b):
v.append(tuple(map(int,input().split())))
v... | python | test | abovesol | codeparrot/apps | all |
Solve in Python:
Little penguin Polo has an n × m matrix, consisting of integers. Let's index the matrix rows from 1 to n from top to bottom and let's index the columns from 1 to m from left to right. Let's represent the matrix element on the intersection of row i and column j as a_{ij}.
In one move the penguin can ad... | """http://codeforces.com/problemset/problem/289/B"""
def solve(d, l):
l.sort()
m = l[0] % d
median = len(l) // 2
res = 0
for num in l:
if num % d != m:
return -1
res += abs(num - l[median]) // d
return res
def __starting_point():
f = lambda: list(map(int, input()... | python | test | qsol | codeparrot/apps | all |
I found an interesting problem on https://atcoder.jp/contests/abc066/tasks/arc077_a:
You are given an integer sequence of length n, a_1, ..., a_n.
Let us consider performing the following n operations on an empty sequence b.
The i-th operation is as follows:
- Append a_i to the end of b.
- Reverse the order of the el... | from collections import deque
n,a,b=int(input()),deque(map(int,input().split())),deque()
for i in range(n):
if n%2==0:
if i%2==0:
b.append(a[i])
else:
b.appendleft(a[i])
else:
if i%2==0:
b.appendleft(a[i])
else:
b.append(a[i])
print(*b,sep=' ') | python | test | abovesol | codeparrot/apps | all |
I found an interesting problem on https://www.codewars.com/kata/589273272fab865136000108:
## Your Story
"A *piano* in the home meant something." - *Fried Green Tomatoes at the Whistle Stop Cafe*
You've just realized a childhood dream by getting a beautiful and beautiful-sounding upright piano from a friend who was lea... | def black_or_white_key(c):
i = int('010100101010'[((c - 1) % 88 - 3) % 12])
return ['white', 'black'][i] | python | train | abovesol | codeparrot/apps | all |
I found an interesting problem on https://www.codechef.com/NQST2020/problems/HEIST101:
For years you have been working hard in Santa's factory to manufacture gifts for kids in substandard work environments with no pay. You have finally managed to escape the factory and now you seek revenge. You are planning a heist wit... | import math
t = int(input())
def phi(n):
res = n
i = 2
while i*i<=n:
if n%i==0:
res/=i
res*=(i-1)
while n%i==0:
n/=i
i+=1
if n>1:
res/=n
res*=(n-1)
return int(res)
while t:
a,m = list(map(int,input().split()))
g = math.gcd(a,m)
print(phi(m//g))
t-=1 | python | train | abovesol | codeparrot/apps | all |
Solve in Python:
Watchmen are in a danger and Doctor Manhattan together with his friend Daniel Dreiberg should warn them as soon as possible. There are n watchmen on a plane, the i-th watchman is located at point (x_{i}, y_{i}).
They need to arrange a plan, but there are some difficulties on their way. As you know, Do... | from collections import defaultdict, Counter
n = int(input())
w = []
for i in range(n):
w.append(tuple(map(int, input().split())))
dx = Counter()
dy = Counter()
for x, y in w:
dx[x] += 1
dy[y] += 1
count = sum((v * (v-1) / 2) for v in list(dx.values())) + \
sum((v * (v-1) / 2) for v in list(dy.v... | python | train | qsol | codeparrot/apps | all |
Solve in Python:
=====Problem Statement=====
You are given a positive integer N. Print a numerical triangle of height N - 1 like the one below:
1
22
333
4444
55555
......
Can you do it using only arithmetic operations, a single for loop and print statement?
Use no more than two lines. The first line (the for statemen... | for i in range(1,int(input())): #More than 2 lines will result in 0 score. Do not leave a blank line also
print((10**i//9 * i)) | python | train | qsol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/1102/D:
You are given a string $s$ consisting of exactly $n$ characters, and each character is either '0', '1' or '2'. Such strings are called ternary strings.
Your task is to replace minimum number of characters in this string with other char... | from sys import stdin, stdout
from math import sin, tan, cos, pi, atan2, sqrt, acos, atan, factorial
from random import randint
n = int(stdin.readline())
s = list(stdin.readline().strip())
a, b, c = s.count('0'), s.count('1'), s.count('2')
d = n // 3
for i in range(len(s)):
if s[i] == '2' and c > d:
if a ... | python | test | abovesol | codeparrot/apps | all |
Solve in Python:
It's one more school day now. Sasha doesn't like classes and is always bored at them. So, each day he invents some game and plays in it alone or with friends.
Today he invented one simple game to play with Lena, with whom he shares a desk. The rules are simple. Sasha draws n sticks in a row. After tha... | string = input()
numbers = string.split()
a, b = int(numbers[0]), int(numbers[1])
n = a // b
if n % 2 == 1:
print("YES")
else:
print("NO") | python | test | qsol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/513/C:
Nowadays, most of the internet advertisements are not statically linked to a web page. Instead, what will be shown to the person opening a web page is determined within 100 milliseconds after the web page is opened. Usually, multiple com... | d = [list(map(int, input().split())) for i in range(int(input()))]
s = 0
for k in range(1, 10001):
p = [min(max((k - l) / (r - l + 1), 1e-20), 1) for l, r in d]
u = v = 1
for r in p: u *= r
for r in p:
v *= r
s += (u - v) * (r - 1) / r
print(s)
# Made By Mostafa_Khaled | python | test | abovesol | codeparrot/apps | all |
Solve in Python:
Ken loves ken-ken-pa (Japanese version of hopscotch). Today, he will play it on a directed graph G.
G consists of N vertices numbered 1 to N, and M edges. The i-th edge points from Vertex u_i to Vertex v_i.
First, Ken stands on Vertex S. He wants to reach Vertex T by repeating ken-ken-pa. In one ken-ke... | from collections import deque
MOD = 10**9 +7
INF = 10**9
def main():
n,m = list(map(int,input().split()))
V0 = [[] for _ in range(n)]
V1 = [[] for _ in range(n)]
V2 = [[] for _ in range(n)]
for _ in range(m):
u,v = list(map(int,input().split()))
u -= 1
v -= 1
V0[u].a... | python | test | qsol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/559/C:
Giant chess is quite common in Geraldion. We will not delve into the rules of the game, we'll just say that the game takes place on an h × w field, and it is painted in two colors, but not like in chess. Almost all cells of the field are... | def init_factorials(N, mod):
f = 1
fac = [1] * N
for i in range(1, N):
f *= i
f %= mod
fac[i] = f
return fac
def init_inv(N, mod, fac):
b = bin(mod-2)[2:][-1::-1]
ret = 1
tmp = fac[N]
if b[0] == '1':
ret = fac[N]
for bi in b[1:]:
tmp *= tmp
... | python | train | abovesol | codeparrot/apps | all |
Solve in Python:
We have N switches with "on" and "off" state, and M bulbs. The switches are numbered 1 to N, and the bulbs are numbered 1 to M.
Bulb i is connected to k_i switches: Switch s_{i1}, s_{i2}, ..., and s_{ik_i}. It is lighted when the number of switches that are "on" among these switches is congruent to p_i... | n,m=map(int,input().split())
ks=[[] for i in range(m)]
for i in range(m):
ks[i]=list(map(lambda x:int(x)-1,input().split()))
p=list(map(int,input().split()))
ans=0
for i in range(1<<n):
l=[0]*n
for j in range(n):
l[j]=1 if i&1 else 0
i>>=1
# light check
for j in range(m):
s=sum([l[k] for k in ... | python | test | qsol | codeparrot/apps | all |
Solve in Python:
Chef has $N$ boxes arranged in a line.Each box has some candies in it,say $C[i]$. Chef wants to distribute all the candies between of his friends: $A$ and $B$, in the following way:
$A$ starts eating candies kept in the leftmost box(box at $1$st place) and $B$ starts eating candies kept in the rightmo... | t=int(input())
for _ in range(t):
n=int(input())
l=list(map(int,input().split()))
x=int(input())
j=n-1
i=0
a=0
b=0
remain = 0
while True:
if i>j:
break
if i==j:
if remain:
a+=1
else:
if b>a:
b+=1
else:
a+=1
break
b+=1
d = x*l[j]+remain
while i<j:
d-=l[i]
if... | python | train | qsol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/1111/B:
Every superhero has been given a power value by the Felicity Committee. The avengers crew wants to maximize the average power of the superheroes in their team by performing certain operations.
Initially, there are $n$ superheroes in av... | n,k,m = map(int,input().split())
a = list(map(int,input().split()))
a.sort(reverse = True)
s = sum(a)
ans = 0
while n > 0 and m > -1:
s2 = (s + min(m,n * k)) / n
ans = max(ans,s2)
s -= a.pop()
n -= 1
m -= 1
print(ans) | python | test | abovesol | codeparrot/apps | all |
Solve in Python:
You have initially a string of N characters, denoted by A1,A2...AN. You have to print the size of the largest subsequence of string A such that all the characters in that subsequence are distinct ie. no two characters in that subsequence should be same.
A subsequence of string A is a sequence that can... | for _ in range(int(input())):
s = input()
arr =[]
for i in range(len(s)):
if s[i] in arr:
pass
else:
arr.append(s[i])
print(len(arr)) | python | train | qsol | codeparrot/apps | all |
Solve in Python:
Let's denote a m-free matrix as a binary (that is, consisting of only 1's and 0's) matrix such that every square submatrix of size m × m of this matrix contains at least one zero.
Consider the following problem:
You are given two integers n and m. You have to construct an m-free square matrix of siz... | n = int(input())
for x in range(n):
x = int(input())
if x == 0:
print(1, 1)
else:
flag = True
for d in range(1, int(x**0.5)+2):
if x % d == 0:
s = x // d
n = (s + d)//2
if int(n) != n:
continue
... | python | test | qsol | codeparrot/apps | all |
Solve in Python:
Given two strings s and t which consist of only lowercase letters.
String t is generated by random shuffling string s and then add one more letter at a random position.
Find the letter that was added in t.
Example:
Input:
s = "abcd"
t = "abcde"
Output:
e
Explanation:
'e' is the letter that was ad... | class Solution:
def findTheDifference(self, s, t):
"""
:type s: str
:type t: str
:rtype: str
"""
ss = sorted(s)
st = sorted(t)
i = 0
j = 0
while i <= len(ss) - 1:
if ss[i] == st[j]:
i += 1
... | python | train | qsol | codeparrot/apps | all |
Solve in Python:
Bizon the Champion isn't just charming, he also is very smart.
While some of us were learning the multiplication table, Bizon the Champion had fun in his own manner. Bizon the Champion painted an n × m multiplication table, where the element on the intersection of the i-th row and j-th column equals i... | from sys import stdin
n, m, k = [int(x) for x in stdin.readline().split()]
be, en = 1, k + 1
while be < en:
mid = (be + en + 1) >> 1
be1, cur = (mid + m - 1) // m, 0
for i in range(1, be1):
cur += m
for i in range(be1, n + 1):
cur += (mid - 1) // i
if cur <= k - 1:
be = m... | python | test | qsol | codeparrot/apps | all |
Solve in Python:
Given an arbitrary ransom note string and another string containing letters from all the magazines, write a function that will return true if the ransom
note can be constructed from the magazines ; otherwise, it will return false.
Each letter in the magazine string can only be used once in your ran... | class Solution:
def canConstruct(self, ransomNote, magazine):
"""
:type ransomNote: str
:type magazine: str
:rtype: bool
"""
r_map = {}
for char in ransomNote:
if char in r_map:
r_map[char] += 1
else:
... | python | train | qsol | codeparrot/apps | all |
Solve in Python:
=====Function Descriptions=====
Exceptions
Errors detected during execution are called exceptions.
Examples:
ZeroDivisionError
This error is raised when the second argument of a division or modulo operation is zero.
>>> a = '1'
>>> b = '0'
>>> print int(a) / int(b)
>>> ZeroDivisionError: integer divis... | n = int(input())
for i in range(n):
a,b=input().split()
try:
print((int(a)//int(b)))
except Exception as e:
print(("Error Code: "+str(e))) | python | train | qsol | codeparrot/apps | all |
I found an interesting problem on https://www.codewars.com/kata/5a4331b18f27f2b31f000085:
In input string ```word```(1 word):
* replace the vowel with the nearest left consonant.
* replace the consonant with the nearest right vowel.
P.S. To complete this task imagine the alphabet is a circle (connect the first and las... | def replace_letters(word):
d = {'a':'z','b':'e','c':'e','d':'e','e':'d','f':'i','g':'i','h':'i','i':'h','j':'o','k':'o','l':'o','m':'o','n':'o','o':'n','p':'u','q':'u','r':'u','s':'u','t':'u','u':'t','v':'a','w':'a','x':'a','y':'a','z':'a'}
return ''.join([d[i] for i in list(word)]) | python | train | abovesol | codeparrot/apps | all |
I found an interesting problem on https://www.codewars.com/kata/5b26047b9e40b9f4ec00002b:
With one die of 6 sides we will have six different possible results:``` 1, 2, 3, 4, 5, 6``` .
With 2 dice of six sides, we will have 36 different possible results:
```
(1,1),(1,2),(2,1),(1,3),(3,1),(1,4),(4,1),(1,5),
(5,1), (1,... | from itertools import combinations_with_replacement
from numpy import prod
def eq_dice(set_):
lst = sorted(set_)
eq, dice, count = 0, [], prod(lst)
for sides in range(3, 21):
if count % sides == 0: dice.append(sides)
for num_dice in range(2, 8):
for c in combinations_with_rep... | python | train | abovesol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/1181/C:
Innokenty works at a flea market and sells some random stuff rare items. Recently he found an old rectangular blanket. It turned out that the blanket is split in $n \cdot m$ colored pieces that form a rectangle with $n$ rows and $m$ col... | def countFlagNum(x):
y = 0
flagNum = 0
while y < m:
curColor = a[x][y]
colorCountByX = 1
isItFlag = True
while x + colorCountByX < n and a[x + colorCountByX][y] == curColor:
colorCountByX += 1
if not(x + colorCountByX * 3 > n):
color2 = a[x + colorCountByX][y]
color3 = a[x + ... | python | test | abovesol | codeparrot/apps | all |
Solve in Python:
Jett is tired after destroying the town and she wants to have a rest. She likes high places, that's why for having a rest she wants to get high and she decided to craft staircases.
A staircase is a squared figure that consists of square cells. Each staircase consists of an arbitrary number of stairs. ... | for _ in range(int(input())):
ans=0
n=int(input())
cp=1
while cp*(cp+1)//2<=n:
ans+=1
n-=cp*(cp+1)//2
cp=cp*2+1
print(ans) | python | train | qsol | codeparrot/apps | all |
I found an interesting problem on https://www.codewars.com/kata/5274e122fc75c0943d000148:
Finish the solution so that it takes an input `n` (integer) and returns a string that is the decimal representation of the number grouped by commas after every 3 digits.
Assume: `0 <= n < 2147483647`
## Examples
```
1 -... | def group_by_commas(n):
n = [i for i in str(n)]
for i in range(len(n) -4, -1, -3):
n.insert(i+1, ',')
return ''.join(n) | python | train | abovesol | codeparrot/apps | all |
I found an interesting problem on https://www.codechef.com/problems/PINS:
Chef's company wants to make ATM PINs for its users, so that they could use the PINs for withdrawing their hard-earned money. One of these users is Reziba, who lives in an area where a lot of robberies take place when people try to withdraw their... | # cook your dish here
for _ in range(int(input())):
n=int(input())
q="1"+"0"*(n//2)
print(1,q) | python | train | abovesol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/1023/A:
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 leng... | 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 | abovesol | codeparrot/apps | all |
Solve in Python:
Having two standards for a keypad layout is inconvenient!
Computer keypad's layout:
Cell phone keypad's layout:
Solve the horror of unstandartized keypads by providing a function that converts computer input to a number as if it was typed by a phone.
Example:
"789" -> "123"
Notes:
You... | def computer_to_phone(numbers):
return "".join([str({0:0, 1:7, 2:8, 3:9, 4:4, 5:5, 6:6, 7:1, 8:2, 9:3}[int(n)]) for n in numbers]) | python | train | qsol | codeparrot/apps | all |
Solve in Python:
Chef has gone shopping with his 5-year old son. They have bought N items so far. The items are numbered from 1 to N, and the item i weighs Wi grams.
Chef's son insists on helping his father in carrying the items. He wants his dad to give him a few items. Chef does not want to burden his son. But he wo... | # cook your dish here
for _ in range(int(input())):
n,k = map(int,input().split())
w = list(map(int,input().split()))
w.sort()
if k <= n//2:
s1 = sum(w[:k])
s2 = sum(w[k:])
print(abs(s2 - s1))
else:
s1 = sum(w[n-k:])
s2 = sum(w[:n-k])
print(abs(s2-s1)) | python | train | qsol | codeparrot/apps | all |
I found an interesting problem on https://www.codewars.com/kata/545a4c5a61aa4c6916000755:
As a part of this Kata, you need to create a function that when provided with a triplet, returns the index of the numerical element that lies between the other two elements.
The input to the function will be an array of three dis... | def gimme(arr):
sort = sorted(arr)
arr.index(sort[1])
return arr.index(sort[1]) | python | train | abovesol | codeparrot/apps | all |
I found an interesting problem on https://www.codewars.com/kata/586d9a71aa0428466d00001c:
Happy traveller [Part 1]
There is a play grid NxN; Always square!
0 1 2 3
0 [o, o, o, X]
1 [o, o, o, o]
2 [o, o, o, o]
3 [o, o, o, o]
You start from a random point. I mean, you are given the coordinates of your start po... | from math import factorial as f
count_paths=lambda n,c:f(c[0]+abs(n-c[1]-1))//(f(abs(n-c[1]-1))*f(c[0])) if n!=1 else 0 | python | train | abovesol | codeparrot/apps | all |
Solve in Python:
Dima loves representing an odd number as the sum of multiple primes, and Lisa loves it when there are at most three primes. Help them to represent the given number as the sum of at most than three primes.
More formally, you are given an odd numer n. Find a set of numbers p_{i} (1 ≤ i ≤ k), such that
... | def prime(i):
for k in range(2, int(i**0.5)+1):
if i%k == 0:
return False
return True
x = int(input())
if prime(x):
print(1)
print(x)
quit()
i = x
while not prime(i):
i -= 2
p1000 = [i for i in range(2, 3000) if prime(i)]
rem = x - i
if rem == 2:
print(2)
print(2, ... | python | test | qsol | codeparrot/apps | all |
Solve in Python:
In the city of Saint Petersburg, a day lasts for $2^{100}$ minutes. From the main station of Saint Petersburg, a train departs after $1$ minute, $4$ minutes, $16$ minutes, and so on; in other words, the train departs at time $4^k$ for each integer $k \geq 0$. Team BowWow has arrived at the station at t... | s = int(input(), base=2)
#print(s)
k = 0
ans = 0
while 4 ** k < s:
ans += 1
k += 1
print(ans) | python | test | qsol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/749/C:
There are n employees in Alternative Cake Manufacturing (ACM). They are now voting on some very important question and the leading world media are trying to predict the outcome of the vote.
Each of the employees belongs to one of two fr... | n = int(input())
s = input()
dd = 0
dr = 0
while len(s) > 1:
t = ''
cd = 0
cr = 0
for c in s:
if c == 'D':
if dd > 0:
dd -= 1
else:
dr += 1
t += c
cd += 1
else:
if dr > 0:
... | python | test | abovesol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/1121/B:
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 ... | 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 | abovesol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/1368/A:
Leo has developed a new programming language C+=. In C+=, integer variables can only be changed with a "+=" operation that adds the right-hand side value to the left-hand side variable. For example, performing "a += b" when a = $2$, b =... | for _ in range(int(input())):
a, b, n = list(map(int, input().split()))
ans = 0
a, b = min(a,b), max(a,b)
while b <= n:
a, b = b, a+b
ans += 1
print(ans) | python | test | abovesol | codeparrot/apps | all |
Solve in Python:
If n is the numerator and d the denominator of a fraction, that fraction is defined a (reduced) proper fraction if and only if GCD(n,d)==1.
For example `5/16` is a proper fraction, while `6/16` is not, as both 6 and 16 are divisible by 2, thus the fraction can be reduced to `3/8`.
Now, if you conside... | def proper_fractions(n):
phi = n > 1 and n
for p in range(2, int(n ** 0.5) + 1):
if not n % p:
phi -= phi // p
while not n % p:
n //= p
if n > 1: phi -= phi // n
return phi | python | train | qsol | codeparrot/apps | all |
I found an interesting problem on https://www.codewars.com/kata/573b216f5328ffcd710013b3:
###BACKGROUND:
Jacob recently decided to get healthy and lose some weight. He did a lot of reading and research and after focusing on steady exercise and a healthy diet for several months, was able to shed over 50 pounds! Now he w... | def lose_weight(gender, weight, duration):
if gender not in ('M','F'):
return 'Invalid gender'
if weight <= 0:
return 'Invalid weight'
if duration <= 0:
return 'Invalid duration'
factor = 0.985 if gender == 'M' else 0.988
expected_weight = factor**duration * weight
return... | python | train | abovesol | codeparrot/apps | all |
I found an interesting problem on https://atcoder.jp/contests/abc097/tasks/abc097_a:
Three people, A, B and C, are trying to communicate using transceivers.
They are standing along a number line, and the coordinates of A, B and C are a, b and c (in meters), respectively.
Two people can directly communicate when the dis... | a, b, c, d = map(int, input().split())
if abs(a-c) <= d:
print("Yes")
elif abs(a-b) <= d and abs(b-c) <= d:
print("Yes")
else:
print("No") | python | test | abovesol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/900/D:
Count the number of distinct sequences a_1, a_2, ..., a_{n} (1 ≤ a_{i}) consisting of positive integers such that gcd(a_1, a_2, ..., a_{n}) = x and $\sum_{i = 1}^{n} a_{i} = y$. As this number could be large, print the answer modulo 10^9... | import math
lectura=lambda:map (int,input().split())
x,y=lectura()
mod= 1000000007
if (y%x!=0):
print("0")
else:
y= y//x
setPrueba=set()
for i in range(1, int(math.sqrt(y) + 1)):
if (y%i==0):
setPrueba.add(i)
setPrueba.add(y// i)
setPrueba=sorted(list(setPrueba))
... | python | test | abovesol | codeparrot/apps | all |
Solve in Python:
The Fibonacci numbers are the numbers in the following integer sequence (Fn):
>0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, ...
such as
>F(n) = F(n-1) + F(n-2) with F(0) = 0 and F(1) = 1.
Given a number, say prod (for product), we search two Fibonacci numbers F(n) and F(n+1) verifying
>F(n) *... | def productFib(prod):
a, b = 0, 1
while a*b < prod:
a, b = b, a+b
return [a, b, a*b == prod] | python | train | qsol | codeparrot/apps | all |
I found an interesting problem on https://www.codewars.com/kata/57675f3dedc6f728ee000256:
Build Tower Advanced
---
Build Tower by the following given arguments:
__number of floors__ (integer and always greater than 0)
__block size__ (width, height) (integer pair and always greater than (0, 0))
Tower block unit is rep... | def tower_builder(n_floors, block_size):
w, h = block_size
filled_block = '*' * w
empty_block = ' ' * w
tower = []
for n in range(1,n_floors+1):
for _ in range(h):
tower.append( empty_block * (n_floors - n) + filled_block * (2*n -1) + empty_block * (n_floors - n))
return towe... | python | train | abovesol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/689/A:
While swimming at the beach, Mike has accidentally dropped his cellphone into the water. There was no worry as he bought a cheap replacement phone with an old-fashioned keyboard. The keyboard has only ten digital equal-sized keys, locate... | n = int(input())
l = [41, 10, 11, 12, 20, 21, 22, 30, 31, 32]
s = list([l[int(x)] for x in input()])
def exists_up(s):
l1 = [x - 10 for x in s]
return all(x in l for x in l1)
def exists_down(s):
l1 = [x + 10 for x in s]
return all(x in l for x in l1)
def exists_left(s):
l1 = [x - 1 for x in s]
... | python | test | abovesol | codeparrot/apps | all |
Solve in Python:
Given an integer n, count the total number of digit 1 appearing in all non-negative integers less than or equal to n.
Example:
Input: 13
Output: 6
Explanation: Digit 1 occurred in the following numbers: 1, 10, 11, 12, 13. | class Solution:
def countDigitOne(self, n):
ones, wei = 0, 1
while wei <= n:
m = int(n / wei) % 10 # 求某位数字
if m > 1:
ones += (int(n / wei / 10) + 1) * wei
elif m == 1:
ones += (int(n / wei ... | python | train | qsol | codeparrot/apps | all |
Solve in Python:
Polycarpus just has been out of luck lately! As soon as he found a job in the "Binary Cat" cafe, the club got burgled. All ice-cream was stolen.
On the burglary night Polycarpus kept a careful record of all club visitors. Each time a visitor entered the club, Polycarpus put down character "+" in his n... | s=input()
s=list(s)
s1=[0]*len(s)
for i in range(len(s)):
if s[i]=='-':
s[i]=1
s1[i]=-1
else:
s[i]=-1
s1[i]=1
def kadane(s):
maxi=-1
curr=0
for i in s:
curr=max(curr+i,i)
maxi=max(maxi,curr)
return maxi
print(max(kadane(s),kadane(s1)))
#@prin... | python | test | qsol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/1312/A:
You are given two integers $n$ and $m$ ($m < n$). Consider a convex regular polygon of $n$ vertices. Recall that a regular polygon is a polygon that is equiangular (all angles are equal in measure) and equilateral (all sides have the sa... | t = int(input())
for i in range(t):
n,m = list(map(int, input().split()))
if n % m == 0:
print ("YES")
else:
print ("NO") | python | test | abovesol | codeparrot/apps | all |
Solve in Python:
Zonal Computing Olympiad 2013, 10 Nov 2012
N teams participate in a league cricket tournament on Mars, where each pair of distinct teams plays each other exactly once. Thus, there are a total of (N × (N-1))/2 matches. An expert has assigned a strength to each team, a positive integer. Strangely, the Ma... | teams=int(input())
strength=list(map(int, input().split()))
rev=0
for i in range(0,teams):
for j in range(i+1,teams):
if(strength[i]>strength[j]):
rev+=strength[i]-strength[j]
else:
rev+=strength[j]-strength[i]
print(rev) | python | train | qsol | codeparrot/apps | all |
I found an interesting problem on https://www.codechef.com/CMYC2020/problems/BTENG:
Voritex a big data scientist collected huge amount of big data having structure of two rows and n columns.
Voritex is storing all the valid data for manipulations and pressing invalid command when data not satisfying the constraints.
Vo... | import math
import os
import random
import re
import sys
r = 100000
prev = 1
s = set()
for i in range(1, r+1):
now = i ^ prev
s.add(now)
prev = now
s = list(s)
t = int(input())
while t > 0:
t -= 1
n, k = list(map(int, input().split()))
if n > 3:
if n % 2 == 0:
... | python | train | abovesol | codeparrot/apps | all |
Solve in Python:
Some time ago Mister B detected a strange signal from the space, which he started to study.
After some transformation the signal turned out to be a permutation p of length n or its cyclic shift. For the further investigation Mister B need some basis, that's why he decided to choose cyclic shift of thi... | n = int(input())
a = list(map(int, input().split()))
t = [0] * 2 * n
s = 0
for i in range(n):
d = a[i] - i - 1
s += abs(d)
if d > 0: t[d] += 1
p = sum(t)
r = (s, 0)
for i in range(1, n):
d = a[n - i] - 1
s += d - p << 1
t[d + i] += d > 0
p += (d > 0) - t[i]
if s < r[0]: r = (s, i)
print(... | python | test | qsol | codeparrot/apps | all |
Solve in Python:
Soon a school Olympiad in Informatics will be held in Berland, n schoolchildren will participate there.
At a meeting of the jury of the Olympiad it was decided that each of the n participants, depending on the results, will get a diploma of the first, second or third degree. Thus, each student will re... | n=int(input())
min1,max1=map(int,input().split())
min2,max2=map(int,input().split())
min3,max3=map(int,input().split())
ans1=min1
ans2=min2
ans3=min3
n-=min1+min2+min3
max1=max1-min1
max2=max2-min2
max3=max3-min3
while n>0:
if max1>0:
if max1>=n:
ans1+=n
max1-=n
n=0
... | python | test | qsol | codeparrot/apps | all |
Solve in Python:
Polycarp is a frequent user of the very popular messenger. He's chatting with his friends all the time. He has $n$ friends, numbered from $1$ to $n$.
Recall that a permutation of size $n$ is an array of size $n$ such that each integer from $1$ to $n$ occurs exactly once in this array.
So his recent c... | #!usr/bin/env python3
import sys
import bisect
def LI(): return [int(x) for x in sys.stdin.readline().split()]
mod = 1000000007
def solve():
def add(i,x):
while i < len(bit):
bit[i] += x
i += i&-i
def sum(i):
res = 0
while i > 0:
res += bit[i]
... | python | test | qsol | codeparrot/apps | all |
I found an interesting problem on https://www.codewars.com/kata/5a59e029145c46eaac000062:
### Please also check out other katas in [Domino Tiling series](https://www.codewars.com/collections/5d19554d13dba80026a74ff5)!
---
# Task
A domino is a rectangular block with `2` units wide and `1` unit high. A domino can be p... | def two_by_n(n, k):
mod = 12345787
if n == 0: return 0
elif n == 1: return k
d = [k, 0, k * (k - 1), k * (k - 1)]
for i in range(3, n + 1):
x, y, z, w = d
d = [z, w, (z * (k - 1) + w * (k - 2)) % mod, (x * (k - 1) * (k - 2) + y * ((k - 2)**2 + k - 1)) % mod]
return (d[2] + d[3]) ... | python | train | abovesol | codeparrot/apps | all |
I found an interesting problem on https://leetcode.com/problems/smallest-range-i/:
Given an array A of integers, for each integer A[i] we may choose any x with -K <= x <= K, and add x to A[i].
After this process, we have some array B.
Return the smallest possible difference between the maximum value of B and the minimu... | class Solution:
def smallestRangeI(self, a: List[int], k: int) -> int:
a = sorted(a)
a[-1] = max(a)
a[0]= min(a)
#print(a,a[-1])
if a[-1]-k<=(a[0]+k):
return 0
return (a[-1]-k)-(a[0]+k) | python | train | abovesol | codeparrot/apps | all |
Solve in Python:
If you have not ever heard the term **Arithmetic Progrossion**, refer to:
http://www.codewars.com/kata/find-the-missing-term-in-an-arithmetic-progression/python
And here is an unordered version. Try if you can survive lists of **MASSIVE** numbers (which means time limit should be considered). :D
Not... | find=lambda s:(min(s)+max(s))*-~len(s)/2-sum(s) | python | train | qsol | codeparrot/apps | all |
Solve in Python:
Lucas numbers are numbers in a sequence defined like this:
```
L(0) = 2
L(1) = 1
L(n) = L(n-1) + L(n-2)
```
Your mission is to complete the function that returns the `n`th term of this sequence.
**Note:** It should work for negative numbers as well; how you do this is you flip the equation around, so... | def lucasnum(n):
if n == 1:
return 1
elif n == 0:
return 2
elif n > 1:
a, b = 2, 1
for i in range(n):
a, b = b, a+b
return a
else:
a, b = -1, -2
for i in range(abs(n)):
a, b = b, a-b
return b*-1 | python | train | qsol | codeparrot/apps | all |
Solve in Python:
# Connect Four
Take a look at wiki description of Connect Four game:
[Wiki Connect Four](https://en.wikipedia.org/wiki/Connect_Four)
The grid is 6 row by 7 columns, those being named from A to G.
You will receive a list of strings showing the order of the pieces which dropped in columns:
```python... | import numpy as np
from scipy.signal import convolve2d
def who_is_winner(pieces_position_list):
arr = np.zeros((7,6), int)
for a in pieces_position_list:
pos, color = a.split('_')
pos = ord(pos) - ord('A')
val = (-1,1)[color == 'Red']
arr[pos, np.argmin(arr[pos] != 0)] = val
... | python | train | qsol | codeparrot/apps | all |
I found an interesting problem on https://www.codewars.com/kata/58b497914c5d0af407000049:
The business has been suffering for years under the watch of Homie the Clown. Every time there is a push to production it requires 500 hands-on deck, a massive manual process, and the fire department is on stand-by along with Fire... | TOTAL = '{} monitoring objections, {} automation, {} deployment pipeline, {} cloud, and {} microservices.'
def nkotb_vs_homie(r):
result = []
for req in sum(r, []):
homie = req.split()[2].title()
result.append(f'{homie}! Homie dont play that!')
result.append(TOTAL.format(*map(len, r)))
... | python | train | abovesol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/733/D:
Kostya is a genial sculptor, he has an idea: to carve a marble sculpture in the shape of a sphere. Kostya has a friend Zahar who works at a career. Zahar knows about Kostya's idea and wants to present him a rectangular parallelepiped of ... | def main():
from collections import defaultdict
d, m = defaultdict(list), 0
for i in range(1, int(input()) + 1):
a, b, c = sorted(map(int, input().split()))
d[b, c].append((a, i))
for (a, b), l in list(d.items()):
if len(l) > 1:
l.sort()
c, i = l[-1]
... | python | test | abovesol | codeparrot/apps | all |
I found an interesting problem on https://www.codewars.com/kata/5f120a13e63b6a0016f1c9d5:
Let's say we have a number, `num`. Find the number of values of `n` such that: there exists `n` consecutive **positive** values that sum up to `num`. A positive number is `> 0`. `n` can also be 1.
```python
#Examples
num = 1
#1
r... | def consecutive_sum(num):
count = 0
N = 1
while( N * (N + 1) < 2 * num):
a = (num - (N * (N + 1) ) / 2) / (N + 1)
if (a - int(a) == 0.0):
count += 1
N += 1
return count+1 | python | train | abovesol | codeparrot/apps | all |
I found an interesting problem on https://www.codechef.com/problems/PERPALIN:
Chef recently learned about concept of periodicity of strings. A string is said to have a period P, if P divides N and for each i, the i-th of character of the string is same as i-Pth character (provided it exists), e.g. "abab" has a period P... | t = int(input())
while(t>0):
t-=1
n,p = [int(x) for x in input().split()]
if(p <= 2):
print('impossible')
continue
else:
s = 'a' + ('b'*(p-2)) + 'a'
s = s*int(n/p)
print(s) | python | train | abovesol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/812/A:
Sagheer is walking in the street when he comes to an intersection of two roads. Each road can be represented as two parts where each part has 3 lanes getting into the intersection (one for each direction) and 3 lanes getting out of the i... | def booly(s):
return bool(int(s))
a = [None]*4;
a[0] = list(map(booly, input().split()))
a[1] = list(map(booly, input().split()))
a[2] = list(map(booly, input().split()))
a[3] =list( map(booly, input().split()))
acc = False
for i in range(4):
if (a[i][3] and (a[i][0] or a[i][1] or a[i][2])):
acc = Tr... | python | test | abovesol | codeparrot/apps | all |
I found an interesting problem on https://www.codewars.com/kata/550527b108b86f700000073f:
The aim of the kata is to try to show how difficult it can be to calculate decimals of an irrational number with a certain precision. We have chosen to get a few decimals of the number "pi" using
the following infinite series (Lei... | import math
def iter_pi(epsilon):
pi,k = 0,0
while abs(pi-math.pi/4) > epsilon/4:
pi += (-1)**k * 1/(2*k + 1)
k += 1
pi *=4
return [k , round(pi, 10)] | python | train | abovesol | codeparrot/apps | all |
Solve in Python:
Most football fans love it for the goals and excitement. Well, this Kata doesn't.
You are to handle the referee's little notebook and count the players who were sent off for fouls and misbehavior.
The rules:
Two teams, named "A" and "B" have 11 players each; players on each team are numbered from 1 to... | def men_still_standing(cards):
players, Y, R = {"A": 11, "B": 11}, set(), set()
for c in cards:
if c[:-1] not in R:
players[c[0]] -= c[-1] == "R" or c[:-1] in Y
if 6 in players.values():
break
(R if (c[-1] == "R" or c[:-1] in Y) else Y).add(c[:-1])
return play... | python | train | qsol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/644/B:
In this problem you have to simulate the workflow of one-thread server. There are n queries to process, the i-th will be received at moment t_{i} and needs to be processed for d_{i} units of time. All t_{i} are guaranteed to be distinct.... | import collections
class TaskMgr:
def __init__(self, n, b):
self.b = b
self.lock_until = 1
self.q = collections.deque()
self.end = [-1 for i in range(n)]
def empty(self):
return len(self.q) == 0
def full(self):
return len(self.q) == self.b
def add(self, i... | python | test | abovesol | codeparrot/apps | all |
Solve in Python:
Good job! Now that Heidi is able to distinguish between Poisson and uniform distributions, she is in a good position to actually estimate the populations.
Can you help Heidi estimate each village's population?
-----Input-----
Same as the easy version.
-----Output-----
Output one line per village... | def sampleVariance(V):
X = sum(V) / len(V)
S = 0.0
for x in V:
S += (X-x)**2
S /= (len(V)-1)
return (X, S)
#That awkward moment when you realized that variance is sigma^2 but you just took the stat course this semester
for i in range(int(input())):
V = list(map(int, input().split()))
... | python | train | qsol | codeparrot/apps | all |
I found an interesting problem on https://www.codewars.com/kata/575690ee34a34efb37001796:
Your task is to write function which takes string and list of delimiters as an input and returns list of strings/characters after splitting given string.
Example:
```python
multiple_split('Hi, how are you?', [' ']) => ['Hi,', 'ho... | def multiple_split(string, delimiters=[]):
print(string, delimiters)
if not string: return [] # trivial case
if not delimiters: return [string] # trivial case
for d in delimiters[1:]:
string = string.replace(d, delimiters[0])
tokens = string.split(delimiters[0])
return [t for t in to... | python | train | abovesol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/701/B:
Vasya has the square chessboard of size n × n and m rooks. Initially the chessboard is empty. Vasya will consequently put the rooks on the board one after another.
The cell of the field is under rook's attack, if there is at least one r... | N, M = map(int, input().split())
r = N
c = N
R = [False for i in range(N)]
C = R.copy()
for i in range(M):
a, b = map(int, input().split())
if not R[a-1]:
r -= 1
R[a-1] = True
if not C[b-1]:
c -= 1
C[b-1] = True
print(r*c, end=' ') | python | test | abovesol | codeparrot/apps | all |
I found an interesting problem on https://www.codewars.com/kata/59ca8e8e1a68b7de740001f4:
Given two arrays of strings, return the number of times each string of the second array appears in the first array.
#### Example
```python
array1 = ['abc', 'abc', 'xyz', 'cde', 'uvw']
array2 = ['abc', 'cde', 'uap']
```
How many... | def solve(first,second):
return [first.count(word) for word in second] | python | train | abovesol | codeparrot/apps | all |
Solve in Python:
Given a rational number n
``` n >= 0, with denominator strictly positive```
- as a string (example: "2/3" in Ruby, Python, Clojure, JS, CS, Go)
- or as two strings (example: "2" "3" in Haskell, Java, CSharp, C++, Swift)
- or as a rational or decimal number (example: 3/4, 0.67 in R)
- or two inte... | from fractions import Fraction
from math import ceil
def decompose(n):
n = Fraction(n)
lst, n = [int(n)], n - int(n)
while n > 0:
next_denom = int(ceil(1/n))
lst.append(next_denom)
n -= Fraction(1, next_denom)
return ([] if lst[0] == 0 else [str(lst[0])]) + ["1/{}".format(d) for... | python | train | qsol | codeparrot/apps | all |
Solve in Python:
## Task
Given a positive integer as input, return the output as a string in the following format:
Each element, corresponding to a digit of the number, multiplied by a power of 10 in such a way that with the sum of these elements you can obtain the original number.
## Examples
Input | Output
--- ... | def simplify(n):
return "+".join([f"{x}*{10**i}" if i else x for i, x in enumerate(str(n)[::-1]) if x != "0"][::-1]) | python | train | qsol | codeparrot/apps | all |
Solve in Python:
10^{10^{10}} participants, including Takahashi, competed in two programming contests.
In each contest, all participants had distinct ranks from first through 10^{10^{10}}-th.
The score of a participant is the product of his/her ranks in the two contests.
Process the following Q queries:
- In the i-th ... | n = int(input())
for i in range(n):
a,b= list(map(int, input().split( )))
#解説参照
#何度見ても解けない
#どちらかは高橋君より良い
#a<=bとする
#a=b (1~a-1)*2
#a<b c**2<abとする
#c(c+1)>=ab?2c-2 / 2c-1
if a==b:
print((2*a-2))
else:
c = int((a*b)**(1/2))
if c*c==a*b:
c -= 1
... | python | train | qsol | codeparrot/apps | all |
Solve in Python:
You are given a sequence of N$N$ powers of an integer k$k$; let's denote the i$i$-th of these powers by kAi$k^{A_i}$. You should partition this sequence into two non-empty contiguous subsequences; each element of the original sequence should appear in exactly one of these subsequences. In addition, the... | # cook your dish here
for i in range(int(input())):
n,k=[int(i) for i in input().split()]
arr=[(k**int(i)) for i in input().split()]
v1=sum(arr)
v1=v1//2
v2=0
for i in range(len(arr)):
v2+=arr[i]
if(v2>=v1):
break
if(i==0):
print(1)
else:
if(abs(v2-v1)<abs(v2-ar... | 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.