inputs stringlengths 175 2.22k | targets stringlengths 10 2.05k | language stringclasses 1
value | split stringclasses 2
values | template stringclasses 2
values | dataset stringclasses 1
value | config stringclasses 1
value |
|---|---|---|---|---|---|---|
I found an interesting problem on https://codeforces.com/problemset/problem/572/B:
In this task you need to process a set of stock exchange orders and use them to create order book.
An order is an instruction of some participant to buy or sell stocks on stock exchange. The order number i has price p_{i}, direction d_{... | s = input()
n, d = int(s.split()[0]), int(s.split()[1])
b, s = {}, {}
wb, ws = [], []
for i in range(0, n):
st = input().split()
st[1] = int(st[1])
st[2] = int(st[2])
if st[0] == 'B':
if st[1] not in b:
b[st[1]] = st[2]
else:
b[st[1]] += st[2];
if st[1] not in wb:
wb.append(st[1]);
else:
if st[1] ... | python | test | abovesol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/1336/A:
Writing light novels is the most important thing in Linova's life. Last night, Linova dreamed about a fantastic kingdom. She began to write a light novel for the kingdom as soon as she woke up, and of course, she is the queen of it.
[I... | import sys
input = sys.stdin.readline
n, k = list(map(int, input().split()))
begin = [-1] * n
end = [-1] * n
hurt = [-1] * n
adj = [[] for i in range(n)]
for _ in range(n-1):
u ,v = list(map(int, input().split()))
adj[u-1].append(v-1)
adj[v-1].append(u-1)
hurt[0] = 1
begin[0] = 0
stack = [0]
curr = 1
wh... | python | train | abovesol | codeparrot/apps | all |
Solve in Python:
Write a function called `LCS` that accepts two sequences and returns the longest subsequence common to the passed in sequences.
### Subsequence
A subsequence is different from a substring. The terms of a subsequence need not be consecutive terms of the original sequence.
### Example subsequence
Subse... | def lcs(x, y):
if not x or not y: return ""
if x[0] == y[0]: return x[0] + lcs(x[1:], y[1:])
return max(lcs(x[1:], y), lcs(x, y[1:]), key=len) | python | train | qsol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/250/E:
Joe has been hurt on the Internet. Now he is storming around the house, destroying everything in his path.
Joe's house has n floors, each floor is a segment of m cells. Each cell either contains nothing (it is an empty cell), or has a b... | n, m = [int(i) for i in input().split()]
current_floor = list(input())
x, t, direction = 0, 0, 1
for i in range(n-1):
floor = list(input())
l, r = x, x
wall = 0
while True:
t += 1
if floor[x] == '.':
break
if (x + direction == m) or (x + direction < 0) or (current_f... | python | test | abovesol | codeparrot/apps | all |
Solve in Python:
We often go to supermarkets to buy some fruits or vegetables, and on the tag there prints the price for a kilo. But in some supermarkets, when asked how much the items are, the clerk will say that $a$ yuan for $b$ kilos (You don't need to care about what "yuan" is), the same as $a/b$ yuan for a kilo.
... | n, m = [int(i) for i in input().split()]
ans = 10 ** 9
for i in range(n):
a1, a2 = [int(i) for i in input().split()]
ans = min(ans, a1 * m / a2)
print(ans) | python | test | qsol | codeparrot/apps | all |
Solve in Python:
An army of n droids is lined up in one row. Each droid is described by m integers a_1, a_2, ..., a_{m}, where a_{i} is the number of details of the i-th type in this droid's mechanism. R2-D2 wants to destroy the sequence of consecutive droids of maximum length. He has m weapons, the i-th weapon can aff... | from heapq import heappush, heappop
from sys import setrecursionlimit
from sys import stdin
from collections import defaultdict
setrecursionlimit(1000000007)
_data = iter(stdin.read().split('\n'))
def input():
return next(_data)
n, m, k = [int(x) for x in input().split()]
a = tuple(tuple(-int(x) for x in input().s... | python | test | qsol | codeparrot/apps | all |
Solve in Python:
Kefa decided to celebrate his first big salary by going to the restaurant.
He lives by an unusual park. The park is a rooted tree consisting of n vertices with the root at vertex 1. Vertex 1 also contains Kefa's house. Unfortunaely for our hero, the park also contains cats. Kefa has already found out... | n, m = input().split()
n, m = int(n), int(m)
a = list( map( int , input().split() ) )
v = [ [] for _ in range( n ) ]
for i in range( n - 1 ):
x = list( map( int , input().split() ) )
x[ 0 ], x[ 1 ] = int(x[ 0 ]) - 1, int(x[ 1 ]) - 1
v[ x[ 0 ] ].append( x[ 1 ] )
v[ x[ 1 ] ].append( x[ 0 ] )
tag = [False] * n
con... | python | test | qsol | codeparrot/apps | all |
Solve in Python:
# Task
The string is called `prime` if it cannot be constructed by concatenating some (more than one) equal strings together.
For example, "abac" is prime, but "xyxy" is not("xyxy"="xy"+"xy").
Given a string determine if it is prime or not.
# Input/Output
- `[input]` string `s`
string cont... | def prime_string(s):
return (s + s).find(s, 1) == len(s) | python | train | qsol | codeparrot/apps | all |
I found an interesting problem on https://www.codewars.com/kata/57f7796697d62fc93d0001b8:
Given an array of integers (x), and a target (t), you must find out if any two consecutive numbers in the array sum to t. If so, remove the second number.
Example:
x = [1, 2, 3, 4, 5]
t = 3
1+2 = t, so remove 2. No other pairs... | from functools import reduce
def trouble(x, t):
return reduce(lambda a, u: a + ([u] if not a or a[-1] + u != t else []), x[1:], x[0:1]) | python | train | abovesol | codeparrot/apps | all |
Solve in Python:
Appleman and Toastman play a game. Initially Appleman gives one group of n numbers to the Toastman, then they start to complete the following tasks: Each time Toastman gets a group of numbers, he sums up all the numbers and adds this sum to the score. Then he gives the group to the Appleman. Each tim... | n = int(input())
a = list(map(int, input().split()))
a.sort(reverse=True)
s = sum(a)
res = s
while len(a) > 1:
res += s
s -= a.pop()
print(res) | python | test | qsol | codeparrot/apps | all |
Solve in Python:
You've got an undirected graph, consisting of n vertices and m edges. We will consider the graph's vertices numbered with integers from 1 to n. Each vertex of the graph has a color. The color of the i-th vertex is an integer c_{i}.
Let's consider all vertices of the graph, that are painted some color ... | from collections import defaultdict
n,m = map(int,input().split())
g = defaultdict(set)
c = list(map(int,input().split()))
for _ in range(m):
x,y = map(int,input().split())
if(c[x-1]!=c[y-1]):g[c[x-1]].add(c[y-1])
if(c[y-1]!=c[x-1]):g[c[y-1]].add(c[x-1])
ma = 0
co = 10**5 + 1
f = 0
for i in g:
... | python | test | qsol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/853/A:
Helen works in Metropolis airport. She is responsible for creating a departure schedule. There are n flights that must depart today, the i-th of them is planned to depart at the i-th minute of the day.
Metropolis airport is the main tra... | from heapq import heappush,heappop,heapify
n,k=list(map(int,input().split()))
*l,=list(map(int,input().split()))
q=[(-l[i],i)for i in range(k)]
heapify(q)
a=[0]*n
s=0
for i in range(k,n) :
heappush(q,(-l[i],i))
x,j=heappop(q)
s-=x*(i-j)
a[j]=i+1
for i in range(n,n+k) :
x,j=heappop(q)
s-=x*(i-j)
... | python | train | abovesol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/1107/A:
You are given a sequence $s$ consisting of $n$ digits from $1$ to $9$.
You have to divide it into at least two segments (segment — is a consecutive sequence of elements) (in other words, you have to place separators between some digits... | q = int(input())
for _ in range(q):
n = int(input())
s = input()
if n > 2:
print('YES')
print(2)
print(s[0],s[1:])
else:
if int(s[0]) >= int(s[1]):
print('NO')
else:
print('YES')
print(2)
print(s[0],s[1]) | python | test | abovesol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/1372/C:
Patrick likes to play baseball, but sometimes he will spend so many hours hitting home runs that his mind starts to get foggy! Patrick is sure that his scores across $n$ sessions follow the identity permutation (ie. in the first game he... | from collections import defaultdict as dd
from collections import deque
import bisect
import heapq
def ri():
return int(input())
def rl():
return list(map(int, input().split()))
def solve():
n = ri()
A = rl()
first_wrong = -1
first_break = -1
skip = False
for i, a in enumerate(A):
... | python | test | abovesol | codeparrot/apps | all |
Solve in Python:
Gennady owns a small hotel in the countryside where he lives a peaceful life. He loves to take long walks, watch sunsets and play cards with tourists staying in his hotel. His favorite game is called "Mau-Mau".
To play Mau-Mau, you need a pack of $52$ cards. Each card has a suit (Diamonds — D, Clubs —... | s1 = input()
ls = input().split()
print('YES' if any(any(s1[i] == ls[j][i] for i in range(2)) for j in range(5)) else 'NO') | python | test | qsol | codeparrot/apps | all |
I found an interesting problem on https://leetcode.com/problems/contains-duplicate/:
Given an array of integers, find if the array contains any duplicates.
Your function should return true if any value appears at least twice in the array, and it should return false if every element is distinct.
Example 1:
Input: [1... | class Solution:
def containsDuplicate(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
diction = {}
flag = 0
for number in nums:
if number not in diction:
diction[number] = 1
else:
... | python | train | abovesol | codeparrot/apps | all |
Solve in Python:
We have a chocolate bar partitioned into H horizontal rows and W vertical columns of squares.
The square (i, j) at the i-th row from the top and the j-th column from the left is dark if S_{i,j} is 0, and white if S_{i,j} is 1.
We will cut the bar some number of times to divide it into some number of bl... | # E - Dividing Chocolate
import numpy as np
H, W, K = list(map(int, input().split()))
S = np.zeros((H, W), dtype=np.int64)
ans = H+W
for i in range(H):
S[i] = list(str(input()))
for m in range(2**(H-1)):
wp = np.zeros((H, W), dtype=np.int64)
wq = np.zeros((H, ), dtype=np.int64)
wp[0] = S[0]
cut ... | python | test | qsol | codeparrot/apps | all |
I found an interesting problem on https://atcoder.jp/contests/abc113/tasks/abc113_b:
A country decides to build a palace.
In this country, the average temperature of a point at an elevation of x meters is T-x \times 0.006 degrees Celsius.
There are N places proposed for the place. The elevation of Place i is H_i meters... | from typing import List
def answer(n: int, t: int, a: int, hs: List[int]) -> int:
import sys
result = 0
temperature_difference = sys.maxsize
for i, h in enumerate(hs, start=1):
temp = abs(a - (t - h * 0.006))
if temp < temperature_difference:
temperature_differenc... | python | test | abovesol | codeparrot/apps | all |
Solve in Python:
Dreamoon is standing at the position 0 on a number line. Drazil is sending a list of commands through Wi-Fi to Dreamoon's smartphone and Dreamoon follows them.
Each command is one of the following two types: Go 1 unit towards the positive direction, denoted as '+' Go 1 unit towards the negative dir... | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import itertools
s1 = input()
s2 = input()
s1_p = s1.count('+')
s1_n = s1.count('-')
s2_p = s2.count('+')
s2_n = s2.count('-')
s2_q = s2.count('?')
correct_pos = s1_p - s1_n
drea_pos = s2_p - s2_n
diff_pos = correct_pos - drea_pos
if s2_q == 0:
if diff_pos == 0... | python | test | qsol | codeparrot/apps | all |
Solve in Python:
You have a string s = s_1s_2...s_{|}s|, where |s| is the length of string s, and s_{i} its i-th character.
Let's introduce several definitions: A substring s[i..j] (1 ≤ i ≤ j ≤ |s|) of string s is string s_{i}s_{i} + 1...s_{j}. The prefix of string s of length l (1 ≤ l ≤ |s|) is string s[1..l]. Th... | s = str(input())
lps = [0]*100005
dp = [0]*100005
ada = [0]*100005
tunda = [0]*100005
n = len(s)
i = 1
j = 0
lps[0] = 0
while(i < n):
if (s[i] == s[j]):
j += 1
lps[i] = j
i += 1
elif (j == 0):
lps[i] = 0
i += 1
else:
j = lps[j-1]
for i in range(n-1,-1,-1... | python | test | qsol | codeparrot/apps | all |
Solve in Python:
You have a given picture with size $w \times h$. Determine if the given picture has a single "+" shape or not. A "+" shape is described below:
A "+" shape has one center nonempty cell. There should be some (at least one) consecutive non-empty cells in each direction (left, right, up, down) from the... | n, m = map(int, input().split())
s = []
for i in range(n):
s.append(input())
flag = False
def check(x, y):
if s[x-1][y-1] == s[x-1][y+1] == s[x+1][y-1] == s[x+1][y+1] == '.' and s[x-1][y] == s[x][y] == s[x+1][y] == s[x][y-1] == s[x][y+1] == '*':
return True
return False
def supercheck(x, y):
... | python | test | qsol | codeparrot/apps | all |
I found an interesting problem on https://leetcode.com/problems/combination-sum-ii/:
Given a collection of candidate numbers (candidates) and a target number (target), find all unique combinations in candidates where the candidate numbers sums to target.
Each number in candidates may only be used once in the combinati... | class Solution(object):
def combinationSum2(self, candidates, target):
"""
:type candidates: List[int]
:type target: int
:rtype: List[List[int]]
"""
result = []
temp = []
candidates.sort(reverse=True)
self.util(candidates, target, r... | python | test | abovesol | codeparrot/apps | all |
Solve in Python:
Chouti was doing a competitive programming competition. However, after having all the problems accepted, he got bored and decided to invent some small games.
He came up with the following game. The player has a positive integer $n$. Initially the value of $n$ equals to $v$ and the player is able to do... | n = int(input())
if n == 2:
print(2)
else:
print(1) | python | test | qsol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/1225/B1:
The only difference between easy and hard versions is constraints.
The BerTV channel every day broadcasts one episode of one of the $k$ TV shows. You know the schedule for the next $n$ days: a sequence of integers $a_1, a_2, \dots, a_... | t = int(input())
for i in range(t):
n,k,d = map(int,input().split())
minn = k
a = [int(i) for i in input().split()]
for i in range(n - d + 1):
m = set(a[i:i + d])
minn = min(minn,len(m))
print (minn) | python | test | abovesol | codeparrot/apps | all |
Solve in Python:
The Squareland national forest is divided into equal $1 \times 1$ square plots aligned with north-south and east-west directions. Each plot can be uniquely described by integer Cartesian coordinates $(x, y)$ of its south-west corner.
Three friends, Alice, Bob, and Charlie are going to buy three distin... | ax, ay = list(map(int, input().split()))
bx, by = list(map(int, input().split()))
cx, cy = list(map(int, input().split()))
def f(cx, ax, bx, cy, ay, by):
mxy = max(ay, by, cy)
mny = min(ay, by, cy)
print(abs(cx - bx) + mxy - mny + 1)
for i in range(mny, mxy + 1):
print(ax, i)
if cx <= bx:
... | python | test | qsol | codeparrot/apps | all |
Solve in Python:
# Task
Two arrays are called similar if one can be obtained from another by swapping at most one pair of elements.
Given two arrays, check whether they are similar.
# Example
For `A = [1, 2, 3]` and `B = [1, 2, 3]`, the output should be `true;`
For `A = [1, 2, 3]` and `B = [2, 1, 3]`, the output sh... | def are_similar(a, b):
return sorted(a)==sorted(b) and sum(1 for x, y in zip(a,b) if x!=y)<=2 | python | train | qsol | codeparrot/apps | all |
I found an interesting problem on https://leetcode.com/problems/maximum-level-sum-of-a-binary-tree/:
Given the root of a binary tree, the level of its root is 1, the level of its children is 2, and so on.
Return the smallest level X such that the sum of all the values of nodes at level X is maximal.
Example 1:
Input... | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def maxLevelSum(self, root: TreeNode) -> int:
if not root: return
st=[[root,0]]
ll=[]
... | python | train | abovesol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/1029/E:
You are given an undirected tree consisting of $n$ vertices. An undirected tree is a connected undirected graph with $n - 1$ edges.
Your task is to add the minimum number of edges in such a way that the length of the shortest path from... | import sys
def get_new_edges(graph):
n = len(graph)
far_vertex = []
pi = [None]*n
visit = [False]*n
visit[0]
queue = [[0,0]]
i = 0
while True:
if i >= len(queue): break
current, d = queue[i]
i += 1
visit[current] = True
for v in graph[current]... | python | test | abovesol | codeparrot/apps | all |
Solve in Python:
The activity of a panipuri seller is "making a panipuri and putting it on the palte of his customer".
$N$ customers are eating panipuri, Given an array $A$ of length $N$, $i^{th}$ customer takes $A_i$ seconds to eat a panipuri.
The Speed of Panipuri seller refers to the number of customers ser... | # your code goes here
import math
t = int(input())
for i in range(t):
a = int(input())
val = input().split()
val = [int(x) for x in val]
ans = a/min(val)
print(math.ceil(ans)) | python | train | qsol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/789/B:
Masha really loves algebra. On the last lesson, her strict teacher Dvastan gave she new exercise.
You are given geometric progression b defined by two integers b_1 and q. Remind that a geometric progression is a sequence of integers b_1... | miis = lambda:list(map(int,input().split()))
b,q,l,m = miis()
*a, = miis()
c = 0
for _ in ' '*100:
if abs(b)>l: break
if b not in a: c+=1
b*=q
if c<35:
print (c)
else:
print ('inf') | python | test | abovesol | codeparrot/apps | all |
Solve in Python:
The dragon's curve is a self-similar fractal which can be obtained by a recursive method.
Starting with the string `D0 = 'Fa'`, at each step simultaneously perform the following operations:
```
replace 'a' with: 'aRbFR'
replace 'b' with: 'LFaLb'
```
For example (spaces added for more visibility) : ... | def Dragon(n, Curve='Fa'):
if type(n)!=int or n%1!=0 or n<0: return ''
elif n==0:
return Curve.replace('a','').replace('b','')
else:
#now need to add an extra step where we swap out a dn b because otherwise the replace will affect the outcome. ie the replaces are not concurrent
return Drag... | python | train | qsol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/405/A:
Little Chris is bored during his physics lessons (too easy), so he has built a toy box to keep himself occupied. The box is special, since it has the ability to change gravity.
There are n columns of toy cubes in the box arranged in a l... | input()
print(*sorted(map(int, input().split()))) | python | test | abovesol | codeparrot/apps | all |
Solve in Python:
You have three tasks, all of which need to be completed.
First, you can complete any one task at cost 0.
Then, just after completing the i-th task, you can complete the j-th task at cost |A_j - A_i|.
Here, |x| denotes the absolute value of x.
Find the minimum total cost required to complete all the tas... | a, b, c = map(int, input().split())
res = [abs(a-b), abs(a-c), abs(b-c)]
print(sum(res)-max(res)) | python | test | qsol | codeparrot/apps | all |
Solve in Python:
Write a program to check whether a triangle is valid or not, when the three angles of the triangle are the inputs. A triangle is valid if the sum of all the three angles is equal to 180 degrees.
-----Input-----
The first line contains an integer T, the total number of testcases. Then T lines follow, ... | n=int(input())
for i in range(n):
a,b,c=map(int,input().split())
if a>0 and b>0 and c>0 and a+b+c==180:
print("YES")
else:
print("NO") | python | train | qsol | codeparrot/apps | all |
Solve in Python:
There are n parliamentarians in Berland. They are numbered with integers from 1 to n. It happened that all parliamentarians with odd indices are Democrats and all parliamentarians with even indices are Republicans.
New parliament assembly hall is a rectangle consisting of a × b chairs — a rows of b ch... | [n,a,b] = list(map(int,input().split(' ')))
r = [(b+1)*[0] for _ in range(a+1)]
t = list(range(1, n+1))
for i in range(1,a+1):
for j in range(1,b+1):
for it in t:
if (r[i-1][j] == 0 or r[i-1][j]%2 != it%2) and (r[i][j-1] == 0 or r[i][j-1]%2 != it%2):
r[i][j] = it
... | python | test | qsol | codeparrot/apps | all |
I found an interesting problem on https://leetcode.com/problems/task-scheduler/:
Given a char array representing tasks CPU need to do. It contains capital letters A to Z where different letters represent different tasks.Tasks could be done without original order. Each task could be done in one interval. For each interv... | class Solution:
def leastInterval(self, tasks, n):
"""
:type tasks: List[str]
:type n: int
:rtype: int
"""
if not tasks:
return 0
counts = {}
for i in tasks:
if i in counts:
counts[i] += 1
... | python | train | abovesol | codeparrot/apps | all |
I found an interesting problem on https://atcoder.jp/contests/abc091/tasks/abc091_b:
Takahashi has N blue cards and M red cards.
A string is written on each card. The string written on the i-th blue card is s_i, and the string written on the i-th red card is t_i.
Takahashi will now announce a string, and then check eve... | from collections import Counter
def main():
n = int(input())
blue = Counter(input() for _ in range(n))
m = int(input())
red = Counter(input() for _ in range(m))
ans = 0
for name, amount in blue.items():
if name in red.keys():
temp = amount - red[name]
else:
... | python | test | abovesol | codeparrot/apps | all |
Solve in Python:
We are given two arrays A and B of words. Each word is a string of lowercase letters.
Now, say that word b is a subset of word a if every letter in b occurs in a, including multiplicity. For example, "wrr" is a subset of "warrior", but is not a subset of "world".
Now say a word a from A is universal ... | class Solution:
def wordSubsets(self, A: List[str], B: List[str]) -> List[str]:
\"\"\"def checkSubset(a, B):
aDict = {}
bDict = {}
for b in B:
bSet = set(b)
for c in bSet:
if b.count(c) > a.count(c):
... | python | train | qsol | codeparrot/apps | all |
Solve in Python:
You are given a matrix with $n$ rows (numbered from $1$ to $n$) and $m$ columns (numbered from $1$ to $m$). A number $a_{i, j}$ is written in the cell belonging to the $i$-th row and the $j$-th column, each number is either $0$ or $1$.
A chip is initially in the cell $(1, 1)$, and it will be moved to ... | T = int(input())
for _ in range(T):
N,M = list(map(int,input().split()))
A = [list(map(int,input().split())) for i in range(N)]
L = N+M-1
c0 = [0]*L
c1 = [0]*L
for i,row in enumerate(A):
for j,a in enumerate(row):
if a==0:
c0[i+j] += 1
else:
... | python | test | qsol | codeparrot/apps | all |
I found an interesting problem on https://www.codewars.com/kata/59b139d69c56e8939700009d:
Write a method named `getExponent(n,p)` that returns the largest integer exponent `x` such that p^(x) evenly divides `n`. if `p<=1` the method should return `null`/`None` (throw an `ArgumentOutOfRange` exception in C#).
I tried i... | def get_exponent(n, p):
return next(iter(i for i in range(int(abs(n) ** (1/p)), 0, -1) if (n / p**i) % 1 == 0), 0) if p > 1 else None | python | train | abovesol | codeparrot/apps | all |
Solve in Python:
Joisino the magical girl has decided to turn every single digit that exists on this world into 1.
Rewriting a digit i with j (0≤i,j≤9) costs c_{i,j} MP (Magic Points).
She is now standing before a wall. The wall is divided into HW squares in H rows and W columns, and at least one square contains a digi... | H, W = list(map(int, input().split()))
C = [list(map(int, input().split())) for _ in range(10)]
for i in range(10):
for k in range(10):
for l in range(10):
C[k][l] = min(C[k][l], C[k][i]+C[i][l])
ans = 0
"""
for _ in C:
print(_)
"""
for i in range(H):
A = list(map(int,input().split()))
... | python | test | qsol | codeparrot/apps | all |
Solve in Python:
Given a standard english sentence passed in as a string, write a method that will return a sentence made up of the same words, but sorted by their first letter. However, the method of sorting has a twist to it:
* All words that begin with a lower case letter should be at the beginning of the sorted sen... | def pseudo_sort(s):
s = ''.join(i for i in s if i.isalpha() or i is ' ')
a = sorted(i for i in s.split() if i[0].islower())
b = sorted((i for i in s.split() if i[0].isupper()),key=lambda x: x.lower(),reverse=True)
return ' '.join(a+b) | python | train | qsol | codeparrot/apps | all |
Solve in Python:
Create an identity matrix of the specified size( >= 0).
Some examples:
```
(1) => [[1]]
(2) => [ [1,0],
[0,1] ]
[ [1,0,0,0,0],
[0,1,0,0,0],
(5) => [0,0,1,0,0],
[0,0,0,1,0],
[0,0,0,0,1] ]
``` | from numpy import identity, ndarray
def get_matrix(n):
return identity(n).tolist() | python | train | qsol | codeparrot/apps | all |
Solve in Python:
You have an array A of size N containing only positive numbers. You have to output the maximum possible value of A[i]%A[j] where 1<=i,j<=N.
-----Input-----
The first line of each test case contains a single integer N denoting the size of the array. The next N lines contains integers A1, A2, ..., AN d... | n = int(input())
a = []
for i in range(n):
a.append(int(input()))
m1 = 0
m2 = 0
for e in a:
if (e > m1):
m2 = m1
m1 = e
elif (e > m2 and e != m1):
m2 = e
ans = 0
for e in a:
temp = m1%e
if (temp>ans):
ans = temp
print(max(m2%m1,ans)) | python | train | qsol | codeparrot/apps | all |
Solve in Python:
The number n is Evil if it has an even number of 1's in its binary representation.
The first few Evil numbers: 3, 5, 6, 9, 10, 12, 15, 17, 18, 20
The number n is Odious if it has an odd number of 1's in its binary representation.
The first few Odious numbers: 1, 2, 4, 7, 8, 11, 13, 14, 16, 19
You have ... | def evil(n: int) -> str:
"""
Check if the given number is:
- evil: it has an even number of 1's in its binary representation
- odious: it has an odd number of 1's in its binary representation
"""
return f"It's {'Odious' if str(bin(n)).count('1') % 2 else 'Evil'}!" | python | train | qsol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/1012/D:
There are two strings s and t, consisting only of letters a and b. You can make the following operation several times: choose a prefix of s, a prefix of t and swap them. Prefixes can be empty, also a prefix can coincide with a whole str... | def blokovi(x):
ret = [0]
for i in range(len(x) - 1):
if x[i] != x[i + 1]:
ret.append(i + 1)
return ret + [len(x)]
s = input()
t = input()
ss = blokovi(s)
tt = blokovi(t)
if s[-1] == 'a':
s += 'b'
else:
s += 'a'
if t[-1] == 'a':
t += 'b'
else:
t += 'a'
def greedy(x, ... | python | test | abovesol | codeparrot/apps | all |
Solve in Python:
Some time ago Lesha found an entertaining string $s$ consisting of lowercase English letters. Lesha immediately developed an unique algorithm for this string and shared it with you. The algorithm is as follows.
Lesha chooses an arbitrary (possibly zero) number of pairs on positions $(i, i + 1)$ in suc... | s = input().strip();N = len(s)
if len(s) == 1:print(1, s[0]);return
X = [s[-1], s[-2]+s[-1] if s[-2]!=s[-1] else ""];Y = [1, 2 if s[-2]!=s[-1] else 0]
for i in range(N-3, -1, -1):
c = s[i];k1 = c+X[-1];ng = Y[-1]+1
if ng > 10:k1 = k1[:5] + "..." + k1[-2:]
if c == s[i+1] and k1 > X[-2]:k1 = X[-2];ng = Y[-2]
... | python | test | qsol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/1206/B:
You are given $n$ numbers $a_1, a_2, \dots, a_n$. With a cost of one coin you can perform the following operation:
Choose one of these numbers and add or subtract $1$ from it.
In particular, we can apply this operation to the same num... | q=int(input())
w=list(map(int,input().split()))
e=0
r=0
t=0
for i in w:
if i<0:
e+=-1-i
r+=1
elif i>0:
e+=i-1
else:
e+=1
t+=1
if r%2==1:
if t>0:
print(e)
else:
print(e+2)
else:
print(e) | python | test | abovesol | codeparrot/apps | all |
Solve in Python:
The semester is already ending, so Danil made an effort and decided to visit a lesson on harmony analysis to know how does the professor look like, at least. Danil was very bored on this lesson until the teacher gave the group a simple task: find 4 vectors in 4-dimensional space, such that every coordi... | k = int(input())
if (k == 0):
print('+')
return
answer = [['+', '+'], ['+', '*']]
length = 2
for i in range(k - 1):
new = []
for i in answer:
temp = []
for j in range(length):
if i[j] == '+':
temp += ['+', '+']
else:
temp += ['*',... | python | test | qsol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/455/A:
Alex doesn't like boredom. That's why whenever he gets bored, he comes up with games. One long winter evening he came up with a game and decided to play it.
Given a sequence a consisting of n integers. The player can make several steps.... | from collections import Counter
n = int(input())
sequence = list(map(int, input().split()))
numset = list(set(sequence))
k = len(numset)
numset.sort()
cnt = Counter(sequence)
f = [0] * (k + 1)
f[1] = cnt[numset[0]] * numset[0]
f[0] = 0
for i in range(2, k + 1):
if numset[i - 1] - numset[i - 2] == 1:
... | python | test | abovesol | codeparrot/apps | all |
Solve in Python:
Given is a string S of length N.
Find the maximum length of a non-empty string that occurs twice or more in S as contiguous substrings without overlapping.
More formally, find the maximum positive integer len such that there exist integers l_1 and l_2 ( 1 \leq l_1, l_2 \leq N - len + 1 ) that satisfy t... | import sys
#input = sys.stdin.buffer.readline
def main():
N = int(input())
s = input()
a,i,j = 0,0,1
while j < N:
if s[i:j] in s[j:]:
a = max(a,j-i)
j += 1
else:
i += 1
if i == j:
j += 1
print(a)
def __starti... | python | test | qsol | codeparrot/apps | all |
Solve in Python:
There is a farm whose length and width are A yard and B yard, respectively. A farmer, John, made a vertical road and a horizontal road inside the farm from one border to another, as shown below: (The gray part represents the roads.)
What is the area of this yard excluding the roads? Find it.
-----Not... | a,b= map(int,input().split())
print((a-1)*(b-1)) | python | test | qsol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/1417/C:
You are given an array $a$ consisting of $n$ integers numbered from $1$ to $n$.
Let's define the $k$-amazing number of the array as the minimum number that occurs in all of the subsegments of the array having length $k$ (recall that a ... | import sys
def main():
#n = iinput()
#k = iinput()
#m = iinput()
n = int(sys.stdin.readline().strip())
#n, k = rinput()
#n, m = rinput()
#m, k = rinput()
#n, k, m = rinput()
#n, m, k = rinput()
#k, n, m = rinput()
#k, m, n = rinput()
#m, k, n = rinput()
#m, ... | python | train | abovesol | codeparrot/apps | all |
I found an interesting problem on https://www.codechef.com/problems/POTATOES:
Farmer Feb has three fields with potatoes planted in them. He harvested x potatoes from the first field, y potatoes from the second field and is yet to harvest potatoes from the third field. Feb is very superstitious and believes that if the ... | def factors(n):
c=0
for i in range(1,n+1):
if n%i==0:
c+=1
return c
t=int(input())
for _ in range(t):
z=1
x,y=map(int,input().split(" "))
k=x+y
while(True):
t=k+z
if factors(t)==2:
break
else:
z+=1
print(z)
t-=1 | python | train | abovesol | codeparrot/apps | all |
I found an interesting problem on https://leetcode.com/problems/sum-root-to-leaf-numbers/:
Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number.
An example is the root-to-leaf path 1->2->3 which represents the number 123.
Find the total sum of all root-to-leaf numbers.
... | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
from copy import deepcopy
class Solution:
def sumNumbers(self, root):
"""
:type root: TreeNode
:rtype: int
... | python | train | abovesol | codeparrot/apps | all |
Solve in Python:
My friend wants a new band name for her band. She like bands that use the formula: "The" + a noun with the first letter capitalized, for example:
`"dolphin" -> "The Dolphin"`
However, when a noun STARTS and ENDS with the same letter, she likes to repeat the noun twice and connect them together with t... | def band_name_generator(name):
return name.capitalize()+name[1:] if name[0]==name[-1] else 'The '+ name.capitalize() | python | train | qsol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/643/B:
Bearland has n cities, numbered 1 through n. Cities are connected via bidirectional roads. Each road connects two distinct cities. No two roads connect the same pair of cities.
Bear Limak was once in a city a and he wanted to go to a ci... | n, k = list(map(int, input().split()))
a, b, c, d = list(map(int, input().split()))
if n == 4 or k < n + 1:
print(-1)
return
extra = 1
while extra == a or extra == b or extra == c or extra == d:
extra += 1
v = [a, c, extra, d]
k = extra + 1
while k <= n:
if k != a and k != b and k != c and k != d and k ... | python | test | abovesol | codeparrot/apps | all |
Solve in Python:
There is a row of m houses in a small city, each house must be painted with one of the n colors (labeled from 1 to n), some houses that has been painted last summer should not be painted again.
A neighborhood is a maximal group of continuous houses that are painted with the same color. (For example: ho... | from functools import lru_cache
class Solution:
def minCost(self, houses: List[int], cost: List[List[int]], m: int, n: int, target: int) -> int:
@lru_cache(None)
def dfs(i,prev,k):
if i>=m:
return 0 - int(k!=0)
if k<0:
... | python | train | qsol | codeparrot/apps | all |
I found an interesting problem on https://www.codewars.com/kata/59476f9d7325addc860000b9:
Mr. Khalkhoul, an amazing teacher, likes to answer questions sent by his students via e-mail, but he often doesn't have the time to answer all of them. In this kata you will help him by making a program that finds
some of the answ... | def answer(question,information):
info=[ i.split(" ") for i in information]
ques=question.lower().split(" ")
high=0 ; iHigh=-1
for i in range(len(info)):
score=0
for j in info[i]:
if j.lower() in ques:
score+=1
if score>high:
iHigh=i
... | python | train | abovesol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/255/C:
Gena loves sequences of numbers. Recently, he has discovered a new type of sequences which he called an almost arithmetical progression. A sequence is an almost arithmetical progression, if its elements can be represented as: a_1 = p, w... | import sys
from math import log2,floor,ceil,sqrt
# import bisect
# from collections import deque
Ri = lambda : [int(x) for x in sys.stdin.readline().split()]
ri = lambda : sys.stdin.readline().strip()
def input(): return sys.stdin.readline().strip()
def list2d(a, b, c): return [[c] * b for i in range(a)]
def list3d(... | python | test | abovesol | codeparrot/apps | all |
Solve in Python:
Pied Piper is a startup company trying to build a new Internet called Pipernet. Currently, they have $A$ users and they gain $X$ users everyday. There is also another company called Hooli, which has currently $B$ users and gains $Y$ users everyday.
Whichever company reaches $Z$ users first takes over P... | # cook your dish here
import heapq as hq
from math import floor
for _ in range(int(input())):
n,a,b,x,y,z=list(map(int,input().split()))
arr=[-int(i) for i in input().split()]
days=floor((z-b)/y)
if b+y*days==z:
z+=1
ans=0
hq.heapify(arr)
curr=a+days*x
while curr<z :
u=hq.heappop(arr)
u=-u
if u==0 ... | python | train | qsol | codeparrot/apps | all |
Solve in Python:
You have a multiset containing several integers. Initially, it contains $a_1$ elements equal to $1$, $a_2$ elements equal to $2$, ..., $a_n$ elements equal to $n$.
You may apply two types of operations: choose two integers $l$ and $r$ ($l \le r$), then remove one occurrence of $l$, one occurrence of ... | n = int(input()) + 1
l = list(map(int, input().split())) + [0]
out = 0
q = []
for v in l:
if v == 0:
dp = []
n = len(q)
for i in range(n):
curr = q[i] + i
smol = q[i]
for j in range(i - 1, -1, -1):
smol = min(q[j], smol)
di... | python | test | qsol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/799/C:
Arkady plays Gardenscapes a lot. Arkady wants to build two new fountains. There are n available fountains, for each fountain its beauty and cost are known. There are two types of money in the game: coins and diamonds, so each fountain co... | from operator import itemgetter
def get_one_max(arr, resource):
res = 0
for beauty, _ in [x for x in arr if x[1] <= resource]:
res = max(res, beauty)
return res
def get_two_max(arr, resource):
arr.sort(key=itemgetter(1))
best = [-1] * (resource + 1)
ptr = 0
for index, (beauty, pr... | python | train | abovesol | codeparrot/apps | all |
I found an interesting problem on https://www.codewars.com/kata/5736378e3f3dfd5a820000cb:
It's been a tough week at work and you are stuggling to get out of bed in the morning.
While waiting at the bus stop you realise that if you could time your arrival to the nearest minute you could get valuable extra minutes in be... | def bus_timer(time):
c = time.split(":")
z = int(c[1]) + 5
t = 0
if int(c[0]) == 23 and int(c[1]) >= 55:
c[0] = 0
c[1] = (int(c[1]) + 5) - 60
if int(c[1]) == 0:
t = 0
elif int(c[1]) > 0:
t = (((5 - int(c[0]))*60) + (60 - int(c[1])))
elif int(c... | python | train | abovesol | codeparrot/apps | all |
Solve in Python:
Lеt's create function to play cards. Our rules:
We have the preloaded `deck`:
```
deck = ['joker','2♣','3♣','4♣','5♣','6♣','7♣','8♣','9♣','10♣','J♣','Q♣','K♣','A♣',
'2♦','3♦','4♦','5♦','6♦','7♦','8♦','9♦','10♦','J♦','Q♦','K♦','A♦',
'2♥','3♥','4♥','5♥','6♥','7♥','8♥','9... | deck = ['joker','2♣','3♣','4♣','5♣','6♣','7♣','8♣','9♣','10♣','J♣','Q♣','K♣','A♣',
'2♦','3♦','4♦','5♦','6♦','7♦','8♦','9♦','10♦','J♦','Q♦','K♦','A♦',
'2♥','3♥','4♥','5♥','6♥','7♥','8♥','9♥','10♥','J♥','Q♥','K♥','A♥',
'2♠','3♠','4♠','5♠','6♠','7♠','8♠','9♠','10♠','J♠','Q♠'... | python | train | qsol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/272/D:
Little Dima has two sequences of points with integer coordinates: sequence (a_1, 1), (a_2, 2), ..., (a_{n}, n) and sequence (b_1, 1), (b_2, 2), ..., (b_{n}, n).
Now Dima wants to count the number of distinct sequences of points of lengt... | from math import sqrt,ceil,gcd
from collections import defaultdict
def modInverse(b,m):
g = gcd(b, m)
if (g != 1):
# print("Inverse doesn't exist")
return -1
else:
# If b and m are relatively prime,
# then modulo inverse is b^(m-2) mode m
return pow(b, m - 2, m)
d... | python | test | abovesol | codeparrot/apps | all |
Solve in Python:
The chef is trying to solve some pattern problems, Chef wants your help to code it. Chef has one number K to form a new pattern. Help the chef to code this pattern problem.
-----Input:-----
- First-line will contain $T$, the number of test cases. Then the test cases follow.
- Each test case contains ... | # cook your dish here
t=int(input(""))
while(t!=0):
s=''
k=int(input(""))
#print(k)
for i in range(k):
for j in range(k):
s=s+str(j+1)+str(i+1)
print(s)
s=''
t-=1 | python | train | qsol | codeparrot/apps | all |
Solve in Python:
Takahashi loves takoyaki - a ball-shaped snack.
With a takoyaki machine, he can make at most X pieces of takoyaki at a time, taking T minutes regardless of the number of pieces to make.
How long does it take to make N takoyaki?
-----Constraints-----
- 1 \leq N,X,T \leq 1000
- All values in input are... | a=list(map(int,input().split()))
if a[0]%a[1]==0:
b=(a[0]//a[1])
else:
b=(a[0]//a[1])+1
c=b*a[2]
print(c) | python | test | qsol | codeparrot/apps | all |
Solve in Python:
You are given an empty grid with $N$ rows (numbered $1$ through $N$) and $M$ columns (numbered $1$ through $M$). You should fill this grid with integers in a way that satisfies the following rules:
- For any three cells $c_1$, $c_2$ and $c_3$ such that $c_1$ shares a side with $c_2$ and another side wi... | for _ in range(int(input())):
n, m = list(map(int, input().split()))
ans = [[0 for i in range(m)] for i in range(n)]
k = 0
if n == 1:
for i in range(m):
if i%4 == 0 or i%4 == 1:
t = 1
else:
t = 2
ans[0][i] = t
k = max(k, ans[0][i])
elif m == 1:
for i in range(n):
if i%4 == 0 or i%4 == 1:... | python | train | qsol | codeparrot/apps | all |
I found an interesting problem on https://www.codewars.com/kata/57aaaada72292d3b8f0001b4:
This the second part part of the kata:
https://www.codewars.com/kata/the-sum-and-the-rest-of-certain-pairs-of-numbers-have-to-be-perfect-squares
In this part we will have to create a faster algorithm because the tests will be mo... | def n_closestPairs_tonum(num, k):
r=[]
m=2
while(m*m<num):
for n in range(1,m):
if (m*m+n*n>=num):
break
r.append([m*m+n*n,2*m*n])
m+=1
return sorted(r,reverse=True)[:k] | python | train | abovesol | codeparrot/apps | all |
I found an interesting problem on https://www.codewars.com/kata/5888145122fe8620950000f0:
# Task
`N` candles are placed in a row, some of them are initially lit. For each candle from the 1st to the Nth the following algorithm is applied: if the observed candle is lit then states of this candle and all candles before i... | def switch_lights(initial_states):
states = list(initial_states)
parity = 0
for i in reversed(range(len(states))):
parity ^= initial_states[i]
states[i] ^= parity
return states | python | train | abovesol | codeparrot/apps | all |
Solve in Python:
Santa Claus has Robot which lives on the infinite grid and can move along its lines. He can also, having a sequence of m points p_1, p_2, ..., p_{m} with integer coordinates, do the following: denote its initial location by p_0. First, the robot will move from p_0 to p_1 along one of the shortest paths... | n = int(input())
a = input()
s = set()
ans = 0
for j in range(n):
if a[j] == 'R':
if 'L' in s:
ans += 1
s = set()
s.add(a[j])
elif a[j] == 'L':
if 'R' in s:
ans += 1
s = set()
s.add(a[j])
elif a[j]... | python | test | qsol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/727/D:
The organizers of a programming contest have decided to present t-shirts to participants. There are six different t-shirts sizes in this problem: S, M, L, XL, XXL, XXXL (sizes are listed in increasing order). The t-shirts are already pre... | shorts = [int(t) for t in input().split()]
n = int(input())
d = dict()
d["S"] = 0
d["M"] = 1
d["L"] = 2
d["XL"] = 3
d["XXL"] = 4
d["XXXL"] = 5
people = []
order = [t for t in range(n)]
for _ in range(n):
people.append(input().split(","))
order.sort(key=lambda x: [d[people[x][0]], len(people[x])])
ans = dict()
for i... | python | test | abovesol | codeparrot/apps | all |
I found an interesting problem on https://atcoder.jp/contests/abc079/tasks/abc079_a:
We call a 4-digit integer with three or more consecutive same digits, such as 1118, good.
You are given a 4-digit integer N. Answer the question: Is N good?
-----Constraints-----
- 1000 ≤ N ≤ 9999
- N is an integer.
-----Input-----... | n = input()
arr = []
for i in range(10):
s = ""
for j in range(3):
s += str(i)
arr.append(s)
if n[0:3] in arr or n[1:4] in arr:
print("Yes")
else:
print("No") | python | test | abovesol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/412/A:
The R1 company has recently bought a high rise building in the centre of Moscow for its main office. It's time to decorate the new office, and the first thing to do is to write the company's slogan above the main entrance to the building... | def main():
n, k = map(int, input().split())
s = input()
if k - 1 <= n - k:
for i in range(k - 1):
print("LEFT")
for i in range(n - 1):
print("PRINT", s[i])
print("RIGHT")
print("PRINT", s[n - 1])
else:
for i in range(n - k):
print("RIGHT")
for i in range(n - 1, 0, -1):
print("PRINT", s[i])... | python | test | abovesol | codeparrot/apps | all |
Solve in Python:
Create a function hollow_triangle(height) that returns a hollow triangle of the correct height. The height is passed through to the function and the function should return a list containing each line of the hollow triangle.
```
hollow_triangle(6) should return : ['_____#_____', '____#_#____', '___#___... | hollow_triangle=lambda n:["".join([['_','#'][k in[n-1-i,n-1+i]]for k in range(n*2-1)])for i in range(n-1)]+[f"{'#'*(n*2-1)}"] | python | train | qsol | codeparrot/apps | all |
Solve in Python:
Takahashi is at an all-you-can-eat restaurant.
The restaurant offers N kinds of dishes. It takes A_i minutes to eat the i-th dish, whose deliciousness is B_i.
The restaurant has the following rules:
- You can only order one dish at a time. The dish ordered will be immediately served and ready to eat.
... | import numpy as np
N, T = map(int, input().split())
AB = []
for i in range(N):
A, B = map(int, input().split())
AB.append([A, B])
AB.sort()
dp = np.zeros(T, dtype=int)
ans = 0
for a, b in AB:
ans = max(ans, dp[-1] + b)
dp[a:] = np.maximum(dp[a:], dp[:-a] + b)
print(ans) | python | test | qsol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/990/C:
A bracket sequence is a string containing only characters "(" and ")".
A regular bracket sequence is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters "1" and "+" between the origina... | import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,copy,functools
sys.setrecursionlimit(10**7)
inf = 10**20
eps = 1.0 / 10**10
mod = 998244353
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF... | python | test | abovesol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/641/E:
Little Artem has invented a time machine! He could go anywhere in time, but all his thoughts of course are with computer science. He wants to apply this time machine to a well-known data structure: multiset.
Artem wants to create a basi... | from bisect import *
d = [{}, {}]
i = [0, 0]
for q in range(int(input())):
a, t, x = map(int, input().split())
for k in [0, 1]:
d[k][x] = d[k].get(x, [])
i[k] = bisect(d[k][x], t)
if a < 3: d[-a][x].insert(i[-a], t)
else: print(i[1] - i[0]) | python | test | abovesol | codeparrot/apps | all |
Solve in Python:
Mike and some bears are playing a game just for fun. Mike is the judge. All bears except Mike are standing in an n × m grid, there's exactly one bear in each cell. We denote the bear standing in column number j of row number i by (i, j). Mike's hands are on his ears (since he's the judge) and each bear... | n, m, q = list(map(int, input().split()))
def csum(row):
return max(list(map(len, "".join(map(str, row)).split("0"))))
grid = ["".join(input().split()) for i in range(n)]
score = [max(list(map(len, row.split("0")))) for row in grid]
for i in range(q):
i, j = list(map(int, input().split()))
row = grid[i-1]
... | python | test | qsol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/263/A:
You've got a 5 × 5 matrix, consisting of 24 zeroes and a single number one. Let's index the matrix rows by numbers from 1 to 5 from top to bottom, let's index the matrix columns by numbers from 1 to 5 from left to right. In one move, you... | a = []
for i in range(5):
a.extend(map(int, input().split()))
a = a.index(1)
print(abs(a // 5 - 2) + abs(a % 5 - 2)) | python | test | abovesol | codeparrot/apps | all |
I found an interesting problem on https://www.codewars.com/kata/5c80b55e95eba7650dc671ea:
__Definition:__ According to Wikipedia, a [complete binary tree](https://en.wikipedia.org/wiki/Binary_tree#Types_of_binary_trees) is a binary tree _"where every level, except possibly the last, is completely filled, and all nodes ... | def mid(n):
x = 1 << (n.bit_length() - 1)
return x-1 if x//2 - 1 <= n-x else n-x//2
def complete_binary_tree(a):
res, queue = [], [a]
while queue:
L = queue.pop(0)
m = mid(len(L))
res.append(L[m])
if m: queue.append(L[:m])
if m < len(L)-1: queue.append(L[m+1:])
... | python | train | abovesol | codeparrot/apps | all |
I found an interesting problem on https://www.codechef.com/problems/WATMELON:
Let's call a sequence good if the sum of all its elements is $0$.
You have a sequence of integers $A_1, A_2, \ldots, A_N$. You may perform any number of operations on this sequence (including zero). In one operation, you should choose a valid... | n=int(input())
for i in range(n):
t=int(input())
m=list(map(int,input().split()))
p,q=0,0
if t==1:
if m[0]>=0:
print('YES')
else:
print('NO')
else:
for i in m:
if i<0:
q+=1
else:
p+=1
if p>=abs(q):
print('YES')
else:
print('NO') | python | train | abovesol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/1129/C:
In Morse code, an letter of English alphabet is represented as a string of some length from $1$ to $4$. Moreover, each Morse code representation of an English letter contains only dots and dashes. In this task, we will represent a dot w... | MOD = 10 ** 9 + 7
BAD = ([0, 0, 1, 1], [0, 1, 0, 1], [1, 1, 1, 0], [1, 1, 1, 1])
def zfunc(s):
z = [0] * len(s)
l = r = 0
for i in range(1, len(s)):
if i <= r:
z[i] = min(r - i + 1, z[i - l])
while i + z[i] < len(s) and s[z[i]] == s[i + z[i]]:
z[i] += 1
if i ... | python | test | abovesol | codeparrot/apps | all |
Solve in Python:
Boboniu likes bit operations. He wants to play a game with you.
Boboniu gives you two sequences of non-negative integers $a_1,a_2,\ldots,a_n$ and $b_1,b_2,\ldots,b_m$.
For each $i$ ($1\le i\le n$), you're asked to choose a $j$ ($1\le j\le m$) and let $c_i=a_i\& b_j$, where $\&$ denotes the bitwise AN... | n,m = [int(i) for i in input().split()]
a = [int(i) for i in input().split()]
b = [int(i) for i in input().split()]
c=0
for i in range(0,513):
c=1
for j in a:
u = 0
for k in b:
if(i|(j&k)==i):
u = 1
break
if(u==0):
c=0
b... | python | test | qsol | codeparrot/apps | all |
Solve in Python:
The famous joke programming language HQ9+ has only 4 commands. In this problem we will explore its subset — a language called HQ...
-----Input-----
The only line of the input is a string between 1 and 10^6 characters long.
-----Output-----
Output "Yes" or "No".
-----Examples-----
Input
HHHH
Ou... | import sys
s = input()
qc = s.count('Q')
qs = int(qc ** 0.5)
hc = s.count('H')
if qs == 0:
print('Yes')
return
if not qc == qs ** 2:
print('No')
return
if not hc % (qs + 1) == 0:
print('No')
return
t = s.split('Q')
pre = len(t[0]) // 2
suf = 0 if len(t) == 1 else len(t[-1]) // 2
a = ['H' * pre... | python | test | qsol | codeparrot/apps | all |
Solve in Python:
You have unweighted tree of $n$ vertices. You have to assign a positive weight to each edge so that the following condition would hold:
For every two different leaves $v_{1}$ and $v_{2}$ of this tree, bitwise XOR of weights of all edges on the simple path between $v_{1}$ and $v_{2}$ has to be equal ... | import sys
input = sys.stdin.readline
n = int(input())
neigh = [[] for i in range(n)]
l = []
for i in range(n - 1):
a, b = list(map(int, input().split()))
a -= 1
b -= 1
neigh[a].append(b)
neigh[b].append(a)
l.append((a,b))
#Max
edges = set()
for a, b in l:
if len(neigh[a]) == 1:
a... | python | train | qsol | codeparrot/apps | all |
Solve in Python:
Uppal-balu is busy in extraction of gold from ores. He got an assignment from his favorite professor MH sir, but he got stuck in a problem. Can you help Uppal-balu to solve the problem.
You are given an array $a_1$, $a_2$, $\dots$, $a_n$ of length $n$. You can perform the following operations on it:
- ... | t=1
for _ in range(t):
n,m,k=(list(map(int,input().split())))
a=list(map(int,input().split()))
for i in range(n):
a[i]=a[i]%k
s=1
for j in range(k):
ss=0
v=0
for i in range(n):
v+=min(abs(a[i]-j),k-abs(a[i]-j))
while ss<i and v>m:
... | python | test | qsol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/895/A:
Students Vasya and Petya are studying at the BSU (Byteland State University). At one of the breaks they decided to order a pizza. In this problem pizza is a circle of some radius. The pizza was delivered already cut into n pieces. The i-... | n = int( input() )
a = list( map( int, input().split() ) )
a = a + a
#print( a )
mid = n//2
best = 99999999999999999999999
for i in range( n ):
sub = a[i:i+n]
#print( sub )
d = sum(sub)
best = min( best, d )
s = 0
#print( d, s )
for j in range( n ):
s += sub[j]
d -= su... | python | test | abovesol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/801/A:
Tonio has a keyboard with only two letters, "V" and "K".
One day, he has typed out a string s with only these two letters. He really likes it when the string "VK" appears, so he wishes to change at most one letter in the string (or do n... | def alternate(c):
if c == "V":
return "K"
return "V"
s = input()
res = s.count("VK")
for i in range(len(s)):
res = max(res, (s[:i]+alternate(s[i])+s[i+1:]).count("VK"))
print(res) | python | test | abovesol | codeparrot/apps | all |
Solve in Python:
Petr likes to come up with problems about randomly generated data. This time problem is about random permutation. He decided to generate a random permutation this way: he takes identity permutation of numbers from $1$ to $n$ and then $3n$ times takes a random pair of different elements and swaps them. ... | n = int(input())
l = list(map(int, input().split()))
c = 1
ans = 0
vis = [0] * 1000005
for i in range(n):
p = i
vis[i + 1] = 1
while vis[l[p]] != 1:
ans -= -1
vis[l[p]] = 1
p = l[p] - 1
if 3 * n % 2 == ans % 2: print("Petr")
else: print("Um_nik") | python | train | qsol | codeparrot/apps | all |
I found an interesting problem on https://leetcode.com/problems/largest-rectangle-in-histogram/:
Given n non-negative integers representing the histogram's bar height where the width of each bar is 1, find the area of largest rectangle in the histogram.
Above is a histogram where width of each bar is 1, given height ... | class Solution:
def largestRectangleArea(self, heights):
n = len(heights)
if n == 0:
return 0
left = [i for i in range(n)]
right = [i+1 for i in range(n)]
print(heights)
for i in range(1, n):
# indicates the next value to compare
... | python | train | abovesol | codeparrot/apps | all |
Solve in Python:
A triangle is called an equable triangle if its area equals its perimeter. Return `true`, if it is an equable triangle, else return `false`. You will be provided with the length of sides of the triangle. Happy Coding! | def equable_triangle(a,b,c):
return (a + b + c) * 16 == (a + b - c) * (b + c - a) * (c + a - b) | python | train | qsol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/1203/E:
There are $n$ boxers, the weight of the $i$-th boxer is $a_i$. Each of them can change the weight by no more than $1$ before the competition (the weight cannot become equal to zero, that is, it must remain positive). Weight is always an... | def main():
n = int(input())
arr = list(map(int,input().split()))
arr.sort()
nums = set()
for i in arr:
if i-1 > 0 and ((i-1) not in nums):
nums.add(i-1)
elif i not in nums:
nums.add(i)
elif (i+1) not in nums:
nums.add(i+1)
print(len(... | python | test | abovesol | codeparrot/apps | all |
Solve in Python:
Given an integer array nums, find the contiguous subarray within an array (containing at least one number) which has the largest product.
Example 1:
Input: [2,3,-2,4]
Output: 6
Explanation: [2,3] has the largest product 6.
Example 2:
Input: [-2,0,-1]
Output: 0
Explanation: The result cannot be 2... | class Solution:
def maxProduct(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
n = len(nums)
dp = [[nums[0], nums[0]] for _ in range(n)]
ans = nums[0]
for i in range(1, n):
temp = [dp[i-1][0] * nums[i], dp[i-1][1] * nums[i]... | python | train | qsol | codeparrot/apps | all |
Solve in Python:
You are given Name of chef's friend and using chef's new method of calculating value of string , chef have to find the value of all the names. Since chef is busy , he asked you to do the work from him .
The method is a function $f(x)$ as follows -
-
$f(x)$ = $1$ , if $x$ is a consonent
-
$f(x)$ = $0... | for _ in range(int(input().strip())):
s = list(input().strip())
n = len(s)
MOD = 1000000007
vow = ['a' , 'e' , 'i' , 'o' , 'u']
K = ""
for i in range(n):
if s[i] not in vow:
K = K + "1"
else:
K = K + "0"
co = int(K,2)
print(str(co%MOD)) | python | train | qsol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/610/C:
The semester is already ending, so Danil made an effort and decided to visit a lesson on harmony analysis to know how does the professor look like, at least. Danil was very bored on this lesson until the teacher gave the group a simple t... | k = int(input())
if (k == 0):
print('+')
return
answer = [['+', '+'], ['+', '*']]
length = 2
for i in range(k - 1):
new = []
for i in answer:
temp = []
for j in range(length):
if i[j] == '+':
temp += ['+', '+']
else:
temp += ['*',... | python | test | abovesol | codeparrot/apps | all |
I found an interesting problem on https://codeforces.com/problemset/problem/998/A:
There are quite a lot of ways to have fun with inflatable balloons. For example, you can fill them with water and see what happens.
Grigory and Andrew have the same opinion. So, once upon a time, they went to the shop and bought $n$ pac... | # python3
def readline(): return list(map(int, input().split()))
def main():
n, = readline()
a = tuple(readline())
if n == 1 or n == 2 and a[0] == a[1]:
print(-1)
else:
print(1)
print(a.index(min(a)) + 1)
main() | python | test | abovesol | codeparrot/apps | all |
I found an interesting problem on https://atcoder.jp/contests/abc122/tasks/abc122_d:
You are given an integer N. Find the number of strings of length N that satisfy the following conditions, modulo 10^9+7:
- The string does not contain characters other than A, C, G and T.
- The string does not contain AGC as a substr... | import numpy as np
N = int(input())
mod = 10**9+7
dp = np.zeros([N+1,4,4,4],dtype=int)
dp[0,-1,-1,-1] = 1
for i in range(N):
for c1 in range(4):
for c2 in range(4):
for c3 in range(4):
if not dp[i,c1,c2,c3]:continue
for a in range(4):
if c1 == 0 and c3 == 1 and a == 2:continue
... | python | test | abovesol | codeparrot/apps | all |
Solve in Python:
Ms. E.T. came from planet Hex. She has 8 fingers in each hand which makes her count in hexadecimal way. When she meets you, she tells you that she came from 7E light years from the planet Earth. You see she means that it is 126 light years far away and she is telling you the numbers in hexadecimal. Now... | # cook your dish here
try:
n=int(input())
for i in range(n):
a=input()
print(int(a, 16))
except EOFError as e:
pass | 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.