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.codewars.com/kata/5550d638a99ddb113e0000a2: This problem takes its name by arguably the most important event in the life of the ancient historian Josephus: according to his tale, he and his 40 soldiers were trapped in a cave by the Romans during a siege. Refusing to surren...
def josephus(itemlist, interval): length = len(itemlist) if interval == 1: return itemlist count = 1 disposal = [] #list which stores order in which items get deleted while len(disposal) != length: #loop runs unti; every item has been deleted index = 0 #gives an index. Useful ...
python
train
abovesol
codeparrot/apps
all
Solve in Python: This kata is the second part of a series: [Neighbourhood kata collection](https://www.codewars.com/collections/5b2f4db591c746349d0000ce). If this one is to easy you can try out the harder Katas.;) ___ The neighbourhood of a cell (in a matrix) are cells that are near to it. There are two popular types:...
def get_neighbourhood(typ, arr, coordinates): def isInside(x,y): return 0 <= x < len(arr) and 0 <= y < len(arr[0]) x,y = coordinates if not isInside(x,y): return [] neigh = ( [(dx, dy) for dx in range(-1,2) for dy in range(-1,2) if (dx,dy) != (0,0)] if typ == 'moore' els...
python
train
qsol
codeparrot/apps
all
Solve in Python: Write a comparator for a list of phonetic words for the letters of the [greek alphabet](https://en.wikipedia.org/wiki/Greek_alphabet). A comparator is: > *a custom comparison function of two arguments (iterable elements) which should return a negative, zero or positive number depending on whether the ...
greek_alphabet = ( 'alpha', 'beta', 'gamma', 'delta', 'epsilon', 'zeta', 'eta', 'theta', 'iota', 'kappa', 'lambda', 'mu', 'nu', 'xi', 'omicron', 'pi', 'rho', 'sigma', 'tau', 'upsilon', 'phi', 'chi', 'psi', 'omega') def greek_comparator(lhs, rhs): # the tuple greek_alphabet is defined in the nonloc...
python
train
qsol
codeparrot/apps
all
I found an interesting problem on https://atcoder.jp/contests/abc137/tasks/abc137_d: There are N one-off jobs available. If you take the i-th job and complete it, you will earn the reward of B_i after A_i days from the day you do it. You can take and complete at most one of these jobs in a day. However, you cannot reta...
import sys, math from functools import lru_cache import numpy as np import heapq from collections import defaultdict sys.setrecursionlimit(10**9) MOD = 10**9+7 def input(): return sys.stdin.readline()[:-1] def mi(): return list(map(int, input().split())) def ii(): return int(input()) def i2(n): tmp ...
python
test
abovesol
codeparrot/apps
all
Solve in Python: This is a simplified version of the task Toy Train. These two versions differ only in the constraints. Hacks for this version are disabled. Alice received a set of Toy Train™ from Bob. It consists of one train and a connected railway network of $n$ stations, enumerated from $1$ through $n$. The train ...
def __starting_point(): from sys import stdin n, m = list(map(int, stdin.readline().split())) c = {} for _ in range(m): a, b = list(map(int, stdin.readline().split())) if (a-1) not in c.keys(): c[a-1] = [] x = b-a + (n if b<a else 0) c[a-1].append(x) for k, l in c.items(): c[k] = min(l) + ((len(l)-1)...
python
test
qsol
codeparrot/apps
all
Solve in Python: You are given a sequence $a_1, a_2, \dots, a_n$, consisting of integers. You can apply the following operation to this sequence: choose some integer $x$ and move all elements equal to $x$ either to the beginning, or to the end of $a$. Note that you have to move all these elements in one direction in o...
import copy def DeleteRepetitionsIn(Array): AlreadyRead = {} index = 0 ConstantArray = copy.deepcopy(Array) for a in range(len(ConstantArray)): if Array[index] not in AlreadyRead: AlreadyRead[Array[index]] = "" index += 1 continue Array = Array[0:index...
python
train
qsol
codeparrot/apps
all
I found an interesting problem on https://www.codechef.com/problems/MINIKILL: Corruption is on the rise in the country of Freedonia, Gru's home. Gru wants to end this for good and for that he needs the help of his beloved minions. This corruption network can be represented in the form of a tree having N$N$ nodes and N−...
from sys import stdin,stdout input=stdin.readline n=int(input()) a=[[] for i in range(n)] for i in range(n-1): u,v=map(int,input().split()) a[u-1].append(v-1) a[v-1].append(u-1) b=[0]*n vis=[0]*n st=[(0,0)] vis[0]=1 pa=[0]*n while st: x,y=st.pop() b[x]=y for i in a[x]: i...
python
train
abovesol
codeparrot/apps
all
I found an interesting problem on https://www.codewars.com/kata/565f5825379664a26b00007c: ```if-not:julia,racket Write a function that returns the total surface area and volume of a box as an array: `[area, volume]` ``` ```if:julia Write a function that returns the total surface area and volume of a box as a tuple: `(a...
def get_size(w,h,d): volume=w*h*d total_surface_area= 2*(w*h+h*d+w*d) return [total_surface_area,volume]
python
train
abovesol
codeparrot/apps
all
I found an interesting problem on https://www.codewars.com/kata/5254ca2719453dcc0b00027d: In this kata you have to create all permutations of an input string and remove duplicates, if present. This means, you have to shuffle all letters from the input in all possible orders. Examples: ```python permutations('a'); # [...
import itertools def permutations(string): return list("".join(p) for p in set(itertools.permutations(string)))
python
train
abovesol
codeparrot/apps
all
I found an interesting problem on https://www.codewars.com/kata/583601518d3b9b8d3b0000c9: Your task in this Kata is to emulate text justify right in monospace font. You will be given a single-lined text and the expected justification width. The longest word will never be greater than this width. Here are the rules: -...
def align_right(text,width): k = text.split() out = '' last = [] for x in k: if len(x + out) <= width: out += x + ' ' else: last.append(out) out = x+' ' last.append(out) return '\n'.join(' ' * (width - len(x.rstrip())) + x.rstrip() fo...
python
train
abovesol
codeparrot/apps
all
I found an interesting problem on https://codeforces.com/problemset/problem/1185/A: Polycarp decided to relax on his weekend and visited to the performance of famous ropewalkers: Agafon, Boniface and Konrad. The rope is straight and infinite in both directions. At the beginning of the performance, Agafon, Boniface and...
a, b, c, d = list(map(int, input().split())) s = [a, b, c] s.sort() a, b, c = s print(max(0, a - b + d) + max(0, b - c + d))
python
test
abovesol
codeparrot/apps
all
Solve in Python: The math faculty of Berland State University has suffered the sudden drop in the math skills of enrolling students. This year the highest grade on the entrance math test was 8. Out of 100! Thus, the decision was made to make the test easier. Future students will be asked just a single question. They a...
CIRCLE = 1 RECTANGLE = 2 SQUARE = 3 def main(): n = int(input()) a = list(map(int, input().split())) answer = 0 for i in range(1, n): if a[i - 1] == CIRCLE: if a[i] == RECTANGLE: answer += 3 if i > 1 and a[i - 2] == SQUARE: answe...
python
test
qsol
codeparrot/apps
all
Solve in Python: Mislove had an array $a_1$, $a_2$, $\cdots$, $a_n$ of $n$ positive integers, but he has lost it. He only remembers the following facts about it: The number of different numbers in the array is not less than $l$ and is not greater than $r$; For each array's element $a_i$ either $a_i = 1$ or $a_i$ ...
n,l,r=map(int,input().split()) ans1,ans2=0,0 c=1 for i in range(n): if i>(n-l): c*=2 ans1+=c c=1 for i in range(n): ans2+=c if i<(r-1): c*=2 print(ans1,ans2)
python
test
qsol
codeparrot/apps
all
Solve in Python: Pasha loves his phone and also putting his hair up... But the hair is now irrelevant. Pasha has installed a new game to his phone. The goal of the game is following. There is a rectangular field consisting of n row with m pixels in each row. Initially, all the pixels are colored white. In one move, Pa...
__author__ = 'default' def TaskA(): #fl = open('TaskA.txt','r') n, m, k = list(map(int,input().split())) pole = [0]*n lose = False cmplt = True for i in range(n): pole[i] = [0]*m for i in range(k): rdl = list(map(int,input().split())) pole[rdl[0]-1][rdl[1]-1] = 1 ...
python
test
qsol
codeparrot/apps
all
Solve in Python: The only difference between easy and hard versions is constraints. Ivan plays a computer game that contains some microtransactions to make characters look cooler. Since Ivan wants his character to be really cool, he wants to use some of these microtransactions — and he won't start playing until he get...
import sys import copy DEBUG = False if DEBUG: inf = open("input.txt") else: inf = sys.stdin N, M = list(map(int, inf.readline().split(' '))) n_items = list(map(int, inf.readline().split(' '))) sales = [] for _ in range(M): sale = list(map(int, inf.readline().split(' '))) sales.append(sale) # sale_da...
python
test
qsol
codeparrot/apps
all
I found an interesting problem on https://codeforces.com/problemset/problem/743/A: Vladik is a competitive programmer. This year he is going to win the International Olympiad in Informatics. But it is not as easy as it sounds: the question Vladik face now is to find the cheapest way to get to the olympiad. Vladik know...
read = lambda: list(map(int, input().split())) n, a, b = read() s = ' ' + input() if s[a] == s[b]: print(0) return else: print(1)
python
test
abovesol
codeparrot/apps
all
I found an interesting problem on https://codeforces.com/problemset/problem/870/B: You are given an array a_1, a_2, ..., a_{n} consisting of n integers, and an integer k. You have to split the array into exactly k non-empty subsegments. You'll then compute the minimum integer on each subsegment, and take the maximum in...
n, k = list(map(int, input().split())) a = list(map(int, input().split())) if k == 1: print(min(a)) elif k == 2: b = [a[0]] * (n - 1) for i in range(1, n - 1): b[i] = min(b[i - 1], a[i]) c = [a[n - 1]] * (n - 1) for i in range(n - 3, -1, -1): c[i] = min(c[i + 1], a[i + 1]) ans = ...
python
test
abovesol
codeparrot/apps
all
Solve in Python: Shubham has a binary string $s$. A binary string is a string containing only characters "0" and "1". He can perform the following operation on the string any amount of times: Select an index of the string, and flip the character at that index. This means, if the character was "0", it becomes "1", an...
q = int(input()) for ii in range(q): s = input() n = len(s) wyn = 5298528589245892 wyn = min(wyn, s.count('0')) wyn = min(wyn, s.count('1')) #00001111 cyk = s.count('0') for i in range(n): if s[i] == '1': cyk +=1 else: cyk -= 1 wyn = min(wyn,cyk) cyk = s.count('1') for i in range(n): if s[i] == ...
python
test
qsol
codeparrot/apps
all
Solve in Python: =====Function Descriptions===== group() A group() expression returns one or more subgroups of the match. Code >>> import re >>> m = re.match(r'(\w+)@(\w+)\.(\w+)','username@hackerrank.com') >>> m.group(0) # The entire match 'username@hackerrank.com' >>> m.group(1) # The first parenthesiz...
#!/usr/bin/env python3 import re def __starting_point(): string = input() match = re.search(r'([a-zA-Z0-9])\1+', string) print((match.group(1) if match else -1)) __starting_point()
python
train
qsol
codeparrot/apps
all
I found an interesting problem on https://www.codechef.com/problems/CHEFZOT: Chef loves research! Now he is looking for subarray of maximal length with non-zero product. Chef has an array A with N elements: A1, A2, ..., AN. Subarray Aij of array A is elements from index i to index j: Ai, Ai+1, ..., Aj. Product of su...
n=int(input()) a=list(map(int,input().split())) c=m=0 for i in range(n): if a[i]!=0: c+=1 else: m=max(m,c) c=0 #print(m,c,a[i]) m=max(m,c) print(m)
python
test
abovesol
codeparrot/apps
all
Solve in Python: There is a country with $n$ citizens. The $i$-th of them initially has $a_{i}$ money. The government strictly controls the wealth of its citizens. Whenever a citizen makes a purchase or earns some money, they must send a receipt to the social services mentioning the amount of money they currently have....
R=lambda:map(int,input().split()) n=int(input()) a=*zip([1]*n,range(1,n+1),R()),*([*R()]for _ in[0]*int(input())) r=[-1]*n m=0 for t,p,*x in a[::-1]: if t>1:m=max(m,p) elif r[p-1]<0:r[p-1]=max(x[0],m) print(*r)
python
train
qsol
codeparrot/apps
all
I found an interesting problem on https://codeforces.com/problemset/problem/645/A: Bessie the cow and her best friend Elsie each received a sliding puzzle on Pi Day. Their puzzles consist of a 2 × 2 grid and three tiles labeled 'A', 'B', and 'C'. The three tiles sit on top of the grid, leaving one grid cell empty. To m...
a, b, c, d = input(), input(), input(), input() a = a + b[::-1] x = "X" for i in range(4): if a[i] == x: a = a[:i] + a[i + 1:] break c = c + d[::-1] for i in range(4): if c[i] == x: c = c[:i] + c[i + 1:] break flag = False for i in range(4): if a == c: flag = True ...
python
test
abovesol
codeparrot/apps
all
Solve in Python: Given are a sequence of N positive integers A_1, A_2, \ldots, A_N and another positive integer S. For a non-empty subset T of the set \{1, 2, \ldots , N \}, let us define f(T) as follows: - f(T) is the number of different non-empty subsets \{x_1, x_2, \ldots , x_k \} of T such that A_{x_1}+A_{x_2}+\...
#!python3 iim = lambda: list(map(int, input().rstrip().split())) def resolve(): N, S = iim() A = list(iim()) mod = 998244353 S1 = S + 1 dp = [0] * (S+1) dp[0] = pow(2, N, mod) inv = pow(2, mod-2, mod) for ai in A: for i in range(S, ai-1, -1): dp[i] = (dp[i] + dp[...
python
test
qsol
codeparrot/apps
all
I found an interesting problem on https://leetcode.com/problems/make-array-strictly-increasing/: Given two integer arrays arr1 and arr2, return the minimum number of operations (possibly zero) needed to make arr1 strictly increasing. In one operation, you can choose two indices 0 <= i < arr1.length and 0 <= j < arr2.le...
import bisect class Solution: def makeArrayIncreasing(self, arr1: List[int], arr2: List[int]) -> int: N = len(arr1) arr1 = [0] + arr1 # 表示前 i 个元素,执行了 k 次操作后,是有序的 dp = [[float('inf')] * (N + 1) for _ in range(N + 1)] dp[0][0] = -float('inf') arr2.sort() ...
python
test
abovesol
codeparrot/apps
all
Solve in Python: # Task Make a custom esolang interpreter for the language Stick. Stick is a simple, stack-based esoteric programming language with only 7 commands. # Commands * `^`: Pop the stack. * `!`: Add new element to stack with the value of 0. * `+`: Increment element. 255+1=0. * `-`: Decrement element. 0-1=...
def interpreter(tape): stack, output = [0], '' i, n = 0, len(tape) while i < n: cmd = tape[i] if cmd == '^': stack.pop() elif cmd == '!': stack.append(0) elif cmd == '+': stack[0] = 0 if stack[0] == 255 else stack[0] + 1 elif cmd ==...
python
train
qsol
codeparrot/apps
all
Solve in Python: =====Function Descriptions===== mean The mean tool computes the arithmetic mean along the specified axis. import numpy my_array = numpy.array([ [1, 2], [3, 4] ]) print numpy.mean(my_array, axis = 0) #Output : [ 2. 3.] print numpy.mean(my_array, axis = 1) #Output : [ 1.5 3.5] print n...
import numpy as np n, m = [int(x) for x in input().strip().split()] array = np.array([[int(x) for x in input().strip().split()] for _ in range(n)], dtype = float) print(np.mean(array, axis = 1)) print(np.var(array, axis = 0)) print(np.std(array))
python
train
qsol
codeparrot/apps
all
Solve in Python: You are given an array $a$ consisting of $n$ integer numbers. Let instability of the array be the following value: $\max\limits_{i = 1}^{n} a_i - \min\limits_{i = 1}^{n} a_i$. You have to remove exactly one element from this array to minimize instability of the resulting $(n-1)$-elements array. Your ...
def go(): n = int(input()) a = [int(i) for i in input().split(' ')] if n == 2: return 0 m1 = max(a) a.remove(m1) m2 = max(a) mi1 = min(a) a.remove(mi1) mi2 = min(a) if m2 - mi1 < m1 - mi2: return m2 - mi1 return m1 - mi2 print(go())
python
test
qsol
codeparrot/apps
all
Solve in Python: Each student eagerly awaits the day he would pass the exams successfully. Thus, Vasya was ready to celebrate, but, alas, he didn't pass it. However, many of Vasya's fellow students from the same group were more successful and celebrated after the exam. Some of them celebrated in the BugDonalds restaur...
A, B, C, N = [int(i) for i in input().split()] summ = A - C + B if summ >= N or (C > min(A, B)): print(-1) else: print(N - summ)
python
test
qsol
codeparrot/apps
all
Solve in Python: This is a harder version of the problem. In this version, $n \le 50\,000$. There are $n$ distinct points in three-dimensional space numbered from $1$ to $n$. The $i$-th point has coordinates $(x_i, y_i, z_i)$. The number of points $n$ is even. You'd like to remove all $n$ points using a sequence of $...
n = int(input()) points = [] for i in range(n): points.append(list(map(int, input().split()))) points[i].append(i+1) points.sort() rem = [] i = 0 while i < len(points): if i < len(points)-1 and points[i][:2] == points[i+1][:2]: print(points[i][3],points[i+1][3]) i+=2 else: rem...
python
test
qsol
codeparrot/apps
all
I found an interesting problem on https://atcoder.jp/contests/abc095/tasks/abc095_a: In "Takahashi-ya", a ramen restaurant, a bowl of ramen costs 700 yen (the currency of Japan), plus 100 yen for each kind of topping (boiled egg, sliced pork, green onions). A customer ordered a bowl of ramen and told which toppings to ...
order_str = input() additional_price = order_str.count('o') * 100 total_price = 700 + additional_price print(total_price)
python
test
abovesol
codeparrot/apps
all
Solve in Python: The number 81 has a special property, a certain power of the sum of its digits is equal to 81 (nine squared). Eighty one (81), is the first number in having this property (not considering numbers of one digit). The next one, is 512. Let's see both cases with the details 8 + 1 = 9 and 9^(2) = 81 512 ...
def dig_sum(n): return sum(map(int, str(n))) terms = [] for b in range(2, 400): for p in range(2, 50): if dig_sum(b ** p) == b: terms.append(b ** p) terms.sort() def power_sumDigTerm(n): return terms[n - 1]
python
train
qsol
codeparrot/apps
all
I found an interesting problem on https://codeforces.com/problemset/problem/1303/E: You are given a string $s$. You can build new string $p$ from $s$ using the following operation no more than two times: choose any subsequence $s_{i_1}, s_{i_2}, \dots, s_{i_k}$ where $1 \le i_1 < i_2 < \dots < i_k \le |s|$; erase th...
def main(): T = int(input().strip()) for _ in range(T): s = input().strip() t = input().strip() n = len(s) find = [[n] * 26 for _ in range(n + 2)] for i in range(n - 1, -1, -1): find[i][:] = find[i + 1] find[i][ord(s[i]) - ord("a")] = i ...
python
test
abovesol
codeparrot/apps
all
I found an interesting problem on https://atcoder.jp/contests/abc128/tasks/abc128_f: There is an infinitely large pond, which we consider as a number line. In this pond, there are N lotuses floating at coordinates 0, 1, 2, ..., N-2 and N-1. On the lotus at coordinate i, an integer s_i is written. You are standing on th...
from collections import defaultdict N = int( input()) S = list( map( int, input().split())) ans = 0 for c in range(1,N): now = 0 for t in range(c ,N, c): if ((N-1-t)%c == 0 and N-1-t <= t) or N-1-t - c <=0: break now += S[t] + S[N-1-t] if now > ans: ans = now pri...
python
test
abovesol
codeparrot/apps
all
I found an interesting problem on https://www.codewars.com/kata/523d2e964680d1f749000135: ```if-not:ruby Create a function, that accepts an arbitrary number of arrays and returns a single array generated by alternately appending elements from the passed in arguments. If one of them is shorter than the others, the resul...
from itertools import zip_longest def interleave(*args): return [y for x in zip_longest(*args) for y in x]
python
train
abovesol
codeparrot/apps
all
I found an interesting problem on https://codeforces.com/problemset/problem/1294/F: You are given an unweighted tree with $n$ vertices. Recall that a tree is a connected undirected graph without cycles. Your task is to choose three distinct vertices $a, b, c$ on this tree such that the number of edges which belong to ...
import sys from collections import deque n = int(input()) adj = [[] for _ in range(n)] for u, v in (list(map(int, l.split())) for l in sys.stdin): adj[u-1].append(v-1) adj[v-1].append(u-1) inf = 10**9 def rec(s): prev = [-1]*n prev[s] = inf dq = deque([s]) last = s while dq: v = ...
python
test
abovesol
codeparrot/apps
all
Solve in Python: You will be given a vector of strings. You must sort it alphabetically (case-sensitive, and based on the ASCII values of the chars) and then return the first value. The returned value must be a string, and have `"***"` between each of its letters. You should not remove or add elements from/to the arr...
def two_sort(array): array = sorted(array) emptystring = '' for eachletter in array[0]: emptystring = emptystring + eachletter + ' ' emptystring = emptystring.rstrip() emptystring = emptystring.split() emptystring = '***'.join(emptystring) return emptystring
python
train
qsol
codeparrot/apps
all
I found an interesting problem on https://atcoder.jp/contests/abc105/tasks/abc105_d: There are N boxes arranged in a row from left to right. The i-th box from the left contains A_i candies. You will take out the candies from some consecutive boxes and distribute them evenly to M children. Such being the case, find the ...
N,M = list(map(int,input().split())) A = list(map(int,input().split())) B = [0 for i in range(N+1)] for i in range(N): B[i+1] += B[i] + A[i] B[i+1] %= M from collections import Counter counterB = Counter(B) ans = 0 for v in list(counterB.values()): ans += v*(v-1)//2 print(ans)
python
test
abovesol
codeparrot/apps
all
Solve in Python: The last stage of Football World Cup is played using the play-off system. There are n teams left in this stage, they are enumerated from 1 to n. Several rounds are held, in each round the remaining teams are sorted in the order of their ids, then the first in this order plays with the second, the thir...
t = list(map(int, input().split())) n = t[0] a = t[1] b = t[2] ans = 0 while a != b: n //= 2 a = (a + 1) // 2 b = (b + 1) // 2 ans += 1 if n == 1: print('Final!') else: print(ans)
python
test
qsol
codeparrot/apps
all
I found an interesting problem on https://leetcode.com/problems/remove-max-number-of-edges-to-keep-graph-fully-traversable/: Alice and Bob have an undirected graph of n nodes and 3 types of edges: Type 1: Can be traversed by Alice only. Type 2: Can be traversed by Bob only. Type 3: Can by traversed by both Alice and B...
from copy import deepcopy class DSU: def __init__(self, n): self.dsu = [i for i in range(n+1)] def find(self, x): if x == self.dsu[x]: return x self.dsu[x] = self.find(self.dsu[x]) return self.dsu[x] def union(self, x, y): xr = self.find(x) ...
python
train
abovesol
codeparrot/apps
all
Solve in Python: Chef Loves to listen to remix songs, but currently he had already finished the entire playlist of remix songs. As Chef is smart, so he thought let's make my own remix songs of the original songs. Chef is not having much knowledge of making remix songs, so he came up with the simple technique in which h...
S=list(input().split()) min=S[0] ml=len(S[0]) ans=[] for i in S: if len(i)<ml: ml=len(i) min=i for j in range(len(S)): print(min,end=" ") print(S[j],end=" ") print(min)
python
train
qsol
codeparrot/apps
all
I found an interesting problem on https://www.codechef.com/problems/HIT: Coach Khaled is a swag teacher in HIT (Hag Institute of Technology). However, he has some obsession problems. Recently, coach Khaled was teaching a course in building 8G networks using TV antennas and programming them with assembly. There are $N$ ...
for T in range(int(input())): N = int(input()) A = sorted(list(map(int,input().split()))) a = N // 4 b = a + a c = b + a if A[a] == A[a-1] or A[b] == A[b-1] or A[c] == A[c-1]: print(-1) else: print(A[a],A[b],A[c])
python
train
abovesol
codeparrot/apps
all
I found an interesting problem on https://leetcode.com/problems/scramble-string/: Given a string s1, we may represent it as a binary tree by partitioning it to two non-empty substrings recursively. Below is one possible representation of s1 = "great": great / \ gr eat / \ / \ g r e at ...
class Solution: def isScramble(self, s1, s2): if sorted(s1) != sorted(s2): return False if len(s1) < 4 or s1 == s2: return True f = self.isScramble for i in range(1, len(s1)): if f(s1[:i], s2[:i]) and f(s1[i:], s2[i:]) or f(s1[:i], s2[-i:]) and f(s1[i:], s2[:len(s1)...
python
train
abovesol
codeparrot/apps
all
Solve in Python: Doubly linked list is one of the fundamental data structures. A doubly linked list is a sequence of elements, each containing information about the previous and the next elements of the list. In this problem all lists have linear structure. I.e. each element except the first has exactly one previous el...
k, n = 0, int(input()) t = [list(map(int, input().split())) for j in range(n)] for m, (l, r) in enumerate(t, 1): if not l: if k: t[k - 1][1], t[m - 1][0] = m, k k = m while r: k, r = r, t[r - 1][1] for l, r in t: print(l, r)
python
train
qsol
codeparrot/apps
all
Solve in Python: Given a number s in their binary representation. Return the number of steps to reduce it to 1 under the following rules: If the current number is even, you have to divide it by 2. If the current number is odd, you have to add 1 to it. It's guaranteed that you can always reach to one for all testc...
class Solution: def numSteps(self, s: str) -> int: i, mid_zero = 0 , 0 for j in range(1, len(s)): if s[j] == '1': mid_zero += j -i - 1 i = j if i == 0: return len(s)-1 return mid_zero + 1 + len(s)
python
train
qsol
codeparrot/apps
all
I found an interesting problem on https://www.codechef.com/problems/UWCOI20A: Well known investigative reporter Kim "Sherlock'' Bumjun needs your help! Today, his mission is to sabotage the operations of the evil JSA. If the JSA is allowed to succeed, they will use the combined power of the WQS binary search and the UF...
for t in range(int(input())): n=int(input()) x=int(input()) for i in range(n-1): y=int(input()) if y>x: x=y print(x)
python
train
abovesol
codeparrot/apps
all
I found an interesting problem on https://www.codechef.com/problems/CNTFAIL: It's year 2018 and it's Christmas time! Before going for vacations, students of Hogwarts School of Witchcraft and Wizardry had their end semester exams. $N$ students attended the semester exam. Once the exam was over, their results were displa...
t = int(input()) for i in range(t): number_of_students = int(input()) list_of_numbers = list(map(int, input().split(" "))) max_number = max(list_of_numbers) min_number = min(list_of_numbers) #max_number must smaller becuase if it is equal, it means one student #saw himself which can't happen #(max_number - min_n...
python
train
abovesol
codeparrot/apps
all
Solve in Python: Given an integer, take the (mean) average of each pair of consecutive digits. Repeat this process until you have a single integer, then return that integer. e.g. Note: if the average of two digits is not an integer, round the result **up** (e.g. the average of 8 and 9 will be 9) ## Examples ``` digi...
import math def digits_average(input): m = str(input) for i in range(len(str(input))-1): m = ''.join(str(math.ceil(int(m[i])/2 + int(m[i+1])/2)) for i in range(len(m) - 1)) return int(m)
python
train
qsol
codeparrot/apps
all
I found an interesting problem on https://codeforces.com/problemset/problem/977/D: Polycarp likes to play with numbers. He takes some integer number $x$, writes it down on the board, and then performs with it $n - 1$ operations of the two kinds: divide the number $x$ by $3$ ($x$ must be divisible by $3$); multiply t...
# Project name: CF-479-D n = int(input()) a = list(map(int, input().split())) def func(x): b = list(a) r=[] for i in range(n): if x%3==0 and x//3 in b: x//=3 b.remove(x) r+=[x] if x*2 in b: x*=2 b.remove(x) r+=[x] ...
python
test
abovesol
codeparrot/apps
all
I found an interesting problem on https://www.codewars.com/kata/589b137753a9a4ab5700009a: Hello everyone. I have a simple challenge for you today. In mathematics, the formula for finding the sum to infinity of a geometric sequence is: **ONLY IF** `-1 < r < 1` where: * `a` is the first term of the sequence * `r` ...
def sum_to_infinity(sequence): # Good Luck! sum = 0 print(sequence) if(len(sequence)>1): r = sequence[1]/sequence[0] print(r) if r<=-1 or r>=1: return 'No Solutions' sum = round(sequence[0]/(1-r),3) return sum return sequence[0]
python
train
abovesol
codeparrot/apps
all
Solve in Python: The chef won a duet singing award at Techsurge & Mridang 2012. From that time he is obsessed with the number 2. He just started calculating the powers of two. And adding the digits of the results. But he got puzzled after a few calculations. So gave you the job to generate the solutions to 2^n and fi...
from sys import stdin lines = stdin.readlines()[1:] for line in lines: str_2n = str(2 ** int(line)) sum = 0 for i in str_2n: sum += int(i) print(sum)
python
train
qsol
codeparrot/apps
all
Solve in Python: Learning to code around your full time job is taking over your life. You realise that in order to make significant steps quickly, it would help to go to a coding bootcamp in London. Problem is, many of them cost a fortune, and those that don't still involve a significant amount of time off work - who ...
def sabb(s, value, happiness): return 'Sabbatical! Boom!' if sum(1 for x in s if x.lower() in 'sabbatical') + value + happiness > 22 else 'Back to your desk, boy.'
python
train
qsol
codeparrot/apps
all
Solve in Python: This year in Equestria was a year of plenty, so Applejack has decided to build some new apple storages. According to the advice of the farm designers, she chose to build two storages with non-zero area: one in the shape of a square and another one in the shape of a rectangle (which possibly can be a sq...
mod=998244353 n=int(input()) a=list(map(int,input().split())) d=dict() two=0 four=0 for i in a: if i in d: d[i]+=1 else: d[i]=1 for i in d: two+=d[i]//2 four+=d[i]//4 m=int(input()) for i in range (m): s=input().split() if s[0]=='+': l=int(s[1]) if l in d: ...
python
test
qsol
codeparrot/apps
all
Solve in Python: Roman and Denis are on the trip to the programming competition. Since the trip was long, they soon got bored, and hence decided to came up with something. Roman invented a pizza's recipe, while Denis invented a string multiplication. According to Denis, the result of multiplication (product) of strings...
from math import * import sys def minp(): return sys.stdin.readline().strip() def mint(): return int(minp()) def mints(): return list(map(int, minp().split())) n = mint() a = [0]*256 b = [0]*256 for k in range(0,n): #print(a[ord('a'):ord('z')+1]) for i in range(ord('a'),ord('z')+1): b[i] = min(a[i],1) i = 0...
python
test
qsol
codeparrot/apps
all
Solve in Python: Little Petya is learning to play chess. He has already learned how to move a king, a rook and a bishop. Let us remind you the rules of moving chess pieces. A chessboard is 64 square fields organized into an 8 × 8 table. A field is represented by a pair of integers (r, c) — the number of the row and the...
from math import fabs a=[int(i)for i in input().split()] if(a[0]==a[2])|(a[1]==a[3]):print(1,end=' ') else:print(2,end=' ') b,c=fabs(a[2]-a[0]),fabs(a[3]-a[1]) if b%2!=c%2:print(0,end=' ') elif b==c:print(1,end=' ') else:print(2,end=' ') print(int(max(fabs(a[2]-a[0]),fabs(a[3]-a[1]))))
python
test
qsol
codeparrot/apps
all
I found an interesting problem on https://codeforces.com/problemset/problem/687/C: Pari wants to buy an expensive chocolate from Arya. She has n coins, the value of the i-th coin is c_{i}. The price of the chocolate is k, so Pari will take a subset of her coins with sum equal to k and give it to Arya. Looking at her c...
n, k = list(map(int, input().split())) cs = list(map(int, input().split())) # table[c][s] has bit ss set if can make subset s and sub-subset ss # using only the first c coins. # We only ever need to know table[c-1] to compute table[c]. table = [[0 for _ in range(k+1)] for _ in range(2)] # Can always make subset 0 and...
python
test
abovesol
codeparrot/apps
all
Solve in Python: Recently, you bought a brand new smart lamp with programming features. At first, you set up a schedule to the lamp. Every day it will turn power on at moment $0$ and turn power off at moment $M$. Moreover, the lamp allows you to set a program of switching its state (states are "lights on" and "lights o...
def main(): n, M = [int(i) for i in input().split(' ')] a = [0] + [int(i) for i in input().split(' ')] + [M] n = n + 2 incr_sum = [] s = 0 for i in range(n): if i % 2 == 1: s += a[i] - a[i-1] incr_sum.append(s) max_sum = s for i in range(n-1): if a[...
python
test
qsol
codeparrot/apps
all
I found an interesting problem on https://www.codechef.com/problems/TOURISTS: The grand kingdom of Mancunia is famous for its tourist attractions and visitors flock to it throughout the year. King Mancunian is the benevolent ruler of the prosperous country whose main source of revenue is, of course, tourism. The count...
# cook your dish here import sys from collections import defaultdict class Graph(object): """docstring for Graph""" def __init__(self, vertices): self.vertices = vertices self.graph = defaultdict(list) def add_edge(self,a,b): self.graph[a].append(b) self.graph[b].append(a) def eulerPath(self): g = self...
python
test
abovesol
codeparrot/apps
all
I found an interesting problem on https://codeforces.com/problemset/problem/892/B: Hands that shed innocent blood! There are n guilty people in a line, the i-th of them holds a claw with length L_{i}. The bell rings and every person kills some of people in front of him. All people kill others at the same time. Namely,...
n = int(input()) l = [int(x) for x in input().split(" ")] s = [1 for i in range(n)] p = n-1 q = n-1 while p>0: while q>p-l[p] and q>0: q -= 1 s[q] = 0 p-=1 q = min(p,q) print(sum(s))
python
test
abovesol
codeparrot/apps
all
I found an interesting problem on https://atcoder.jp/contests/abc045/tasks/arc061_a: You are given a string S consisting of digits between 1 and 9, inclusive. You can insert the letter + into some of the positions (possibly none) between two letters in this string. Here, + must not occur consecutively after insertion. ...
s = input() len_s = len(s) total = int(s) eval_s = "" insert_list = [] for i in range(1, 2 ** (len_s - 1)): # print(i) for j in range(len_s): eval_s += s[j] if ((i >> j) & 1): # print(i, j) eval_s += "+" # print(eval_s) total += eval(eval_s) eval_s = "" print(total)
python
test
abovesol
codeparrot/apps
all
I found an interesting problem on https://codeforces.com/problemset/problem/1082/C: A multi-subject competition is coming! The competition has $m$ different subjects participants can choose from. That's why Alex (the coach) should form a competition delegation among his students. He has $n$ candidates. For the $i$-th...
n, m = list(map(int, input().split())) inp = tuple(([] for _ in range(m))) for __ in range(n): s, r = list(map(int, input().split())) inp[s - 1].append(r) for rs in inp: rs.sort(reverse=True) res = 0 inp1 = list(map(iter, inp)) curs = [0] * m for ___ in range(n): cur = 0 i = 0 while i < m: try: curs[i] += ne...
python
test
abovesol
codeparrot/apps
all
Solve in Python: In recreational mathematics, a [Keith number](https://en.wikipedia.org/wiki/Keith_number) or repfigit number (short for repetitive Fibonacci-like digit) is a number in the following integer sequence: `14, 19, 28, 47, 61, 75, 197, 742, 1104, 1537, 2208, 2580, 3684, 4788, 7385, 7647, 7909, ...` (sequenc...
def is_keith_number(n): if n <= 10: return False c, k_lst, k_num = 0, list(str(n)), n while k_num <= n: k_num = sum([int(x) for x in k_lst]) c += 1 if k_num == n: return c k_lst.append(k_num) k_lst.pop(0) return False
python
train
qsol
codeparrot/apps
all
Solve in Python: # Task "AL-AHLY" and "Zamalek" are the best teams in Egypt, but "AL-AHLY" always wins the matches between them. "Zamalek" managers want to know what is the best match they've played so far. The best match is the match they lost with the minimum goal difference. If there is more than one match with ...
from collections import namedtuple def best_match(goals1, goals2): Match = namedtuple('Match', ['diff', 'scored', 'index']) temp = [Match(xy[0]-xy[1], xy[1], idx) for idx, xy in enumerate(zip(goals1, goals2))] best_diff = min([match.diff for match in temp]) temp = [match for match in temp if match.dif...
python
train
qsol
codeparrot/apps
all
Solve in Python: Student Valera is an undergraduate student at the University. His end of term exams are approaching and he is to pass exactly n exams. Valera is a smart guy, so he will be able to pass any exam he takes on his first try. Besides, he can take several exams on one day, and in any order. According to the...
import collections Exam = collections.namedtuple("Exam", ['a', 'b']) n = int(input()) exams = [ ] for i in range(n): exams.append(Exam(*list(map(int, input().split())))) exams.sort() today = 0 for e in exams: today = e.b if e.b >= today else e.a print(today)
python
test
qsol
codeparrot/apps
all
Solve in Python: 3R2 - Standby for Action Our dear Cafe's owner, JOE Miller, will soon take part in a new game TV-show "1 vs. $n$"! The game goes in rounds, where in each round the host asks JOE and his opponents a common question. All participants failing to answer are eliminated. The show ends when only JOE remains...
n = int(input()) s = 0 for i in range(1, n + 1): s += 1/i print(s)
python
test
qsol
codeparrot/apps
all
I found an interesting problem on https://www.codewars.com/kata/58069e4cf3c13ef3a6000168: Impliment the reverse function, which takes in input n and reverses it. For instance, `reverse(123)` should return `321`. You should do this without converting the inputted number into a string. I tried it in Python, but could no...
def reverse(n): m = 0 while n > 0: n, m = n // 10, m * 10 + n % 10 return m
python
train
abovesol
codeparrot/apps
all
Solve in Python: An isogram is a word that has no repeating letters, consecutive or non-consecutive. Implement a function that determines whether a string that contains only letters is an isogram. Assume the empty string is an isogram. Ignore letter case. ```python is_isogram("Dermatoglyphics" ) == true is_isogram("ab...
def is_isogram(string): string = string.lower() for letter in string: if string.count(letter) > 1: return False return True
python
train
qsol
codeparrot/apps
all
Solve in Python: The sum of divisors of `6` is `12` and the sum of divisors of `28` is `56`. You will notice that `12/6 = 2` and `56/28 = 2`. We shall say that `(6,28)` is a pair with a ratio of `2`. Similarly, `(30,140)` is also a pair but with a ratio of `2.4`. These ratios are simply decimal representations of frac...
from fractions import Fraction as F cache = {} def divisors(n): result = cache.get(n) if result is not None: return result if n < 2: return [1] if n == 1 else [] result = set([1, n]) for i in range(2, n // 2): if n % i == 0: result.add(i) result.add(n...
python
train
qsol
codeparrot/apps
all
Solve in Python: Given an array of integers A, find the sum of min(B), where B ranges over every (contiguous) subarray of A. Since the answer may be large, return the answer modulo 10^9 + 7.   Example 1: Input: [3,1,2,4] Output: 17 Explanation: Subarrays are [3], [1], [2], [4], [3,1], [1,2], [2,4], [3,1,2], [1,2,4], [3...
class Solution: def sumSubarrayMins(self, A: List[int]) -> int: n = len(A) left = [0] * n right = [0] * n s1 = [] s2 = [] mod = 10 ** 9 + 7 for i in range(n): cnt = 1 while s1 and s1[-1][0] > A[i]: cnt += s1.pop()[1] ...
python
train
qsol
codeparrot/apps
all
Solve in Python: After making bad dives into swimming pools, Wilbur wants to build a swimming pool in the shape of a rectangle in his backyard. He has set up coordinate axes, and he wants the sides of the rectangle to be parallel to them. Of course, the area of the rectangle must be positive. Wilbur had all four vertic...
n = int(input()) lst = [] for i in range(n): a, b = list(map(int, input().split())) lst.append([a, b]) if n == 1: print(-1) elif n == 2 and lst[0][0] != lst[1][0] and lst[0][1] != lst[1][1]: print(abs(lst[0][0] - lst[1][0]) * abs(lst[0][1] - lst[1][1])) elif n == 2: print(-1) elif n == 3 or n =...
python
test
qsol
codeparrot/apps
all
I found an interesting problem on https://www.codewars.com/kata/55d2aee99f30dbbf8b000001: A new school year is approaching, which also means students will be taking tests. The tests in this kata are to be graded in different ways. A certain number of points will be given for each correct answer and a certain number o...
#returns test score def score_test(tests: list, right: int, omit: int, wrong: int) -> int: right_count = tests.count(0) omit_count = tests.count(1) wrong_count = tests.count(2) return right_count * right + omit_count * omit - wrong_count * wrong
python
train
abovesol
codeparrot/apps
all
I found an interesting problem on https://www.codechef.com/CCWC2018/problems/BONAPP: Tejas has invited the Clash Team for a Dinner Party. He places V empty plates (numbered from 1 to V inclusive) in a straight line on a table. He has prepared 2 kinds of Delicious Dishes named dish A and dish B. He has exactly V servin...
t=int(input()) while(t>0): v,w=list(map(int,input().split())) if(w<v): print(w+1) else: print(v+1) t=t-1
python
train
abovesol
codeparrot/apps
all
I found an interesting problem on https://codeforces.com/problemset/problem/448/C: Bizon the Champion isn't just attentive, he also is very hardworking. Bizon the Champion decided to paint his old fence his favorite color, orange. The fence is represented as n vertical planks, put in a row. Adjacent planks have no gap...
import sys oo=1000000000000 ar=[] def solve(l, r, val): if(r<l): return 0 indx=l+ar[l:r+1].index(min(ar[l:r+1])) tot=r-l+1 cur=ar[indx]-val+solve(l, indx-1, ar[indx])+solve(indx+1, r, ar[indx]) return min(tot, cur) sys.setrecursionlimit(10000) n=int(input()) ar=list(map(int, input().split())) print(solve(0, n-1, 0...
python
test
abovesol
codeparrot/apps
all
Solve in Python: You are given two sequences $a_1, a_2, \dots, a_n$ and $b_1, b_2, \dots, b_n$. Each element of both sequences is either $0$, $1$ or $2$. The number of elements $0$, $1$, $2$ in the sequence $a$ is $x_1$, $y_1$, $z_1$ respectively, and the number of elements $0$, $1$, $2$ in the sequence $b$ is $x_2$, $...
def main(): x1, y1, z1 = [int(s) for s in input().split()] x2, y2, z2 = [int(s) for s in input().split()] plus = min(z1, y2) remain = z1 - plus minus = max(z2 - remain - x1, 0) return (plus - minus) * 2 tests = int(input()) for _ in range(tests): print(main())
python
test
qsol
codeparrot/apps
all
I found an interesting problem on https://www.codewars.com/kata/58311536e77f7d08de000085: Consider having a cow that gives a child every year from her fourth year of life on and all her subsequent children do the same. After n years how many cows will you have? Return null if n is not an integer. Note: Assume all the...
def count_cows(n): if not isinstance(n, int): return None cows = [1] old_cows = 0 for _ in range(n): cows = [old_cows] + cows if len(cows) >= 3: old_cows += cows.pop() return sum(cows) + old_cows
python
train
abovesol
codeparrot/apps
all
Solve in Python: According to ISO 8601, the first calendar week (1) starts with the week containing the first thursday in january. Every year contains of 52 (53 for leap years) calendar weeks. **Your task is** to calculate the calendar week (1-53) from a given date. For example, the calendar week for the date `2019-01...
from datetime import datetime def get_calendar_week(date): return datetime.strptime(date, '%Y-%m-%d').isocalendar()[1]
python
train
qsol
codeparrot/apps
all
I found an interesting problem on https://www.codechef.com/ENAU2020/problems/ECAUG202: One day, Delta, the dog, got very angry. He has $N$ items with different values, and he decided to destroy a few of them. However, Delta loves his hooman as well. So he only destroyed those items whose Least Significant Bit in binary...
def bit(x): s=0 for i in range(len(x)): p=bool((x[i] & (1 << (0) ))) if(p==False): s=s+x[i] return s def __starting_point(): n=int(input()) for i in range(n): a=int(input()) x=list(map(int,input().split())) print(bit(x)) __starting_point()
python
train
abovesol
codeparrot/apps
all
I found an interesting problem on https://codeforces.com/problemset/problem/1037/C: You are given two binary strings $a$ and $b$ of the same length. You can perform the following two operations on the string $a$: Swap any two bits at indices $i$ and $j$ respectively ($1 \le i, j \le n$), the cost of this operation i...
import sys input = sys.stdin.readline n = int(input()) a = input() b = input() s = 0 i = 0 while i != len(a): if a[i] != b[i]: if a[i + 1] != b[i + 1] and a[i] != a[i + 1]: s += 1 i += 2 else: s += 1 i += 1 else: i += 1 print(s)
python
train
abovesol
codeparrot/apps
all
Solve in Python: Vanya has a scales for weighing loads and weights of masses w^0, w^1, w^2, ..., w^100 grams where w is some integer not less than 2 (exactly one weight of each nominal value). Vanya wonders whether he can weight an item with mass m using the given weights, if the weights can be put on both pans of the ...
w, m = list(map(int, input().split(' '))) f = 0 if (w == 2): print("YES") else: st = 1 while (f == 0): if (m % (st * w) != 0): if ((m - st) % (st * w) == 0): m -= st else: if ((m + st) % (st * w) == 0): m += st ...
python
test
qsol
codeparrot/apps
all
I found an interesting problem on https://www.codewars.com/kata/56b861671d36bb0aa8000819: Your task is to ___Reverse and Combine Words___. It's not too difficult, but there are some things you have to consider... ### So what to do? Input: String containing different "words" separated by spaces ``` 1. More than one ...
def reverse_and_combine_text(text): words = text.split() while len(words) > 1: words = [''.join(w[::-1] for w in words[i:i+2]) for i in range(0, len(words), 2)] return ''.join(words)
python
train
abovesol
codeparrot/apps
all
I found an interesting problem on https://codeforces.com/problemset/problem/761/A: On her way to programming school tiger Dasha faced her first test — a huge staircase! [Image] The steps were numbered from one to infinity. As we know, tigers are very fond of all striped things, it is possible that it has something to...
a, b = map(int, input().split()) if abs(a - b) > 1 or a == b == 0: print("NO") else: print("YES")
python
test
abovesol
codeparrot/apps
all
I found an interesting problem on https://www.codewars.com/kata/58397ee871df657929000209: Laura really hates people using acronyms in her office and wants to force her colleagues to remove all acronyms before emailing her. She wants you to build a system that will edit out all known acronyms or else will notify the sen...
def acronym_buster(message): acronyms = { 'CTA': 'call to action', 'EOD': 'the end of the day', 'IAM': 'in a meeting', 'KPI': 'key performance indicators', 'NRN': 'no reply necessary', 'OOO': 'out of office', 'SWOT': 'strengths, weaknesses, opportunities and t...
python
train
abovesol
codeparrot/apps
all
Solve in Python: Igor is a post-graduate student of chemistry faculty in Berland State University (BerSU). He needs to conduct a complicated experiment to write his thesis, but laboratory of BerSU doesn't contain all the materials required for this experiment. Fortunately, chemical laws allow material transformations ...
import sys # @profile def main(): f = sys.stdin # f = open('input.txt', 'r') # fo = open('log.txt', 'w') n = int(f.readline()) # b = [] # for i in range(n): # b.append() b = list(map(int, f.readline().strip().split(' '))) a = list(map(int, f.readline().strip().split(' '))) # ...
python
test
qsol
codeparrot/apps
all
I found an interesting problem on https://www.codewars.com/kata/5bd00c99dbc73908bb00057a: In this kata you will be given a random string of letters and tasked with returning them as a string of comma-separated sequences sorted alphabetically, with each sequence starting with an uppercase character followed by `n-1` low...
def alpha_seq(string): return ','.join(a * (ord(a) - 96) for a in sorted(string.lower())).title()
python
train
abovesol
codeparrot/apps
all
I found an interesting problem on https://codeforces.com/problemset/problem/1076/F: Vova has taken his summer practice this year and now he should write a report on how it went. Vova has already drawn all the tables and wrote down all the formulas. Moreover, he has already decided that the report will consist of exact...
def max(a, b): if a > b: return a else: return b n, k = map(int, input().split()) x = [int(t) for t in input().split()] y = [int(t) for t in input().split()] f, s = 0, 0 for i in range(n): f = max(0, x[i] + f - k * y[i]) s = max(0, y[i] + s - k * x[i]) if f > k or s > k: print('NO') re...
python
test
abovesol
codeparrot/apps
all
I found an interesting problem on https://atcoder.jp/contests/abc166/tasks/abc166_c: There are N observatories in AtCoder Hill, called Obs. 1, Obs. 2, ..., Obs. N. The elevation of Obs. i is H_i. There are also M roads, each connecting two different observatories. Road j connects Obs. A_j and Obs. B_j. Obs. i is said t...
def main(): n, m = list(map(int, input().split())) h = list(map(int, input().split())) hf = [0] * n for i in range(m): a, b = list(map(int, input().split())) if h[a-1] > h[b-1]: hf[b-1] = 1 elif h[a-1] == h[b-1]: hf[a-1] = 1 hf[b-1] = 1 ...
python
test
abovesol
codeparrot/apps
all
I found an interesting problem on https://leetcode.com/problems/maximum-sum-obtained-of-any-permutation/: We have an array of integers, nums, and an array of requests where requests[i] = [starti, endi]. The ith request asks for the sum of nums[starti] + nums[starti + 1] + ... + nums[endi - 1] + nums[endi]. Both starti ...
class Solution: def maxSumRangeQuery(self, nums: List[int], requests: List[List[int]]) -> int: \"\"\" Assume: 1. list, list -> int 2. only find sum, permutation is not unique 3. nums is not sorted Algorithm: sort nums in requ...
python
train
abovesol
codeparrot/apps
all
Solve in Python: Chef Ada is preparing $N$ dishes (numbered $1$ through $N$). For each valid $i$, it takes $C_i$ minutes to prepare the $i$-th dish. The dishes can be prepared in any order. Ada has a kitchen with two identical burners. For each valid $i$, to prepare the $i$-th dish, she puts it on one of the burners an...
for i in range(int(input())): n=int(input()) c=[int(z) for z in input().split()] c.sort() c.reverse() b1,b2=0,0 for i in range(n): if b1<b2: b1+=c[i] elif b2<b1: b2+=c[i] else: b1+=c[i] print(max(b1,b2))
python
train
qsol
codeparrot/apps
all
Solve in Python: There is an N-car train. You are given an integer i. Find the value of j such that the following statement is true: "the i-th car from the front of the train is the j-th car from the back." -----Constraints----- - 1 \leq N \leq 100 - 1 \leq i \leq N -----Input----- Input is given from Standard Inpu...
n, i = map(int, input().split()) print(n - i + 1)
python
test
qsol
codeparrot/apps
all
I found an interesting problem on https://leetcode.com/problems/validate-binary-tree-nodes/: You have n binary tree nodes numbered from 0 to n - 1 where node i has two children leftChild[i] and rightChild[i], return true if and only if all the given nodes form exactly one valid binary tree. If node i has no left child ...
class Solution: def validateBinaryTreeNodes(self, n, left, right): roots={*range(n)} for x in left+right: if x==-1: continue if x not in roots: return False roots.discard(x) if len(roots)!=1: return False ...
python
train
abovesol
codeparrot/apps
all
Solve in Python: 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 can eat other monster if its weight is strictly greater than the wei...
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
qsol
codeparrot/apps
all
I found an interesting problem on https://www.codewars.com/kata/59f33b86a01431d5ae000032: The [half-life](https://en.wikipedia.org/wiki/Half-life) of a radioactive substance is the time it takes (on average) for one-half of its atoms to undergo radioactive decay. # Task Overview Given the initial quantity of a radioac...
import math def half_life(q0, q1, t): return 1/(math.log(q0/q1)/(t*math.log(2)))
python
train
abovesol
codeparrot/apps
all
Solve in Python: The Little Elephant from the Zoo of Lviv has an array A that consists of N positive integers. Let A[i] be the i-th number in this array (i = 1, 2, ..., N). Find the minimal number x > 1 such that x is a divisor of all integers from array A. More formally, this x should satisfy the following relations:...
from functools import reduce from math import gcd def divisor(n): i = 3 while i*i <= n: if n%i==0: return i i+=2 return n for _ in range(int(input())): n = int(input()) ls = [int(X) for X in input().split()] gc = reduce(gcd,ls) #gcd gives you the gre...
python
train
qsol
codeparrot/apps
all
I found an interesting problem on https://codeforces.com/problemset/problem/952/E: Not to be confused with chessboard. [Image] -----Input----- The first line of input contains a single integer N (1 ≤ N ≤ 100) — the number of cheeses you have. The next N lines describe the cheeses you have. Each line contains two...
from math import sqrt n = int(input()) s, h = 0, 0 for i in range(n): a, b = input().split() if b == 'soft': s += 1 else: h += 1 k = 2 * max(s, h) - 1 if s + h > k: k += 1 t = int(sqrt(k)) if t * t < k: t += 1 print(t)
python
test
abovesol
codeparrot/apps
all
Solve in Python: Return the length of the shortest, non-empty, contiguous subarray of A with sum at least K. If there is no non-empty subarray with sum at least K, return -1.   Example 1: Input: A = [1], K = 1 Output: 1 Example 2: Input: A = [1,2], K = 4 Output: -1 Example 3: Input: A = [2,-1,2], K = 3 Output: 3...
from collections import deque class Solution: def shortestSubarray(self, A: List[int], k: int) -> int: for ele in A: if ele>=k: return 1 s=[0] for i in range(len(A)): s.append((s[-1] if len(s) else 0)+A[i]) print(s) queue=deque() ...
python
train
qsol
codeparrot/apps
all
I found an interesting problem on https://codeforces.com/problemset/problem/1029/C: You are given $n$ segments on a number line; each endpoint of every segment has integer coordinates. Some segments can degenerate to points. Segments can intersect with each other, be nested in each other or even coincide. The intersec...
n = int(input()) l1 = 0 l2 = -1 r1 = 0 r2 = -1 ls = [] rs = [] for i in range(n): l, r = map(int, input().split()) ls.append(l) rs.append(r) if i == 0: continue if l > ls[l1] or l == ls[l1] and r <= rs[l1]: l2 = l1 l1 = i elif l2 == -1 or l > ls[l2] or l == ls[l2] and r <...
python
test
abovesol
codeparrot/apps
all
Solve in Python: #### Background: A linear regression line has an equation in the form `$Y = a + bX$`, where `$X$` is the explanatory variable and `$Y$` is the dependent variable. The parameter `$b$` represents the *slope* of the line, while `$a$` is called the *intercept* (the value of `$y$` when `$x = 0$`). For ...
import numpy as np def regressionLine(x, y): b, a = tuple(np.round(np.polyfit(x, y, 1), 4)) return a, b
python
train
qsol
codeparrot/apps
all
I found an interesting problem on https://atcoder.jp/contests/abc172/tasks/abc172_f: There are N piles of stones. The i-th pile has A_i stones. Aoki and Takahashi are about to use them to play the following game: - Starting with Aoki, the two players alternately do the following operation: - Operation: Choose one pil...
def main(): import sys def input(): return sys.stdin.readline().rstrip() n = int(input()) a = list(map(int, input().split())) x = 0 for i in range(2, n): x ^= a[i] d = a[0]+a[1]-x if d%2 == 1 or d < 0: print(-1) return d >>= 1 if d&x != 0 or d > a[0]: ...
python
test
abovesol
codeparrot/apps
all
I found an interesting problem on https://www.codechef.com/PBK12020/problems/ITGUY16: 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...
# cook your dish here t = int(input()) def pattern(k): for i in range(1, k+1): if i%2 == 1: s = '' for j in range(i): s+=chr(65+j) s = ' '*(26-i) + s print(s) else: s='' for j in range(1, i+1): s+=str(j) s = ' '*(26-i) + s print(s) for _ in range(t): k = int(input()) pattern(k...
python
train
abovesol
codeparrot/apps
all
Solve in Python: You are given a tree with N vertices and N-1 edges. The vertices are numbered 1 to N, and the i-th edge connects Vertex a_i and b_i. You have coloring materials of K colors. For each vertex in the tree, you will choose one of the K colors to paint it, so that the following condition is satisfied: - If...
import sys sys.setrecursionlimit(10**6) MOD=10**9+7 def facinv(N): fac,finv,inv=[0]*(N+1),[0]*(N+1),[0]*(N+1) fac[0]=1;fac[1]=1;finv[0]=1;finv[1]=1;inv[1]=1 for i in range(2,N+1): fac[i]=fac[i-1]*i%MOD inv[i]=MOD-inv[MOD%i]*(MOD//i)%MOD finv[i]=finv[i-1]*inv[i]%MOD return fac,fin...
python
test
qsol
codeparrot/apps
all
Solve in Python: Let $a$ and $b$ be two arrays of lengths $n$ and $m$, respectively, with no elements in common. We can define a new array $\mathrm{merge}(a,b)$ of length $n+m$ recursively as follows: If one of the arrays is empty, the result is the other array. That is, $\mathrm{merge}(\emptyset,b)=b$ and $\mathrm{me...
t = int(input()) for _ in range(t): n = int(input()) l = [int(x) for x in input().split()] cur = l[0] cll = 1 blocks = [] for x in l[1:]: if x > cur: blocks.append(cll) cur = x cll = 1 else: cll += 1 blocks.append(cll) pos...
python
train
qsol
codeparrot/apps
all