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 surrender to the enemy, they instead opted for mass suicide, with a twist: **they formed a circle and proceeded to kill one man every three, until one last man was left (and that it was supposed to kill himself to end the act)**. Well, Josephus and another man were the last two and, as we now know every detail of the story, you may have correctly guessed that they didn't exactly follow through the original idea. You are now to create a function that returns a Josephus permutation, taking as parameters the initial *array/list of items* to be permuted as if they were in a circle and counted out every *k* places until none remained. **Tips and notes:** it helps to start counting from 1 up to n, instead of the usual range 0..n-1; k will always be >=1. For example, with n=7 and k=3 `josephus(7,3)` should act this way. ``` [1,2,3,4,5,6,7] - initial sequence [1,2,4,5,6,7] => 3 is counted out and goes into the result [3] [1,2,4,5,7] => 6 is counted out and goes into the result [3,6] [1,4,5,7] => 2 is counted out and goes into the result [3,6,2] [1,4,5] => 7 is counted out and goes into the result [3,6,2,7] [1,4] => 5 is counted out and goes into the result [3,6,2,7,5] [4] => 1 is counted out and goes into the result [3,6,2,7,5,1] [] => 4 is counted out and goes into the result [3,6,2,7,5,1,4] ``` So our final result is: ``` josephus([1,2,3,4,5,6,7],3)==[3,6,2,7,5,1,4] ``` For more info, browse the Josephus Permutation page on wikipedia; related kata: Josephus Survivor. Also, [live game demo](https://iguacel.github.io/josephus/) by [OmniZoetrope](https://www.codewars.com/users/OmniZoetrope). I tried it in Python, but could not do it. Can you solve it?
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 if there are duplicates of items in a list for item in itemlist: if count == interval: disposal.append(item) itemlist.pop(index) count = 1 try: print(itemlist[index]) #sees if there is another number after the deleted one. Catches numbers at the end of the list which get's deleted except: break count += 1 index += 1 return disposal
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: - The [Moore neighborhood](https://en.wikipedia.org/wiki/Moore_neighborhood) are eight cells which surround a given cell. - The [Von Neumann neighborhood](https://en.wikipedia.org/wiki/Von_Neumann_neighborhood) are four cells which share a border with the given cell. ___ # Task Given a neighbourhood type (`"moore"` or `"von_neumann"`), a 2D matrix (a list of lists) and a pair of coordinates, return the list of neighbours of the given cell. Notes: - The order of the elements in the output list is not important. - If the input indexes are outside the matrix, return an empty list. - If the the matrix is empty, return an empty list. - Order of the indices: The first index should be applied for the outer/first matrix layer. The last index for the most inner/last layer. `coordinates = (m, n)` should be apllied like `mat[m][n]` ___ ## Examples ``` \ n 0 1 2 3 4 m -------------------------- 0 | 0 | 1 | 2 | 3 | 4 | 1 | 5 | 6 | 7 | 8 | 9 | 2 | 10 | 11 | 12 | 13 | 14 | 3 | 15 | 16 | 17 | 18 | 19 | 4 | 20 | 21 | 22 | 23 | 24 | -------------------------- get_neighborhood("moore", mat, (1,1)) == [0, 1, 2, 5, 7, 10, 11, 12] get_neighborhood("moore", mat, (0,0)) == [1, 6, 5] get_neighborhood("moore", mat, (4,2)) == [21, 16, 17, 18, 23] get_neighborhood("von_neumann", mat, (1,1)) == [1, 5, 7, 11] get_neighborhood("von_neumann", mat, (0,0)) == [1, 5] get_neighborhood("von_neumann", mat, (4,2)) == [21, 17, 23] ``` ___ Translations are appreciated.^^ If you like chess take a look at [Chess Aesthetics](https://www.codewars.com/kata/5b574980578c6a6bac0000dc) If you like puzzles and take a look at [Rubik's cube](https://www.codewars.com/kata/5b3bec086be5d8893000002e)
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' else [(0,1), (0,-1), (1,0), (-1,0)] ) return [ arr[a][b] for a,b in ((x+dx,y+dy) for dx,dy in neigh) if isInside(a,b) ]
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 first argument is considered smaller than, equal to, or larger than the second argument* *(source: https://docs.python.org/2/library/functions.html#sorted)* The greek alphabet is preloded for you as `greek_alphabet`: ```python 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') ``` ## Examples ```python greek_comparator('alpha', 'beta') < 0 greek_comparator('psi', 'psi') == 0 greek_comparator('upsilon', 'rho') > 0 ```
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 nonlocal namespace if greek_alphabet.index(lhs) < greek_alphabet.index(rhs): return -(greek_alphabet.index(rhs) - greek_alphabet.index(lhs)) elif greek_alphabet.index(lhs) == greek_alphabet.index(rhs): return 0 else: return greek_alphabet.index(lhs) - greek_alphabet.index(rhs)
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 retake a job that you have already done. Find the maximum total reward that you can earn no later than M days from today. You can already start working today. -----Constraints----- - All values in input are integers. - 1 \leq N \leq 10^5 - 1 \leq M \leq 10^5 - 1 \leq A_i \leq 10^5 - 1 \leq B_i \leq 10^4 -----Input----- Input is given from Standard Input in the following format: N M A_1 B_1 A_2 B_2 \vdots A_N B_N -----Output----- Print the maximum total reward that you can earn no later than M days from today. -----Sample Input----- 3 4 4 3 4 1 2 2 -----Sample Output----- 5 You can earn the total reward of 5 by taking the jobs as follows: - Take and complete the first job today. You will earn the reward of 3 after four days from today. - Take and complete the third job tomorrow. You will earn the reward of 2 after two days from tomorrow, that is, after three days from today. I tried it in Python, but could not do it. Can you solve it?
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 = [list(mi()) for i in range(n)] return [list(i) for i in zip(*tmp)] def lcm(a, b): return a*b//math.gcd(a, b) def main(): N, M = mi() A, B = i2(N) ans = 0 d = defaultdict(list) for i in range(N): d[A[i]].append(B[i]) h = [] heapq.heapify(h) for i in range(1, M+1): for v in d[i]: heapq.heappush(h, -v) if h: ans -= heapq.heappop(h) else: continue print(ans) def __starting_point(): main() __starting_point()
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 occupies one station at a time and travels around the network of stations in a circular manner. More precisely, the immediate station that the train will visit after station $i$ is station $i+1$ if $1 \leq i < n$ or station $1$ if $i = n$. It takes the train $1$ second to travel to its next station as described. Bob gave Alice a fun task before he left: to deliver $m$ candies that are initially at some stations to their independent destinations using the train. The candies are enumerated from $1$ through $m$. Candy $i$ ($1 \leq i \leq m$), now at station $a_i$, should be delivered to station $b_i$ ($a_i \neq b_i$). [Image] The blue numbers on the candies correspond to $b_i$ values. The image corresponds to the $1$-st example. The train has infinite capacity, and it is possible to load off any number of candies at a station. However, only at most one candy can be loaded from a station onto the train before it leaves the station. You can choose any candy at this station. The time it takes to move the candies is negligible. Now, Alice wonders how much time is needed for the train to deliver all candies. Your task is to find, for each station, the minimum time the train would need to deliver all the candies were it to start from there. -----Input----- The first line contains two space-separated integers $n$ and $m$ ($2 \leq n \leq 100$; $1 \leq m \leq 200$) — the number of stations and the number of candies, respectively. The $i$-th of the following $m$ lines contains two space-separated integers $a_i$ and $b_i$ ($1 \leq a_i, b_i \leq n$; $a_i \neq b_i$) — the station that initially contains candy $i$ and the destination station of the candy, respectively. -----Output----- In the first and only line,...
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)*n) out_ = [] for x in range(n): res = 0 for y, v in c.items(): s = y-x + (n if y<x else 0) res = max(res, v+s) out_.append(res) print(*out_) __starting_point()
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 one operation. For example, if $a = [2, 1, 3, 1, 1, 3, 2]$, you can get the following sequences in one operation (for convenience, denote elements equal to $x$ as $x$-elements): $[1, 1, 1, 2, 3, 3, 2]$ if you move all $1$-elements to the beginning; $[2, 3, 3, 2, 1, 1, 1]$ if you move all $1$-elements to the end; $[2, 2, 1, 3, 1, 1, 3]$ if you move all $2$-elements to the beginning; $[1, 3, 1, 1, 3, 2, 2]$ if you move all $2$-elements to the end; $[3, 3, 2, 1, 1, 1, 2]$ if you move all $3$-elements to the beginning; $[2, 1, 1, 1, 2, 3, 3]$ if you move all $3$-elements to the end; You have to determine the minimum number of such operations so that the sequence $a$ becomes sorted in non-descending order. Non-descending order means that for all $i$ from $2$ to $n$, the condition $a_{i-1} \le a_i$ is satisfied. Note that you have to answer $q$ independent queries. -----Input----- The first line contains one integer $q$ ($1 \le q \le 3 \cdot 10^5$) — the number of the queries. Each query is represented by two consecutive lines. The first line of each query contains one integer $n$ ($1 \le n \le 3 \cdot 10^5$) — the number of elements. The second line of each query contains $n$ integers $a_1, a_2, \dots , a_n$ ($1 \le a_i \le n$) — the elements. It is guaranteed that the sum of all $n$ does not exceed $3 \cdot 10^5$. -----Output----- For each query print one integer — the minimum number of operation for sorting sequence $a$ in non-descending order. -----Example----- Input 3 7 3 1 6 6 3 1 1 8 1 1 4 4 4 7 8 8 7 4 2 5 2 6 2 7 Output 2 0 1 -----Note----- In the first query, you can move all $1$-elements to the beginning (after that sequence turn into $[1, 1, 1, 3, 6, 6, 3]$) and then move all...
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] + Array[index + 1:len(Array)] return Array def DeleteRepetitionsIn2(Array): AlreadyRead = {} for elem in Array: if elem in AlreadyRead: continue AlreadyRead[elem] = "" return list(AlreadyRead) Results = [] ArraysNumber = int(input()) for e in range(ArraysNumber): AbsolutelyUselessNumber = int(input()) Array = list(map(int, input().split())) if len(Array) == 1: Results.append(0) continue #print(Array) TheRightOrder = DeleteRepetitionsIn2(Array) TheRightOrder.sort() TheCurrentOrder = {} for i in range(len(Array)): if Array[i] not in TheCurrentOrder: TheCurrentOrder[Array[i]] = [i, i] continue TheCurrentOrder[Array[i]][1] = i #print(TheRightOrder) #print(TheCurrentOrder) #print(Array) TheCurrentResult = 1 TheMaxResult = 1 for i in range(len(TheRightOrder)): #print("a =", TheCurrentResult) #print("b =", TheMaxResult) if i == len(TheRightOrder) - 1: if TheCurrentResult >= TheMaxResult: TheMaxResult = TheCurrentResult continue if TheCurrentOrder[TheRightOrder[i]][1] > TheCurrentOrder[TheRightOrder[i + 1]][0]: if TheCurrentResult >= TheMaxResult: TheMaxResult = TheCurrentResult TheCurrentResult = 1 continue TheCurrentResult += 1 Results.append(len(TheRightOrder) - TheMaxResult) for i in Results: print(i)
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−1$N-1$ edges. The nodes are numbered from 1$1$ to N$N$, and the tree is rooted at node 1$1$. These nodes represent the corrupt officials and each corrupt official works under some other corrupt official except the Boss who is represented by node 1$1$. Gru believes in divide and conquer and thinks that this network needs to be divided into as many sub-networks as possible. He commands the minions to kill some of the corrupt officials in order to break the network into maximum sub-networks. But as you know, these corrupt officials are very sharp, and hence these assassinations need to be done very smartly and silently, without leaving any traces. To achieve this Gru devises a strategy, in which he designs an operation, and that operation can be applied by the minions any number of times (even 0). In one operation the minions can select any one leaf node official [that is an official who does not have any other official beneath him] in the graph and kill him along with all his ancestors$ancestors$ officials till the root$root$ of the tree in which the operation is applied (this is done to wipe all traces of the operation). This deleted all those nodes from the graph, and also, while doing so, all the associated edges/connections$edges/connections$ of the leaf node and its ancestors are also destroyed. Hence after applying this operation on any tree, it breaks into some connected components which are also trees, which are the new sub-networks. Now the minions are a bit lazy and will do the task someday, but they need to submit a report to Gru containing the number of the maximum$maximum$ connected$connected$ components$components$ that they could achieve by applying the operation any number of times. To do this, the minions require your help. So help the minions by finding... I tried it in Python, but could not do it. Can you solve it?
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]: if vis[i]==0: pa[i]=x vis[i]=1 if x==0: st.append((i,y+len(a[x])-1)) else: st.append((i,y+len(a[x])-2)) c=[] for i in range(1,n): if len(a[i])==1: c.append((b[i],i)) c.sort() ans=0 while c: x,y=c.pop() m=y p=0 while y!=0 and pa[y]!=-1: y=pa[y] if pa[y]==-1: break if y!=0: p+=(len(a[y])-2) else: p+=(len(a[y])-1) if p>=1: p=0 while m!=0 and pa[m]!=-1: x=m if pa[m]==-1: break m=pa[m] pa[x]=-1 if m!=0: p+=(len(a[m])-2) else: p+=(len(a[m])-1) if y==0: pa[0]=-1 for i in range(n): if pa[i]!=-1: st=[i] pa[i]=-1 while st: x=st.pop() for j in a[x]: if pa[j]!=-1: pa[j]=-1 st.append(j) ans+=1 print(ans)
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: `(area, volume)` ``` ```if:racket Write a function that returns the total surface area and volume of a box as a list: `'(area, volume)` ``` I tried it in Python, but could not do it. Can you solve it?
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'); # ['a'] permutations('ab'); # ['ab', 'ba'] permutations('aabb'); # ['aabb', 'abab', 'abba', 'baab', 'baba', 'bbaa'] ``` The order of the permutations doesn't matter. I tried it in Python, but could not do it. Can you solve it?
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: - Use spaces to fill in the gaps on the left side of the words. - Each line should contain as many words as possible. - Use '\n' to separate lines. - Gap between words can't differ by more than one space. - Lines should end with a word not a space. - '\n' is not included in the length of a line. - Last line should not contain '\n' Example with width=30: ``` Bacon ipsum dolor amet excepteur ut kevin burgdoggen, shankle cupim dolor officia ground round id ullamco deserunt nisi. Commodo tail qui salami, brisket boudin tri-tip. Labore flank laboris, cow enim proident aliqua sed hamburger consequat. Sed consequat ut non bresaola capicola shoulder excepteur veniam, bacon kevin. Pastrami shank laborum est excepteur non eiusmod bresaola flank in nostrud. Corned beef ex pig do kevin filet mignon in irure deserunt ipsum qui duis short loin. Beef ribs dolore meatball officia rump fugiat in enim corned beef non est. ``` If you enjoyed this one and want more of a challenge try https://www.codewars.com/kata/text-align-justify/python If you like bacon ipsum https://baconipsum.com I tried it in Python, but could not do it. Can you solve it?
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() for x in last)
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 Konrad are located in positions $a$, $b$ and $c$ respectively. At the end of the performance, the distance between each pair of ropewalkers was at least $d$. Ropewalkers can walk on the rope. In one second, only one ropewalker can change his position. Every ropewalker can change his position exactly by $1$ (i. e. shift by $1$ to the left or right direction on the rope). Agafon, Boniface and Konrad can not move at the same time (Only one of them can move at each moment). Ropewalkers can be at the same positions at the same time and can "walk past each other". You should find the minimum duration (in seconds) of the performance. In other words, find the minimum number of seconds needed so that the distance between each pair of ropewalkers can be greater or equal to $d$. Ropewalkers can walk to negative coordinates, due to the rope is infinite to both sides. -----Input----- The only line of the input contains four integers $a$, $b$, $c$, $d$ ($1 \le a, b, c, d \le 10^9$). It is possible that any two (or all three) ropewalkers are in the same position at the beginning of the performance. -----Output----- Output one integer — the minimum duration (in seconds) of the performance. -----Examples----- Input 5 2 6 3 Output 2 Input 3 1 5 6 Output 8 Input 8 3 3 2 Output 2 Input 2 3 10 4 Output 3 -----Note----- In the first example: in the first two seconds Konrad moves for 2 positions to the right (to the position $8$), while Agafon and Boniface stay at their positions. Thus, the distance between Agafon and Boniface will be $|5 - 2| = 3$, the distance between Boniface and Konrad will be $|2 - 8| = 6$ and the distance between Agafon and Konrad will be $|5 - 8| = 3$. Therefore, all three pairwise distances will be at least $d=3$, so the performance could be finished... I tried it in Python, but could not do it. Can you solve it?
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 are given a sequence of integer numbers $a_1, a_2, \dots, a_n$, each number is from $1$ to $3$ and $a_i \ne a_{i + 1}$ for each valid $i$. The $i$-th number represents a type of the $i$-th figure: circle; isosceles triangle with the length of height equal to the length of base; square. The figures of the given sequence are placed somewhere on a Cartesian plane in such a way that: $(i + 1)$-th figure is inscribed into the $i$-th one; each triangle base is parallel to OX; the triangle is oriented in such a way that the vertex opposite to its base is at the top; each square sides are parallel to the axes; for each $i$ from $2$ to $n$ figure $i$ has the maximum possible length of side for triangle and square and maximum radius for circle. Note that the construction is unique for some fixed position and size of just the first figure. The task is to calculate the number of distinct points (not necessarily with integer coordinates) where figures touch. The trick is, however, that the number is sometimes infinite. But that won't make the task difficult for you, will it? So can you pass the math test and enroll into Berland State University? -----Input----- The first line contains a single integer $n$ ($2 \le n \le 100$) — the number of figures. The second line contains $n$ integer numbers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 3$, $a_i \ne a_{i + 1}$) — types of the figures. -----Output----- The first line should contain either the word "Infinite" if the number of distinct points where figures touch is infinite or "Finite" otherwise. If the number is finite than print it in the second line. It's guaranteed that the number fits into 32-bit integer type. -----Examples----- Input 3 2 1...
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: answer -= 1 else: answer += 4 elif a[i - 1] == RECTANGLE: if a[i] == CIRCLE: answer += 3 else: print('Infinite') return elif a[i - 1] == SQUARE: if a[i] == CIRCLE: answer += 4 else: print('Infinite') return print('Finite') print(answer) def __starting_point(): main() __starting_point()
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$ is even and there is a number $\dfrac{a_i}{2}$ in the array. For example, if $n=5$, $l=2$, $r=3$ then an array could be $[1,2,2,4,4]$ or $[1,1,1,1,2]$; but it couldn't be $[1,2,2,4,8]$ because this array contains $4$ different numbers; it couldn't be $[1,2,2,3,3]$ because $3$ is odd and isn't equal to $1$; and it couldn't be $[1,1,2,2,16]$ because there is a number $16$ in the array but there isn't a number $\frac{16}{2} = 8$. According to these facts, he is asking you to count the minimal and the maximal possible sums of all elements in an array. -----Input----- The only input line contains three integers $n$, $l$ and $r$ ($1 \leq n \leq 1\,000$, $1 \leq l \leq r \leq \min(n, 20)$) — an array's size, the minimal number and the maximal number of distinct elements in an array. -----Output----- Output two numbers — the minimal and the maximal possible sums of all elements in an array. -----Examples----- Input 4 2 2 Output 5 7 Input 5 1 5 Output 5 31 -----Note----- In the first example, an array could be the one of the following: $[1,1,1,2]$, $[1,1,2,2]$ or $[1,2,2,2]$. In the first case the minimal sum is reached and in the last case the maximal sum is reached. In the second example, the minimal sum is reached at the array $[1,1,1,1,1]$, and the maximal one is reached at the array $[1,2,4,8,16]$.
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, Pasha can choose any pixel and color it black. In particular, he can choose the pixel that is already black, then after the boy's move the pixel does not change, that is, it remains black. Pasha loses the game when a 2 × 2 square consisting of black pixels is formed. Pasha has made a plan of k moves, according to which he will paint pixels. Each turn in his plan is represented as a pair of numbers i and j, denoting respectively the row and the column of the pixel to be colored on the current move. Determine whether Pasha loses if he acts in accordance with his plan, and if he does, on what move the 2 × 2 square consisting of black pixels is formed. -----Input----- The first line of the input contains three integers n, m, k (1 ≤ n, m ≤ 1000, 1 ≤ k ≤ 10^5) — the number of rows, the number of columns and the number of moves that Pasha is going to perform. The next k lines contain Pasha's moves in the order he makes them. Each line contains two integers i and j (1 ≤ i ≤ n, 1 ≤ j ≤ m), representing the row number and column number of the pixel that was painted during a move. -----Output----- If Pasha loses, print the number of the move when the 2 × 2 square consisting of black pixels is formed. If Pasha doesn't lose, that is, no 2 × 2 square consisting of black pixels is formed during the given k moves, print 0. -----Examples----- Input 2 2 4 1 1 1 2 2 1 2 2 Output 4 Input 2 3 6 2 3 2 2 1 3 2 2 1 2 1 1 Output 5 Input 5 3 7 2 3 1 2 1 1 4 1 3 1 5 3 3 2 Output 0
__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 lose = check(pole, rdl[0]-1,rdl[1]-1) if lose and cmplt: cmplt = False print(i+1) #fl.close() if not lose and cmplt: print(0) def check(pole, index1,index): if index1-1 >= 0 and index+1 < len(pole[0]): if pole[index1][index+1] == 1 and pole[index1-1][index] == 1 and pole[index1-1][index+1] == 1: return True if index1+1 < len(pole) and index-1>0 >= 0: if pole[index1][index-1] == 1 and pole[index1+1][index-1] == 1 and pole[index1+1][index] == 1: return True if index1-1 >= 0 and index-1 >= 0: if pole[index1-1][index] == 1 and pole[index1-1][index-1] == 1 and pole[index1][index-1] == 1: return True if index1+1 < len(pole) and index+1 < len(pole[0]): if pole[index1+1][index] == 1 and pole[index1+1][index+1] == 1 and pole[index1][index+1]: return True TaskA()
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 gets all of them. Each day (during the morning) Ivan earns exactly one burle. There are $n$ types of microtransactions in the game. Each microtransaction costs $2$ burles usually and $1$ burle if it is on sale. Ivan has to order exactly $k_i$ microtransactions of the $i$-th type (he orders microtransactions during the evening). Ivan can order any (possibly zero) number of microtransactions of any types during any day (of course, if he has enough money to do it). If the microtransaction he wants to order is on sale then he can buy it for $1$ burle and otherwise he can buy it for $2$ burles. There are also $m$ special offers in the game shop. The $j$-th offer $(d_j, t_j)$ means that microtransactions of the $t_j$-th type are on sale during the $d_j$-th day. Ivan wants to order all microtransactions as soon as possible. Your task is to calculate the minimum day when he can buy all microtransactions he want and actually start playing. -----Input----- The first line of the input contains two integers $n$ and $m$ ($1 \le n, m \le 1000$) — the number of types of microtransactions and the number of special offers in the game shop. The second line of the input contains $n$ integers $k_1, k_2, \dots, k_n$ ($0 \le k_i \le 1000$), where $k_i$ is the number of copies of microtransaction of the $i$-th type Ivan has to order. It is guaranteed that sum of all $k_i$ is not less than $1$ and not greater than $1000$. The next $m$ lines contain special offers. The $j$-th of these lines contains the $j$-th special offer. It is given as a pair of integers $(d_j, t_j)$ ($1 \le d_j \le 1000, 1 \le t_j \le n$) and means that microtransactions of the $t_j$-th type are on sale during the $d_j$-th day. -----Output----- Print one...
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_day, sale_type sales = sorted(sales, key=lambda x: x[0], reverse=True) # sort by day def can_buy_in(dday): used = 0 money_left = dday items = copy.deepcopy(n_items) for sale_day, sale_type in sales: if sale_day > dday: continue if money_left > sale_day: money_left = sale_day can_buy = min(items[sale_type-1], money_left) # buy it used += can_buy items[sale_type-1] -= can_buy money_left -= can_buy if money_left == 0: break need_money_for_rest = sum(items) * 2 return need_money_for_rest + used <= dday total_items = sum(n_items) low = total_items high = total_items * 2 # find minimum can_buy day while low <= high: mid = (low + high) // 2 if can_buy_in(mid): high = mid-1 else: low = mid+1 print(low)
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 knows n airports. All the airports are located on a straight line. Each airport has unique id from 1 to n, Vladik's house is situated next to the airport with id a, and the place of the olympiad is situated next to the airport with id b. It is possible that Vladik's house and the place of the olympiad are located near the same airport. To get to the olympiad, Vladik can fly between any pair of airports any number of times, but he has to start his route at the airport a and finish it at the airport b. Each airport belongs to one of two companies. The cost of flight from the airport i to the airport j is zero if both airports belong to the same company, and |i - j| if they belong to different companies. Print the minimum cost Vladik has to pay to get to the olympiad. -----Input----- The first line contains three integers n, a, and b (1 ≤ n ≤ 10^5, 1 ≤ a, b ≤ n) — the number of airports, the id of the airport from which Vladik starts his route and the id of the airport which he has to reach. The second line contains a string with length n, which consists only of characters 0 and 1. If the i-th character in this string is 0, then i-th airport belongs to first company, otherwise it belongs to the second. -----Output----- Print single integer — the minimum cost Vladik has to pay to get to the olympiad. -----Examples----- Input 4 1 4 1010 Output 1 Input 5 5 2 10110 Output 0 -----Note----- In the first example Vladik can fly to the airport 2 at first and pay |1 - 2| = 1 (because the airports belong to different companies), and then fly from the airport 2 to the airport 4 for free (because the airports belong to the same company). So the cost of the whole flight is equal to 1. It's impossible to get to the olympiad for free, so the answer is equal to 1. In the second... I tried it in Python, but could not do it. Can you solve it?
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 integer over the k obtained minimums. What is the maximum possible integer you can get? Definitions of subsegment and array splitting are given in notes. -----Input----- The first line contains two integers n and k (1 ≤ k ≤ n ≤ 10^5) — the size of the array a and the number of subsegments you have to split the array to. The second line contains n integers a_1, a_2, ..., a_{n} ( - 10^9 ≤ a_{i} ≤ 10^9). -----Output----- Print single integer — the maximum possible integer you can get if you split the array into k non-empty subsegments and take maximum of minimums on the subsegments. -----Examples----- Input 5 2 1 2 3 4 5 Output 5 Input 5 1 -4 -5 -3 -2 -1 Output -5 -----Note----- A subsegment [l, r] (l ≤ r) of array a is the sequence a_{l}, a_{l} + 1, ..., a_{r}. Splitting of array a of n elements into k subsegments [l_1, r_1], [l_2, r_2], ..., [l_{k}, r_{k}] (l_1 = 1, r_{k} = n, l_{i} = r_{i} - 1 + 1 for all i > 1) is k sequences (a_{l}_1, ..., a_{r}_1), ..., (a_{l}_{k}, ..., a_{r}_{k}). In the first example you should split the array into subsegments [1, 4] and [5, 5] that results in sequences (1, 2, 3, 4) and (5). The minimums are min(1, 2, 3, 4) = 1 and min(5) = 5. The resulting maximum is max(1, 5) = 5. It is obvious that you can't reach greater result. In the second example the only option you have is to split the array into one subsegment [1, 5], that results in one sequence ( - 4, - 5, - 3, - 2, - 1). The only minimum is min( - 4, - 5, - 3, - 2, - 1) = - 5. The resulting maximum is - 5. I tried it in Python, but could not do it. Can you solve it?
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 = - 10 ** 10 for i in range(n - 1): ans = max(ans, max(b[i], c[i])) print(ans) else: print(max(a))
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", and vice versa. A string is called good if it does not contain "010" or "101" as a subsequence  — for instance, "1001" contains "101" as a subsequence, hence it is not a good string, while "1000" doesn't contain neither "010" nor "101" as subsequences, so it is a good string. What is the minimum number of operations he will have to perform, so that the string becomes good? It can be shown that with these operations we can make any string good. A string $a$ is a subsequence of a string $b$ if $a$ can be obtained from $b$ by deletion of several (possibly, zero or all) characters. -----Input----- The first line of the input contains a single integer $t$ $(1\le t \le 100)$ — the number of test cases. Each of the next $t$ lines contains a binary string $s$ $(1 \le |s| \le 1000)$. -----Output----- For every string, output the minimum number of operations required to make it good. -----Example----- Input 7 001 100 101 010 0 1 001100 Output 0 0 1 1 0 0 2 -----Note----- In test cases $1$, $2$, $5$, $6$ no operations are required since they are already good strings. For the $3$rd test case: "001" can be achieved by flipping the first character  — and is one of the possible ways to get a good string. For the $4$th test case: "000" can be achieved by flipping the second character  — and is one of the possible ways to get a good string. For the $7$th test case: "000000" can be achieved by flipping the third and fourth characters  — and is one of the possible ways to get a good string.
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] == '0': cyk += 1 else: cyk -= 1 wyn = min(wyn,cyk) print(wyn)
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 parenthesized subgroup. 'username' >>> m.group(2) # The second parenthesized subgroup. 'hackerrank' >>> m.group(3) # The third parenthesized subgroup. 'com' >>> m.group(1,2,3) # Multiple arguments give us a tuple. ('username', 'hackerrank', 'com') groups() A groups() expression returns a tuple containing all the subgroups of the match. Code >>> import re >>> m = re.match(r'(\w+)@(\w+)\.(\w+)','username@hackerrank.com') >>> m.groups() ('username', 'hackerrank', 'com') groupdict() A groupdict() expression returns a dictionary containing all the named subgroups of the match, keyed by the subgroup name. Code >>> m = re.match(r'(?P<user>\w+)@(?P<website>\w+)\.(?P<extension>\w+)','myname@hackerrank.com') >>> m.groupdict() {'website': 'hackerrank', 'user': 'myname', 'extension': 'com'} =====Problem Statement===== You are given a string S. Your task is to find the first occurrence of an alphanumeric character in (read from left to right) that has consecutive repetitions. =====Input Format===== A single line of input containing the string S. =====Constraints===== 0<len(S)<100 =====Output Format===== Print the first occurrence of the repeating character. If there are no repeating characters, print -1.
#!/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 subarray Aij is product of all its elements (from ith to jth). -----Input----- - First line contains sinlge integer N denoting the number of elements. - Second line contains N space-separated integers A1, A2, ..., AN denoting the elements of array. -----Output----- - In a single line print single integer - the maximal length of subarray with non-zero product. -----Constraints----- - 1 ≤ N ≤ 100000 - 0 ≤ Ai ≤ 10000 -----Example----- Input: 6 1 0 2 3 0 4 Output: 2 Input: 1 0 Output: 0 Input: 3 1 0 1 Output: 1 -----Explanation----- For the first sample subarray is: {2, 3}. For the second sample there are no subbarays with non-zero product. For the third sample subbarays is {1}, (the first element, or the third one). I tried it in Python, but could not do it. Can you solve it?
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. Sometimes the government makes payouts to the poor: all citizens who have strictly less money than $x$ are paid accordingly so that after the payout they have exactly $x$ money. In this case the citizens don't send a receipt. You know the initial wealth of every citizen and the log of all events: receipts and payouts. Restore the amount of money each citizen has after all events. -----Input----- The first line contains a single integer $n$ ($1 \le n \le 2 \cdot 10^{5}$) — the numer of citizens. The next line contains $n$ integers $a_1$, $a_2$, ..., $a_n$ ($0 \le a_{i} \le 10^{9}$) — the initial balances of citizens. The next line contains a single integer $q$ ($1 \le q \le 2 \cdot 10^{5}$) — the number of events. Each of the next $q$ lines contains a single event. The events are given in chronological order. Each event is described as either 1 p x ($1 \le p \le n$, $0 \le x \le 10^{9}$), or 2 x ($0 \le x \le 10^{9}$). In the first case we have a receipt that the balance of the $p$-th person becomes equal to $x$. In the second case we have a payoff with parameter $x$. -----Output----- Print $n$ integers — the balances of all citizens after all events. -----Examples----- Input 4 1 2 3 4 3 2 3 1 2 2 2 1 Output 3 2 3 4 Input 5 3 50 2 1 10 3 1 2 0 2 8 1 3 20 Output 8 8 20 8 10 -----Note----- In the first example the balances change as follows: 1 2 3 4 $\rightarrow$ 3 3 3 4 $\rightarrow$ 3 2 3 4 $\rightarrow$ 3 2 3 4 In the second example the balances change as follows: 3 50 2 1 10 $\rightarrow$ 3 0 2 1 10 $\rightarrow$ 8 8 8 8 10 $\rightarrow$ 8 8 20 8 10
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 make a move, Bessie or Elsie can slide a tile adjacent to the empty cell into the empty cell as shown below: $\rightarrow$ In order to determine if they are truly Best Friends For Life (BFFLs), Bessie and Elsie would like to know if there exists a sequence of moves that takes their puzzles to the same configuration (moves can be performed in both puzzles). Two puzzles are considered to be in the same configuration if each tile is on top of the same grid cell in both puzzles. Since the tiles are labeled with letters, rotations and reflections are not allowed. -----Input----- The first two lines of the input consist of a 2 × 2 grid describing the initial configuration of Bessie's puzzle. The next two lines contain a 2 × 2 grid describing the initial configuration of Elsie's puzzle. The positions of the tiles are labeled 'A', 'B', and 'C', while the empty cell is labeled 'X'. It's guaranteed that both puzzles contain exactly one tile with each letter and exactly one empty position. -----Output----- Output "YES"(without quotes) if the puzzles can reach the same configuration (and Bessie and Elsie are truly BFFLs). Otherwise, print "NO" (without quotes). -----Examples----- Input AB XC XB AC Output YES Input AB XC AC BX Output NO -----Note----- The solution to the first sample is described by the image. All Bessie needs to do is slide her 'A' tile down. In the second sample, the two puzzles can never be in the same configuration. Perhaps Bessie and Elsie are not meant to be friends after all... I tried it in Python, but could not do it. Can you solve it?
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 c = c[1:] + c[0] if flag: print("YES") else: print("NO")
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}+\cdots +A_{x_k} = S. Find the sum of f(T) over all 2^N-1 subsets T of \{1, 2, \ldots , N \}. Since the sum can be enormous, print it modulo 998244353. -----Constraints----- - All values in input are integers. - 1 \leq N \leq 3000 - 1 \leq S \leq 3000 - 1 \leq A_i \leq 3000 -----Input----- Input is given from Standard Input in the following format: N S A_1 A_2 ... A_N -----Output----- Print the sum of f(T) modulo 998244353. -----Sample Input----- 3 4 2 2 4 -----Sample Output----- 6 For each T, the value of f(T) is shown below. The sum of these values is 6. - f(\{1\}) = 0 - f(\{2\}) = 0 - f(\{3\}) = 1 (One subset \{3\} satisfies the condition.) - f(\{1, 2\}) = 1 (\{1, 2\}) - f(\{2, 3\}) = 1 (\{3\}) - f(\{1, 3\}) = 1 (\{3\}) - f(\{1, 2, 3\}) = 2 (\{1, 2\}, \{3\})
#!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[i-ai]*inv) % mod print((dp[-1])) def __starting_point(): resolve() __starting_point()
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.length and do the assignment arr1[i] = arr2[j]. If there is no way to make arr1 strictly increasing, return -1.   Example 1: Input: arr1 = [1,5,3,6,7], arr2 = [1,3,2,4] Output: 1 Explanation: Replace 5 with 2, then arr1 = [1, 2, 3, 6, 7]. Example 2: Input: arr1 = [1,5,3,6,7], arr2 = [4,3,1] Output: 2 Explanation: Replace 5 with 3 and then replace 3 with 4. arr1 = [1, 3, 4, 6, 7]. Example 3: Input: arr1 = [1,5,3,6,7], arr2 = [1,6,3,3] Output: -1 Explanation: You can't make arr1 strictly increasing.   Constraints: 1 <= arr1.length, arr2.length <= 2000 0 <= arr1[i], arr2[i] <= 10^9 I tried it in Python, but could not do it. Can you solve it?
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() for i in range(1, N + 1): for k in range(i + 1): # 前i-1个元素,已经完成了k次交换 if arr1[i] > dp[i-1][k]: dp[i][k] = min(dp[i][k], arr1[i]) # 前 i-1 个元素,已经完成了 k-1次交换,所以这一次一定要交换 if k >= 1: idx_2 = bisect.bisect_right(arr2, dp[i-1][k-1]) if idx_2 != len(arr2): dp[i][k] = min(dp[i][k], arr2[idx_2]) res = float('inf') for i in range(1, N+1): if dp[N][i] != float('inf'): res = min(res, i) return res if res != float('inf') else -1
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=255. * `*`: Add ascii value of **top** element to the output stream. * `[`: Skip past **next** `]` if element value is 0. * `]`: Jump back to the command after **previous** `[` if element value is nonzero. # Syntax and other info * You don't need to add support for nested brackets. * Non-command characters should be ignored. * Code will always have all brackets closed. * Note the highlighted **next** and **previous** in the commands reference. * Program begins with the top element having the value of 0 and being the only element in the stack. * Program ends when command executor reaches the end. # Examples ## Hello,...
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 == '-': stack[0] = 255 if stack[0] == 0 else stack[0] - 1 elif cmd == '*': output += chr(stack.pop(0)) elif cmd == '[' and stack[0] == 0: while tape[i] != ']': i += 1 elif cmd == ']' and stack[0] != 0: while tape[i] != '[': i -= 1 i += 1 return output.replace('\n', '\x02')
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 numpy.mean(my_array, axis = None) #Output : 2.5 print numpy.mean(my_array) #Output : 2.5 By default, the axis is None. Therefore, it computes the mean of the flattened array. var The var tool computes the arithmetic variance along the specified axis. import numpy my_array = numpy.array([ [1, 2], [3, 4] ]) print numpy.var(my_array, axis = 0) #Output : [ 1. 1.] print numpy.var(my_array, axis = 1) #Output : [ 0.25 0.25] print numpy.var(my_array, axis = None) #Output : 1.25 print numpy.var(my_array) #Output : 1.25 By default, the axis is None. Therefore, it computes the variance of the flattened array. std The std tool computes the arithmetic standard deviation along the specified axis. import numpy my_array = numpy.array([ [1, 2], [3, 4] ]) print numpy.std(my_array, axis = 0) #Output : [ 1. 1.] print numpy.std(my_array, axis = 1) #Output : [ 0.5 0.5] print numpy.std(my_array, axis = None) #Output : 1.118033988749895 print numpy.std(my_array) #Output : 1.118033988749895 By default, the axis is None. Therefore, it computes the standard deviation of the flattened array. =====Problem Statement===== You are given a 2-D array of size NXM. Your task is to find: The mean along axis 1 The var along axis 0 The std along axis None =====Input Format===== The first line contains the space separated values of N and M. The next N lines contains M space separated integers. =====Output Format===== First, print the mean. Second, print the var. Third, print the std.
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 task is to calculate the minimum possible instability. -----Input----- The first line of the input contains one integer $n$ ($2 \le n \le 10^5$) — the number of elements in the array $a$. The second line of the input contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 10^5$) — elements of the array $a$. -----Output----- Print one integer — the minimum possible instability of the array if you have to remove exactly one element from the array $a$. -----Examples----- Input 4 1 3 3 7 Output 2 Input 2 1 100000 Output 0 -----Note----- In the first example you can remove $7$ then instability of the remaining array will be $3 - 1 = 2$. In the second example you can remove either $1$ or $100000$ then instability of the remaining array will be $100000 - 100000 = 0$ and $1 - 1 = 0$ correspondingly.
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 restaurant, some of them — in the BeaverKing restaurant, the most successful ones were fast enough to celebrate in both of restaurants. Students which didn't pass the exam didn't celebrate in any of those restaurants and elected to stay home to prepare for their reexamination. However, this quickly bored Vasya and he started checking celebration photos on the Kilogramm. He found out that, in total, BugDonalds was visited by $A$ students, BeaverKing — by $B$ students and $C$ students visited both restaurants. Vasya also knows that there are $N$ students in his group. Based on this info, Vasya wants to determine either if his data contradicts itself or, if it doesn't, how many students in his group didn't pass the exam. Can you help him so he won't waste his valuable preparation time? -----Input----- The first line contains four integers — $A$, $B$, $C$ and $N$ ($0 \leq A, B, C, N \leq 100$). -----Output----- If a distribution of $N$ students exists in which $A$ students visited BugDonalds, $B$ — BeaverKing, $C$ — both of the restaurants and at least one student is left home (it is known that Vasya didn't pass the exam and stayed at home), output one integer — amount of students (including Vasya) who did not pass the exam. If such a distribution does not exist and Vasya made a mistake while determining the numbers $A$, $B$, $C$ or $N$ (as in samples 2 and 3), output $-1$. -----Examples----- Input 10 10 5 20 Output 5 Input 2 2 0 4 Output -1 Input 2 2 2 1 Output -1 -----Note----- The first sample describes following situation: $5$ only visited BugDonalds, $5$ students only visited BeaverKing, $5$ visited both of them and $5$ students (including Vasya) didn't pass the exam. In the second sample $2$...
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 $\frac{n}{2}$ snaps. In one snap, you can remove any two points $a$ and $b$ that have not been removed yet and form a perfectly balanced pair. A pair of points $a$ and $b$ is perfectly balanced if no other point $c$ (that has not been removed yet) lies within the axis-aligned minimum bounding box of points $a$ and $b$. Formally, point $c$ lies within the axis-aligned minimum bounding box of points $a$ and $b$ if and only if $\min(x_a, x_b) \le x_c \le \max(x_a, x_b)$, $\min(y_a, y_b) \le y_c \le \max(y_a, y_b)$, and $\min(z_a, z_b) \le z_c \le \max(z_a, z_b)$. Note that the bounding box might be degenerate. Find a way to remove all points in $\frac{n}{2}$ snaps. -----Input----- The first line contains a single integer $n$ ($2 \le n \le 50\,000$; $n$ is even), denoting the number of points. Each of the next $n$ lines contains three integers $x_i$, $y_i$, $z_i$ ($-10^8 \le x_i, y_i, z_i \le 10^8$), denoting the coordinates of the $i$-th point. No two points coincide. -----Output----- Output $\frac{n}{2}$ pairs of integers $a_i, b_i$ ($1 \le a_i, b_i \le n$), denoting the indices of points removed on snap $i$. Every integer between $1$ and $n$, inclusive, must appear in your output exactly once. We can show that it is always possible to remove all points. If there are many solutions, output any of them. -----Examples----- Input 6 3 1 0 0 3 0 2 2 0 1 0 0 1 3 0 0 1 0 Output 3 6 5 1 2 4 Input 8 0 1 1 1 0 1 1 1 0 1 1 1 2 2 2 3 2 2 2 3 2 2 2 3 Output 4 5 1 6 2 7 3 8 -----Note----- In the first example, here is what points and their corresponding bounding boxes look like (drawn in two dimensions for simplicity, as all points lie on $z = 0$ plane). Note that order of removing matters: for example,...
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.append(points[i]) i+=1 points = list(rem) rem = [] i = 0 while i < len(points): if i < len(points)-1 and points[i][0] == points[i+1][0]: print(points[i][3],points[i+1][3]) i+=2 else: rem.append(points[i]) i+=1 #print(rem) points = list(rem) rem = [] i = 0 while i < len(points)-1: print(points[i][3], points[i+1][3]) i+=2
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 put on his ramen to a clerk. The clerk took a memo of the order as a string S. S is three characters long, and if the first character in S is o, it means the ramen should be topped with boiled egg; if that character is x, it means the ramen should not be topped with boiled egg. Similarly, the second and third characters in S mean the presence or absence of sliced pork and green onions on top of the ramen. Write a program that, when S is given, prints the price of the corresponding bowl of ramen. -----Constraints----- - S is a string of length 3. - Each character in S is o or x. -----Input----- Input is given from Standard Input in the following format: S -----Output----- Print the price of the bowl of ramen corresponding to S. -----Sample Input----- oxo -----Sample Output----- 900 The price of a ramen topped with two kinds of toppings, boiled egg and green onions, is 700 + 100 \times 2 = 900 yen. I tried it in Python, but could not do it. Can you solve it?
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 = 5 + 1 + 2 = 8 and 8^(3) = 512 We need to make a function, ```power_sumDigTerm()```, that receives a number ```n``` and may output the ```n-th term``` of this sequence of numbers. The cases we presented above means that power_sumDigTerm(1) == 81 power_sumDigTerm(2) == 512 Happy coding!
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 the chosen subsequence from $s$ ($s$ can become empty); concatenate chosen subsequence to the right of the string $p$ (in other words, $p = p + s_{i_1}s_{i_2}\dots s_{i_k}$). Of course, initially the string $p$ is empty. For example, let $s = \text{ababcd}$. At first, let's choose subsequence $s_1 s_4 s_5 = \text{abc}$ — we will get $s = \text{bad}$ and $p = \text{abc}$. At second, let's choose $s_1 s_2 = \text{ba}$ — we will get $s = \text{d}$ and $p = \text{abcba}$. So we can build $\text{abcba}$ from $\text{ababcd}$. Can you build a given string $t$ using the algorithm above? -----Input----- The first line contains the single integer $T$ ($1 \le T \le 100$) — the number of test cases. Next $2T$ lines contain test cases — two per test case. The first line contains string $s$ consisting of lowercase Latin letters ($1 \le |s| \le 400$) — the initial string. The second line contains string $t$ consisting of lowercase Latin letters ($1 \le |t| \le |s|$) — the string you'd like to build. It's guaranteed that the total length of strings $s$ doesn't exceed $400$. -----Output----- Print $T$ answers — one per test case. Print YES (case insensitive) if it's possible to build $t$ and NO (case insensitive) otherwise. -----Example----- Input 4 ababcd abcba a b defi fed xyz x Output YES NO NO YES I tried it in Python, but could not do it. Can you solve it?
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 def interleaving(a, b): dp = [n] * (len(b) + 1) for i in range(len(a) + 1): for j in range(len(b) + 1): if i == j == 0: dp[j] = -1 continue res = n if i > 0: res = min(res, find[dp[j] + 1][ord(a[i - 1]) - ord("a")]) if j > 0: res = min(res, find[dp[j - 1] + 1][ord(b[j - 1]) - ord("a")]) dp[j] = res return dp[-1] < n if any(interleaving(t[:i], t[i:]) for i in range(len(t))): print("YES") else: print("NO") main()
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 the lotus at coordinate 0. You will play a game that proceeds as follows: - 1. Choose positive integers A and B. Your score is initially 0. - 2. Let x be your current coordinate, and y = x+A. The lotus at coordinate x disappears, and you move to coordinate y. - If y = N-1, the game ends. - If y \neq N-1 and there is a lotus floating at coordinate y, your score increases by s_y. - If y \neq N-1 and there is no lotus floating at coordinate y, you drown. Your score decreases by 10^{100} points, and the game ends. - 3. Let x be your current coordinate, and y = x-B. The lotus at coordinate x disappears, and you move to coordinate y. - If y = N-1, the game ends. - If y \neq N-1 and there is a lotus floating at coordinate y, your score increases by s_y. - If y \neq N-1 and there is no lotus floating at coordinate y, you drown. Your score decreases by 10^{100} points, and the game ends. - 4. Go back to step 2. You want to end the game with as high a score as possible. What is the score obtained by the optimal choice of A and B? -----Constraints----- - 3 \leq N \leq 10^5 - -10^9 \leq s_i \leq 10^9 - s_0=s_{N-1}=0 - All values in input are integers. -----Input----- Input is given from Standard Input in the following format: N s_0 s_1 ...... s_{N-1} -----Output----- Print the score obtained by the optimal choice of A and B. -----Sample Input----- 5 0 2 5 1 0 -----Sample Output----- 3 If you choose A = 3 and B = 2, the game proceeds as follows: - Move to coordinate 0 + 3 = 3. Your score increases by s_3 = 1. - Move to coordinate 3 - 2 = 1. Your score increases by s_1 = 2. - Move to coordinate 1 + 3 = 4. The game ends with a score of 3. There is no way to end the game with a score of 4 or higher, so the answer is 3. Note that you cannot land the lotus at coordinate 2... I tried it in Python, but could not do it. Can you solve it?
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 print(ans)
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 result should be padded with empty elements. ``` ```if: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 result should be padded with `nil`s. ``` Examples: ```python interleave([1, 2, 3], ["c", "d", "e"]) == [1, "c", 2, "d", 3, "e"] interleave([1, 2, 3], [4, 5]) == [1, 4, 2, 5, 3, None] interleave([1, 2, 3], [4, 5, 6], [7, 8, 9]) == [1, 4, 7, 2, 5, 8, 3, 6, 9] interleave([]) == [] ``` I tried it in Python, but could not do it. Can you solve it?
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 at least one of the simple paths between $a$ and $b$, $b$ and $c$, or $a$ and $c$ is the maximum possible. See the notes section for a better understanding. The simple path is the path that visits each vertex at most once. -----Input----- The first line contains one integer number $n$ ($3 \le n \le 2 \cdot 10^5$) — the number of vertices in the tree. Next $n - 1$ lines describe the edges of the tree in form $a_i, b_i$ ($1 \le a_i$, $b_i \le n$, $a_i \ne b_i$). It is guaranteed that given graph is a tree. -----Output----- In the first line print one integer $res$ — the maximum number of edges which belong to at least one of the simple paths between $a$ and $b$, $b$ and $c$, or $a$ and $c$. In the second line print three integers $a, b, c$ such that $1 \le a, b, c \le n$ and $a \ne, b \ne c, a \ne c$. If there are several answers, you can print any. -----Example----- Input 8 1 2 2 3 3 4 4 5 4 6 3 7 3 8 Output 5 1 8 6 -----Note----- The picture corresponding to the first example (and another one correct answer): [Image] If you choose vertices $1, 5, 6$ then the path between $1$ and $5$ consists of edges $(1, 2), (2, 3), (3, 4), (4, 5)$, the path between $1$ and $6$ consists of edges $(1, 2), (2, 3), (3, 4), (4, 6)$ and the path between $5$ and $6$ consists of edges $(4, 5), (4, 6)$. The union of these paths is $(1, 2), (2, 3), (3, 4), (4, 5), (4, 6)$ so the answer is $5$. It can be shown that there is no better answer. I tried it in Python, but could not do it. Can you solve it?
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 = dq.popleft() last = v for dest in adj[v]: if prev[dest] > -1: continue prev[dest] = v dq.append(dest) return last, prev v1, _ = rec(0) v2, prev = rec(v1) v = prev[v2] visited = [0]*n visited[v] = visited[v1] = visited[v2] = 1 dia = 0 max_e, max_e_i = 0, v while v != inf: dia += 1 if prev[v] != inf: visited[prev[v]] = 1 stack = [(v, 0)] while stack: cv, e = stack.pop() if max_e < e: max_e, max_e_i = e, cv e += 1 for dest in adj[cv]: if visited[dest]: continue visited[dest] = 1 stack.append((dest, e)) v = prev[v] print(dia + max_e) print(v1+1, v2+1, max_e_i+1)
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 array.
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 number of the pairs (l, r) that satisfy the following: - l and r are both integers and satisfy 1 \leq l \leq r \leq N. - A_l + A_{l+1} + ... + A_r is a multiple of M. -----Constraints----- - All values in input are integers. - 1 \leq N \leq 10^5 - 2 \leq M \leq 10^9 - 1 \leq A_i \leq 10^9 -----Input----- Input is given from Standard Input in the following format: N M A_1 A_2 ... A_N -----Output----- Print the number of the pairs (l, r) that satisfy the conditions. Note that the number may not fit into a 32-bit integer type. -----Sample Input----- 3 2 4 1 5 -----Sample Output----- 3 The sum A_l + A_{l+1} + ... + A_r for each pair (l, r) is as follows: - Sum for (1, 1): 4 - Sum for (1, 2): 5 - Sum for (1, 3): 10 - Sum for (2, 2): 1 - Sum for (2, 3): 6 - Sum for (3, 3): 5 Among these, three are multiples of 2. I tried it in Python, but could not do it. Can you solve it?
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 third — with the fourth, the fifth — with the sixth, and so on. It is guaranteed that in each round there is even number of teams. The winner of each game advances to the next round, the loser is eliminated from the tournament, there are no draws. In the last round there is the only game with two remaining teams: the round is called the Final, the winner is called the champion, and the tournament is over. Arkady wants his two favorite teams to play in the Final. Unfortunately, the team ids are already determined, and it may happen that it is impossible for teams to meet in the Final, because they are to meet in some earlier stage, if they are strong enough. Determine, in which round the teams with ids a and b can meet. -----Input----- The only line contains three integers n, a and b (2 ≤ n ≤ 256, 1 ≤ a, b ≤ n) — the total number of teams, and the ids of the teams that Arkady is interested in. It is guaranteed that n is such that in each round an even number of team advance, and that a and b are not equal. -----Output----- In the only line print "Final!" (without quotes), if teams a and b can meet in the Final. Otherwise, print a single integer — the number of the round in which teams a and b can meet. The round are enumerated from 1. -----Examples----- Input 4 1 2 Output 1 Input 8 2 6 Output Final! Input 8 7 5 Output 2 -----Note----- In the first example teams 1 and 2 meet in the first round. In the second example teams 2 and 6 can only meet in the third round, which is the Final, if they win all their opponents in earlier rounds. In the third example the teams with ids 7 and 5 can meet in the second round, if they win their opponents in the first round.
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 Bob. Given an array edges where edges[i] = [typei, ui, vi] represents a bidirectional edge of type typei between nodes ui and vi, find the maximum number of edges you can remove so that after removing the edges, the graph can still be fully traversed by both Alice and Bob. The graph is fully traversed by Alice and Bob if starting from any node, they can reach all other nodes. Return the maximum number of edges you can remove, or return -1 if it's impossible for the graph to be fully traversed by Alice and Bob.   Example 1: Input: n = 4, edges = [[3,1,2],[3,2,3],[1,1,3],[1,2,4],[1,1,2],[2,3,4]] Output: 2 Explanation: If we remove the 2 edges [1,1,2] and [1,1,3]. The graph will still be fully traversable by Alice and Bob. Removing any additional edge will not make it so. So the maximum number of edges we can remove is 2. Example 2: Input: n = 4, edges = [[3,1,2],[3,2,3],[1,1,4],[2,1,4]] Output: 0 Explanation: Notice that removing any edge will not make the graph fully traversable by Alice and Bob. Example 3: Input: n = 4, edges = [[3,2,3],[1,1,2],[2,3,4]] Output: -1 Explanation: In the current graph, Alice cannot reach node 4 from the other nodes. Likewise, Bob cannot reach 1. Therefore it's impossible to make the graph fully traversable.     Constraints: 1 <= n <= 10^5 1 <= edges.length <= min(10^5, 3 * n * (n-1) / 2) edges[i].length == 3 1 <= edges[i][0] <= 3 1 <= edges[i][1] < edges[i][2] <= n All tuples (typei, ui, vi) are distinct. I tried it in Python, but could not do it. Can you solve it?
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) yr = self.find(y) self.dsu[yr] = xr return class Solution: def maxNumEdgesToRemove(self, n: int, edges: List[List[int]]) -> int: alice = [] bob = [] both = [] for t, x, y in edges: if t == 1: alice.append((x, y)) elif t == 2: bob.append((x, y)) else: both.append((x, y)) dsu = DSU(n) counter3 = 0 for x, y in both: if dsu.find(x) == dsu.find(y): continue dsu.union(x, y) counter3 += 1 dsu1 = deepcopy(dsu) counter1 = 0 for x, y in alice: if dsu1.find(x) == dsu1.find(y): continue dsu1.union(x, y) counter1 += 1 # print(dsu1.dsu) dsu2 = deepcopy(dsu) counter2 = 0 for x, y in bob: if dsu2.find(x) == dsu2.find(y): continue dsu2.union(x, y) counter2 += 1 # print(dsu2.dsu) if counter1 + counter3 != n-1 or counter2 + counter3 != n-1: return -1 else: return len(edges) + counter3 - 2*n +2
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 he will pick the word which contains the smallest number of characters from the lyrics of the song, and then he will append that word to the start and end of the lyrics, also Chef will insert this word between every two words of the lyrics. Note: While inserting a new word Chef will also insert extra white-spaces, so that every word in the final remixed lyrics is separated by space. It is Recommended to use fast Input/Ouput techniques. -----Input:----- - The input contains the text $S$, which denotes the lyrics of the song. -----Output:----- - Print the Remixed, lyrics as done by Chef. -----Constraints:----- - $1 \leq Length of text $S$ \leq 10^7$ -----Sample Input:----- Mai Hu Jiyaan -----Sample Output:----- Hu Mai Hu Hu Hu Jiyaan Hu
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$ students (numbered $1$ through $N$) in his class; for some reason, this number is always a multiple of $4$. The final exam has finished and Khaled has all the scores of his $N$ students. For each valid $i$, the score of the $i$-th student is $A_i$; each score is an integer between $0$ and $100$. Currently, the score-grade distribution is as follows: - grade D for score smaller than $60$ - grade C for score greater or equal to $60$, but smaller than $75$ - grade B for score greater or equal to $75$, but smaller than $90$ - grade A for score greater or equal to $90$ However, coach Khaled is not satisfied with this. He wants exactly $N/4$ students to receive each grade (A, B, C and D), so that the grades are perfectly balanced. The scores cannot be changed, but the boundaries between grades can. Therefore, he wants to choose three integers $x$, $y$ and $z$ and change the grade distribution to the following (note that initially, $x = 60$, $y = 75$ and $z = 90$): - grade D for score smaller than $x$ - grade C for score greater or equal to $x$, but smaller than $y$ - grade B for score greater or equal to $y$, but smaller than $z$ - grade A for score greater or equal to $z$ Your task is to find thresholds $x$, $y$ and $z$ that result in a perfect balance of grades. If there are multiple solutions, choose the one with the maximum value of $x+y+z$ (because coach Khaled wants seem smarter than his students); it can be proved that there is at most one such solution. Sometimes, there is no way to choose the thresholds and coach Khaled would resign because his exam questions were low-quality. -----Input----- - The first line of the input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows. - The first line of each test case... I tried it in Python, but could not do it. Can you solve it?
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 / \ a t To scramble the string, we may choose any non-leaf node and swap its two children. For example, if we choose the node "gr" and swap its two children, it produces a scrambled string "rgeat". rgeat / \ rg eat / \ / \ r g e at / \ a t We say that "rgeat" is a scrambled string of "great". Similarly, if we continue to swap the children of nodes "eat" and "at", it produces a scrambled string "rgtae". rgtae / \ rg tae / \ / \ r g ta e / \ t a We say that "rgtae" is a scrambled string of "great". Given two strings s1 and s2 of the same length, determine if s2 is a scrambled string of s1. Example 1: Input: s1 = "great", s2 = "rgeat" Output: true Example 2: Input: s1 = "abcde", s2 = "caebd" Output: false I tried it in Python, but could not do it. Can you solve it?
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) - i]): return True return False
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 element, each element except the last has exactly one next element. The list is not closed in a cycle. In this problem you are given n memory cells forming one or more doubly linked lists. Each cell contains information about element from some list. Memory cells are numbered from 1 to n. For each cell i you are given two values: l_{i} — cell containing previous element for the element in the cell i; r_{i} — cell containing next element for the element in the cell i. If cell i contains information about the element which has no previous element then l_{i} = 0. Similarly, if cell i contains information about the element which has no next element then r_{i} = 0. [Image] Three lists are shown on the picture. For example, for the picture above the values of l and r are the following: l_1 = 4, r_1 = 7; l_2 = 5, r_2 = 0; l_3 = 0, r_3 = 0; l_4 = 6, r_4 = 1; l_5 = 0, r_5 = 2; l_6 = 0, r_6 = 4; l_7 = 1, r_7 = 0. Your task is to unite all given lists in a single list, joining them to each other in any order. In particular, if the input data already contains a single list, then there is no need to perform any actions. Print the resulting list in the form of values l_{i}, r_{i}. Any other action, other than joining the beginning of one list to the end of another, can not be performed. -----Input----- The first line contains a single integer n (1 ≤ n ≤ 100) — the number of memory cells where the doubly linked lists are located. Each of the following n lines contains two integers l_{i}, r_{i} (0 ≤ l_{i}, r_{i} ≤ n) — the cells of the previous and the next element of list for cell i. Value l_{i} = 0 if element in cell i has no previous element in its list. Value r_{i} = 0 if element in cell i has no next element in...
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 testcases.   Example 1: Input: s = "1101" Output: 6 Explanation: "1101" corressponds to number 13 in their decimal representation. Step 1) 13 is odd, add 1 and obtain 14.  Step 2) 14 is even, divide by 2 and obtain 7. Step 3) 7 is odd, add 1 and obtain 8. Step 4) 8 is even, divide by 2 and obtain 4.  Step 5) 4 is even, divide by 2 and obtain 2.  Step 6) 2 is even, divide by 2 and obtain 1.  Example 2: Input: s = "10" Output: 1 Explanation: "10" corressponds to number 2 in their decimal representation. Step 1) 2 is even, divide by 2 and obtain 1.  Example 3: Input: s = "1" Output: 0   Constraints: 1 <= s.length <= 500 s consists of characters '0' or '1' s[0] == '1'
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 UFDS to take over the world! But Kim doesn't know where the base is located. He knows that the base is on the highest peak of the Himalayan Mountains. He also knows the heights of each of the $N$ mountains. Can you help Kim find the height of the mountain where the base is located? -----Input:----- - First line will contain $T$, number of testcases. Then the testcases follow. - The first line in each testcase contains one integer, $N$. - The following $N$ lines of each test case each contain one integer: the height of a new mountain. -----Output:----- For each testcase, output one line with one integer: the height of the tallest mountain for that test case. -----Constraints----- - $1 \leq T \leq 10$ - $1 \leq N \leq 100000$ - $0 \leq$ height of each mountain $\leq 10^9$ -----Subtasks:----- - 100 points: No additional constraints. -----Sample Input:----- 1 5 4 7 6 3 1 -----Sample Output:----- 7 I tried it in Python, but could not do it. Can you solve it?
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 displayed as either "Pass" or "Fail" behind their magic jacket which they wore. A student cannot see his/her result but can see everyone else's results. Each of $N$ students count the number of passed students they can see. Given the number of "Pass" verdicts that each of the $N$ students counted, we have to figure out conclusively, the number of students who failed, or report that there is some inconsistency or that we cannot be sure. -----Input:----- - First line will contain $T$, number of testcases. Then the testcases follow. - The first line of each test case will contain $N$, representing the number of students who attended the exam. - Next line contains $N$ spaced integers representing the number of "Pass" counted by each of the $N$ students. -----Output:----- - For each test case, output the answer in a single line. - If the counts reported by the students are not consistent with each other or if it's not possible to predict the number of failed students from the given input, then print -1. -----Constraints----- - $1 \leq T \leq 50$ - $1 \leq N \leq 10^{5}$ - $0 \leq$ Count given by each Student $\leq 10^{5}$ -----Sample Input:----- 1 4 3 2 2 2 -----Sample Output:----- 1 -----EXPLANATION:----- There are 4 students, and they counted the number of passed students as 3,2,2,2. The first student can see that all others have passed, and all other students can see only 2 students who have passed. Hence, the first student must have failed, and others have all passed. Hence, the answer is 1. I tried it in Python, but could not do it. Can you solve it?
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_number) is always 0 or 1 if max_number < number_of_students and min_number > -1 and \ abs(max_number - min_number) <= 1: #can't see himself sum_of_values = sum(list_of_numbers) if number_of_students == 1: print(-1) elif (sum_of_values%(number_of_students-1)) != 0: print(-1) else: print(number_of_students-(sum_of_values//(number_of_students-1))) else: print(-1)
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 ``` digitsAverage(246) ==> 4 original: 2 4 6 \ / \ / 1st iter: 3 5 \ / 2nd iter: 4 digitsAverage(89) ==> 9 original: 8 9 \ / 1st iter: 9 ``` p.s. for a bigger challenge, check out the [one line version](https://www.codewars.com/kata/one-line-task-digits-average) of this kata by myjinxin2015!
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 the number $x$ by $2$. After each operation, Polycarp writes down the result on the board and replaces $x$ by the result. So there will be $n$ numbers on the board after all. You are given a sequence of length $n$ — the numbers that Polycarp wrote down. This sequence is given in arbitrary order, i.e. the order of the sequence can mismatch the order of the numbers written on the board. Your problem is to rearrange (reorder) elements of this sequence in such a way that it can match possible Polycarp's game in the order of the numbers written on the board. I.e. each next number will be exactly two times of the previous number or exactly one third of previous number. It is guaranteed that the answer exists. -----Input----- The first line of the input contatins an integer number $n$ ($2 \le n \le 100$) — the number of the elements in the sequence. The second line of the input contains $n$ integer numbers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 3 \cdot 10^{18}$) — rearranged (reordered) sequence that Polycarp can wrote down on the board. -----Output----- Print $n$ integer numbers — rearranged (reordered) input sequence that can be the sequence that Polycarp could write down on the board. It is guaranteed that the answer exists. -----Examples----- Input 6 4 8 6 3 12 9 Output 9 3 6 12 4 8 Input 4 42 28 84 126 Output 126 42 84 28 Input 2 1000000000000000000 3000000000000000000 Output 3000000000000000000 1000000000000000000 -----Note----- In the first example the given sequence can be rearranged in the following way: $[9, 3, 6, 12, 4, 8]$. It can match possible Polycarp's game which started with $x = 9$. I tried it in Python, but could not do it. Can you solve it?
# 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] return r for i in a: if sorted( [i]+func(i)) == sorted(a): print (' '.join(map(str, [i]+func(i))))
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` is the common ratio of the sequence (calculated by dividing one term in the sequence by the previous term) For example: `1 + 0.5 + 0.25 + 0.125 + ... = 2` Your challenge is to calculate the sum to infinity of the given sequence. The solution must be rounded to 3 decimal places. If there are no solutions, for example if `r` is out of the above boundaries, return `"No Solutions"`. Hope you enjoy, let me know of any issues or improvements! I tried it in Python, but could not do it. Can you solve it?
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 find their sum of digits. -----Input----- N : number of inputs N<=100 then N lines with input T<=2000 -----Output----- The output for the corresponding input T -----Example----- Input: 3 5 10 4 Output: 5 7 7 Explanation: 2^5=32 3+2=5 2^10=1024 1+0+2+4=7 2^4=16 1+6=7
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 will pay your mortgage?! To offset this risk, you decide that rather than leaving work totally, you will request a sabbatical so that you can go back to work post bootcamp and be paid while you look for your next role. You need to approach your boss. Her decision will be based on three parameters: val=your value to the organisation happiness=her happiness level at the time of asking and finally The numbers of letters from 'sabbatical' that are present in string `s`. Note that if `s` contains three instances of the letter 'l', that still scores three points, even though there is only one in the word sabbatical. If the sum of the three parameters (as described above) is > 22, return 'Sabbatical! Boom!', else return 'Back to your desk, boy.'. ~~~if:c NOTE: For the C translation you should return a string literal. ~~~
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 square as well). Applejack will build the storages using planks, she is going to spend exactly one plank on each side of the storage. She can get planks from her friend's company. Initially, the company storehouse has $n$ planks, Applejack knows their lengths. The company keeps working so it receives orders and orders the planks itself. Applejack's friend can provide her with information about each operation. For convenience, he will give her information according to the following format: $+$ $x$: the storehouse received a plank with length $x$ $-$ $x$: one plank with length $x$ was removed from the storehouse (it is guaranteed that the storehouse had some planks with length $x$). Applejack is still unsure about when she is going to order the planks so she wants to know if she can order the planks to build rectangular and square storages out of them after every event at the storehouse. Applejack is busy collecting apples and she has completely no time to do the calculations so she asked you for help! We remind you that all four sides of a square are equal, and a rectangle has two pairs of equal sides. -----Input----- The first line contains a single integer $n$ ($1 \le n \le 10^5$): the initial amount of planks at the company's storehouse, the second line contains $n$ integers $a_1, a_2, \ldots, a_n$ ($1 \le a_i \le 10^5$): the lengths of the planks. The third line contains a single integer $q$ ($1 \le q \le 10^5$): the number of events in the company. Each of the next $q$ lines contains a description of the events in a given format: the type of the event (a symbol $+$ or $-$) is given first, then goes the integer $x$ ($1 \le x \le 10^5$). -----Output----- After every event in the company, print...
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: d[l]+=1 else: d[l]=1 if d[l]%2==0: two+=1 if d[l]%4==0: four+=1 else: l=int(s[1]) d[l]-=1 if d[l]%2==1: two-=1 if d[l]%4==3: four-=1 if four>0 and two>3: print("YES") else: print("NO")
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 $s$ of length $m$ and $t$ is a string $t + s_1 + t + s_2 + \ldots + t + s_m + t$, where $s_i$ denotes the $i$-th symbol of the string $s$, and "+" denotes string concatenation. For example, the product of strings "abc" and "de" is a string "deadebdecde", while the product of the strings "ab" and "z" is a string "zazbz". Note, that unlike the numbers multiplication, the product of strings $s$ and $t$ is not necessarily equal to product of $t$ and $s$. Roman was jealous of Denis, since he invented such a cool operation, and hence decided to invent something string-related too. Since Roman is beauty-lover, he decided to define the beauty of the string as the length of the longest substring, consisting of only one letter. For example, the beauty of the string "xayyaaabca" is equal to $3$, since there is a substring "aaa", while the beauty of the string "qwerqwer" is equal to $1$, since all neighboring symbols in it are different. In order to entertain Roman, Denis wrote down $n$ strings $p_1, p_2, p_3, \ldots, p_n$ on the paper and asked him to calculate the beauty of the string $( \ldots (((p_1 \cdot p_2) \cdot p_3) \cdot \ldots ) \cdot p_n$, where $s \cdot t$ denotes a multiplication of strings $s$ and $t$. Roman hasn't fully realized how Denis's multiplication works, so he asked you for a help. Denis knows, that Roman is very impressionable, he guarantees, that the beauty of the resulting string is at most $10^9$. -----Input----- The first line contains a single integer $n$ ($2 \leq n \leq 100\,000$) — the number of strings, wroted by Denis. Next $n$ lines contain non-empty strings $p_1, p_2, \ldots, p_n$, consisting of lowercase english letters. It's guaranteed, that the total length of the strings $p_i$...
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 s = list(minp()) l = len(s) q = 0 while i < l: j = i + 1 while j < l and s[j] == s[i]: j += 1 z = ord(s[i]) w = j-i if i == 0: q = w if j == l: w += (w+1)*a[z] elif a[z] != 0: w += 1 elif j == l: w += 1 if s[0] == s[-1]: w += q b[z] = max(b[z], w) i = j a,b = b,a print(max(a))
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 number of the column (in a classical game the columns are traditionally indexed by letters). Each chess piece takes up exactly one field. To make a move is to move a chess piece, the pieces move by the following rules: A rook moves any number of fields horizontally or vertically. A bishop moves any number of fields diagonally. A king moves one field in any direction — horizontally, vertically or diagonally. [Image] The pieces move like that Petya is thinking about the following problem: what minimum number of moves is needed for each of these pieces to move from field (r_1, c_1) to field (r_2, c_2)? At that, we assume that there are no more pieces besides this one on the board. Help him solve this problem. -----Input----- The input contains four integers r_1, c_1, r_2, c_2 (1 ≤ r_1, c_1, r_2, c_2 ≤ 8) — the coordinates of the starting and the final field. The starting field doesn't coincide with the final one. You can assume that the chessboard rows are numbered from top to bottom 1 through 8, and the columns are numbered from left to right 1 through 8. -----Output----- Print three space-separated integers: the minimum number of moves the rook, the bishop and the king (in this order) is needed to move from field (r_1, c_1) to field (r_2, c_2). If a piece cannot make such a move, print a 0 instead of the corresponding number. -----Examples----- Input 4 3 1 6 Output 2 1 3 Input 5 5 5 6 Output 1 0 1
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 coins, a question came to her mind: after giving the coins to Arya, what values does Arya can make with them? She is jealous and she doesn't want Arya to make a lot of values. So she wants to know all the values x, such that Arya will be able to make x using some subset of coins with the sum k. Formally, Pari wants to know the values x such that there exists a subset of coins with the sum k such that some subset of this subset has the sum x, i.e. there is exists some way to pay for the chocolate, such that Arya will be able to make the sum x using these coins. -----Input----- The first line contains two integers n and k (1 ≤ n, k ≤ 500) — the number of coins and the price of the chocolate, respectively. Next line will contain n integers c_1, c_2, ..., c_{n} (1 ≤ c_{i} ≤ 500) — the values of Pari's coins. It's guaranteed that one can make value k using these coins. -----Output----- First line of the output must contain a single integer q— the number of suitable values x. Then print q integers in ascending order — the values that Arya can make for some subset of coins of Pari that pays for the chocolate. -----Examples----- Input 6 18 5 6 1 10 12 2 Output 16 0 1 2 3 5 6 7 8 10 11 12 13 15 16 17 18 Input 3 50 25 25 50 Output 3 0 25 50 I tried it in Python, but could not do it. Can you solve it?
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 sub-subset 0 using 0 coins. table[0][0] = 1 for i, c in enumerate(cs,1): for s in range(k+1): # Include the coin in neither subset nor sub-subset. table[i%2][s] |= table[(i-1)%2][s] if c <= s: # Include the coin in subset but not sub-subset. table[i%2][s] |= table[(i-1)%2][s-c] # Include the coin in both the subset and sub-subset. table[i%2][s] |= (table[(i-1)%2][s-c] << c) possible = [str(i) for i in range(k+1) if (table[n%2][k] >> i) & 1] print(len(possible)) print(*possible)
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 off"). Unfortunately, some program is already installed into the lamp. The lamp allows only good programs. Good program can be represented as a non-empty array $a$, where $0 < a_1 < a_2 < \dots < a_{|a|} < M$. All $a_i$ must be integers. Of course, preinstalled program is a good program. The lamp follows program $a$ in next manner: at moment $0$ turns power and light on. Then at moment $a_i$ the lamp flips its state to opposite (if it was lit, it turns off, and vice versa). The state of the lamp flips instantly: for example, if you turn the light off at moment $1$ and then do nothing, the total time when the lamp is lit will be $1$. Finally, at moment $M$ the lamp is turning its power off regardless of its state. Since you are not among those people who read instructions, and you don't understand the language it's written in, you realize (after some testing) the only possible way to alter the preinstalled program. You can insert at most one element into the program $a$, so it still should be a good program after alteration. Insertion can be done between any pair of consecutive elements of $a$, or even at the begining or at the end of $a$. Find such a way to alter the program that the total time when the lamp is lit is maximum possible. Maybe you should leave program untouched. If the lamp is lit from $x$ till moment $y$, then its lit for $y - x$ units of time. Segments of time when the lamp is lit are summed up. -----Input----- First line contains two space separated integers $n$ and $M$ ($1 \le n \le 10^5$, $2 \le M \le 10^9$) — the length of program $a$ and the moment when power turns off. Second line contains $n$ space separated integers $a_1, a_2, \dots, a_n$ ($0 < a_1 < a_2 < \dots < a_n < M$) —...
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[i+1] - a[i] != 1: to_add = a[i+1] - 1 # added in pos between i and i+1 s_ = incr_sum[i] s_ += to_add - a[i] s_ += (a[-1] - a[i+1]) - (incr_sum[-1] - incr_sum[i+1]) if s_ > max_sum: max_sum = s_ print(max_sum) def __starting_point(): main() __starting_point()
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 country can be represented by a network of unidirectional roads between the cities. But Mancunian, our benign monarch, has a headache. The road network of the country is not tourist-friendly and this is affecting revenue. To increase the GDP of the nation, he wants to redirect some of the roads to make the road network tourist-friendly and hence, ensure happiness and prosperity for his loyal subjects. Now is the time for some formal definitions. :( A road network is said to be tourist-friendly if for every city in the country, if a tourist starts his journey there, there is a path she can take to visit each and every city of the nation and traverse each road exactly once before ending up at the city where she started. Given a description of the road network of Mancunia, can you come up with a scheme to redirect some (possibly none) of the roads to make it tourist-friendly? -----Input----- The first line contains two integers N and E denoting the number of cities and roads in the beautiful country of Mancunia respectively. Each of the next E lines contains two integers a and b implying that there is a unidirectional road from city a to city b. It is guaranteed that there aren't multiple roads in the exact same direction and that there is no road from a city to itself. -----Output----- If there is no solution, print "NO" (without quotes). Else, print "YES" (without quotes), followed by exactly E lines. The ith line of output should represent the ith road in the input. It should have two integers a and b denoting that the final orientation of that road is from a to b. -----Constraints----- - 1 ≤ N ≤ 100000 - 1 ≤ E ≤ 200000 - 1 ≤ a, b ≤ N Subtask 1: (20 points) - 1 ≤ N ≤ 20 - 1 ≤ E ≤ 21 Subtask 2: (80 points) - Same as original constraints -----Example 1----- Input: 3... I tried it in Python, but could not do it. Can you solve it?
# 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.graph odd = [k for k, v in g.items() if len(v)%2 == 1] if len(odd) == 0 : odd = [list(g.keys())[0]] elif len(odd) == 1 or len(odd) > 2 : return None path = [] stack = [odd[-1]] while stack: u = stack[-1] if g[u]: v = g[u][0] del g[u][0] del g[v][g[v].index(u)] stack.append(v) else: path.append(stack.pop()) return path n, e = map(int, sys.stdin.readline().strip().split()) g = Graph(n) u = [] v = [] for i in range(e): a, b = map(int, sys.stdin.readline().strip().split()) g.add_edge(a,b) u.append(a) v.append(b) ans = g.eulerPath() if ans is None: print('NO') else: if len(ans) == (e+1) and ans[0] == ans[-1]: print("YES") temp = defaultdict(defaultdict) for i in range(len(ans)-1, 0, -1): temp[ans[i]][ans[i - 1]] = True for i in range(e): if u[i] in temp and v[i] in temp[u[i]]: print(u[i], v[i]) else: print(v[i], u[i]) else: print("NO")
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, the i-th person kills the j-th person if and only if j < i and j ≥ i - L_{i}. You are given lengths of the claws. You need to find the total number of alive people after the bell rings. -----Input----- The first line contains one integer n (1 ≤ n ≤ 10^6) — the number of guilty people. Second line contains n space-separated integers L_1, L_2, ..., L_{n} (0 ≤ L_{i} ≤ 10^9), where L_{i} is the length of the i-th person's claw. -----Output----- Print one integer — the total number of alive people after the bell rings. -----Examples----- Input 4 0 1 0 10 Output 1 Input 2 0 0 Output 2 Input 10 1 1 3 0 0 0 2 1 0 3 Output 3 -----Note----- In first sample the last person kills everyone in front of him. I tried it in Python, but could not do it. Can you solve it?
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. All strings that can be obtained in this way can be evaluated as formulas. Evaluate all possible formulas, and print the sum of the results. -----Constraints----- - 1 \leq |S| \leq 10 - All letters in S are digits between 1 and 9, inclusive. -----Input----- The input is given from Standard Input in the following format: S -----Output----- Print the sum of the evaluated value over all possible formulas. -----Sample Input----- 125 -----Sample Output----- 176 There are 4 formulas that can be obtained: 125, 1+25, 12+5 and 1+2+5. When each formula is evaluated, - 125 - 1+25=26 - 12+5=17 - 1+2+5=8 Thus, the sum is 125+26+17+8=176. I tried it in Python, but could not do it. Can you solve it?
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 person he knows subject $s_i$ the candidate specializes in and $r_i$ — a skill level in his specialization (this level can be negative!). The rules of the competition require each delegation to choose some subset of subjects they will participate in. The only restriction is that the number of students from the team participating in each of the chosen subjects should be the same. Alex decided that each candidate would participate only in the subject he specializes in. Now Alex wonders whom he has to choose to maximize the total sum of skill levels of all delegates, or just skip the competition this year if every valid non-empty delegation has negative sum. (Of course, Alex doesn't have any spare money so each delegate he chooses must participate in the competition). -----Input----- The first line contains two integers $n$ and $m$ ($1 \le n \le 10^5$, $1 \le m \le 10^5$) — the number of candidates and the number of subjects. The next $n$ lines contains two integers per line: $s_i$ and $r_i$ ($1 \le s_i \le m$, $-10^4 \le r_i \le 10^4$) — the subject of specialization and the skill level of the $i$-th candidate. -----Output----- Print the single integer — the maximum total sum of skills of delegates who form a valid delegation (according to rules above) or $0$ if every valid non-empty delegation has negative sum. -----Examples----- Input 6 3 2 6 3 6 2 5 3 5 1 9 3 1 Output 22 Input 5 3 2 6 3 6 2 5 3 5 1 11 Output 23 Input 5 2 1 -1 1 -5 2 -1 2 -1 1 -10 Output 0 -----Note----- In the first example it's optimal to choose candidates $1$, $2$, $3$, $4$, so two of them specialize in the $2$-nd subject and other two in the $3$-rd. The total sum is $6 + 6 + 5 + 5 = 22$. In the second example it's optimal to choose candidates $1$, $2$ and $5$. One person in each... I tried it in Python, but could not do it. Can you solve it?
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] += next(inp1[i]) if curs[i] < 0: raise StopIteration cur += curs[i] i += 1 except StopIteration: m -= 1 try: inp1[i] = inp1.pop() except IndexError: pass try: curs[i] = curs.pop() except IndexError: pass res = max(res, cur) print(res)
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, ...` (sequence A007629 in the OEIS) Keith numbers were introduced by Mike Keith in 1987. They are computationally very challenging to find, with only about 100 known. Implement the code to check if the given number is a Keith number. Return the number number of iteration needed to confirm it; otherwise return `false`. **Note:** 1-digit numbers are **not** Keith numbers by definition ## Examples ``` n = 197 # --> [1, 9, 7] # calculation iteration 1 + 9 + 7 = 17 # 1 9 + 7 + 17 = 33 # 2 7 + 17 + 33 = 57 # 3 17 + 33 + 57 = 107 # 4 33 + 57 + 107 = 197 # 5 ``` As `197` is the same as the initial number, so it's a Keith number: return `5` Another example: ``` n = 196 # calculation iteration 1 + 9 + 6 = 16 # 1 ... ``` `196` is not a Keith number, so return `false`
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 the same difference, choose the one "Zamalek" scored more goals in. Given the information about all matches they played, return the `index` of the best match (`0-based`). If more than one valid result, return the smallest index. # Example For `ALAHLYGoals = [6,4] and zamalekGoals = [1,2]`, the output should be 1. Because `4 - 2` is less than `6 - 1` For `ALAHLYGoals = [1,2,3,4,5] and zamalekGoals = [0,1,2,3,4]`, the output should be 4. The goal difference of all matches are 1, but at 4th match "Zamalek" scored more goals in. So the result is `4`. # Input/Output - `[input]` integer array `ALAHLYGoals` The number of goals "AL-AHLY" scored in each match. - `[input]` integer array `zamalekGoals` The number of goals "Zamalek" scored in each match. It is guaranteed that zamalekGoals[i] < ALAHLYGoals[i] for each element. - `[output]` an integer Index of the best match.
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.diff == best_diff] return sorted(temp, key=lambda match: match.scored, reverse=True)[0].index
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 schedule, a student can take the exam for the i-th subject on the day number a_{i}. However, Valera has made an arrangement with each teacher and the teacher of the i-th subject allowed him to take an exam before the schedule time on day b_{i} (b_{i} < a_{i}). Thus, Valera can take an exam for the i-th subject either on day a_{i}, or on day b_{i}. All the teachers put the record of the exam in the student's record book on the day of the actual exam and write down the date of the mark as number a_{i}. Valera believes that it would be rather strange if the entries in the record book did not go in the order of non-decreasing date. Therefore Valera asks you to help him. Find the minimum possible value of the day when Valera can take the final exam if he takes exams so that all the records in his record book go in the order of non-decreasing date. -----Input----- The first line contains a single positive integer n (1 ≤ n ≤ 5000) — the number of exams Valera will take. Each of the next n lines contains two positive space-separated integers a_{i} and b_{i} (1 ≤ b_{i} < a_{i} ≤ 10^9) — the date of the exam in the schedule and the early date of passing the i-th exam, correspondingly. -----Output----- Print a single integer — the minimum possible number of the day when Valera can take the last exam if he takes all the exams so that all the records in his record book go in the order of non-decreasing date. -----Examples----- Input 3 5 2 3 1 4 2 Output 2 Input 3 6 1 5 2 4 3 Output 6 -----Note----- In the first sample Valera first takes an exam in the second subject on the first day (the teacher writes down the schedule date that is 3). On the next day he takes an exam in the third subject (the teacher...
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 (we assume that JOE never answers a question wrong!). For each question JOE answers, if there are $s$ ($s > 0$) opponents remaining and $t$ ($0 \le t \le s$) of them make a mistake on it, JOE receives $\displaystyle\frac{t}{s}$ dollars, and consequently there will be $s - t$ opponents left for the next question. JOE wonders what is the maximum possible reward he can receive in the best possible scenario. Yet he has little time before show starts, so can you help him answering it instead? -----Input----- The first and single line contains a single integer $n$ ($1 \le n \le 10^5$), denoting the number of JOE's opponents in the show. -----Output----- Print a number denoting the maximum prize (in dollars) JOE could have. Your answer will be considered correct if it's absolute or relative error won't exceed $10^{-4}$. In other words, if your answer is $a$ and the jury answer is $b$, then it must hold that $\frac{|a - b|}{max(1, b)} \le 10^{-4}$. -----Examples----- Input 1 Output 1.000000000000 Input 2 Output 1.500000000000 -----Note----- In the second example, the best scenario would be: one contestant fails at the first question, the other fails at the next one. The total reward will be $\displaystyle \frac{1}{2} + \frac{1}{1} = 1.5$ dollars.
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 not do it. Can you solve it?
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("aba" ) == false is_isogram("moOse" ) == false # -- ignore letter case ``` ```C is_isogram("Dermatoglyphics" ) == true; is_isogram("aba" ) == false; is_isogram("moOse" ) == false; // -- ignore letter case ```
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 fractions. `(6,28)` and `(30,140)` are the only pairs in which `every member of a pair is 0 <= n < 200`. The sum of the lowest members of each pair is `6 + 30 = 36`. You will be given a `range(a,b)`, and your task is to group the numbers into pairs with the same ratios. You will return the sum of the lowest member of each pair in the range. If there are no pairs. return `nil` in Ruby, `0` in python. Upper limit is `2000`. ```Haskell solve(0,200) = 36 ``` Good luck! if you like this Kata, please try: [Simple division](https://www.codewars.com/kata/59ec2d112332430ce9000005) [Sub-array division](https://www.codewars.com/kata/59eb64cba954273cd4000099)
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 // i) cache[n] = result return result def solve(a, b): print(f'a: {a}, b: {b}') vals = {} for n in range(max(a, 1), b): r = F(sum(divisors(n)), n) vals.setdefault(r, []).append(n) result = 0 for k, v in vals.items(): if len(v) >= 2: result += v[0] return result
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,1,2,4]. Minimums are 3, 1, 2, 4, 1, 1, 2, 1, 1, 1.  Sum is 17.   Note: 1 <= A.length <= 30000 1 <= A[i] <= 30000
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] s1.append((A[i], cnt)) left[i] = cnt for i in range(n-1, -1, -1): cnt = 1 while s2 and s2[-1][0] >= A[i]: cnt += s2.pop()[1] s2.append((A[i], cnt)) right[i] = cnt return sum(A[i] * left[i] * right[i] for i in range(n)) % mod
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 vertices of the planned pool written on a paper, until his friend came along and erased some of the vertices. Now Wilbur is wondering, if the remaining n vertices of the initial rectangle give enough information to restore the area of the planned swimming pool. -----Input----- The first line of the input contains a single integer n (1 ≤ n ≤ 4) — the number of vertices that were not erased by Wilbur's friend. Each of the following n lines contains two integers x_{i} and y_{i} ( - 1000 ≤ x_{i}, y_{i} ≤ 1000) —the coordinates of the i-th vertex that remains. Vertices are given in an arbitrary order. It's guaranteed that these points are distinct vertices of some rectangle, that has positive area and which sides are parallel to the coordinate axes. -----Output----- Print the area of the initial rectangle if it could be uniquely determined by the points remaining. Otherwise, print - 1. -----Examples----- Input 2 0 0 1 1 Output 1 Input 1 1 1 Output -1 -----Note----- In the first sample, two opposite corners of the initial rectangle are given, and that gives enough information to say that the rectangle is actually a unit square. In the second sample there is only one vertex left and this is definitely not enough to uniquely define the area.
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 == 4: if 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 lst[1][0] != lst[2][0] and lst[1][1] != lst[2][1]: print(abs(lst[1][0] - lst[2][0]) * abs(lst[1][1] - lst[2][1])) else: print(abs(lst[0][0] - lst[2][0]) * abs(lst[0][1] - lst[2][1]))
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 of points will be deducted for each incorrect answer. For ommitted answers, points will either be awarded, deducted, or no points will be given at all. Return the number of points someone has scored on varying tests of different lengths. The given parameters will be: * An array containing a series of `0`s, `1`s, and `2`s, where `0` is a correct answer, `1` is an omitted answer, and `2` is an incorrect answer. * The points awarded for correct answers * The points awarded for omitted answers (note that this may be negative) * The points **deducted** for incorrect answers (hint: this value has to be subtracted) **Note:** The input will always be valid (an array and three numbers) ## Examples \#1: ``` [0, 0, 0, 0, 2, 1, 0], 2, 0, 1 --> 9 ``` because: * 5 correct answers: `5*2 = 10` * 1 omitted answer: `1*0 = 0` * 1 wrong answer: `1*1 = 1` which is: `10 + 0 - 1 = 9` \#2: ``` [0, 1, 0, 0, 2, 1, 0, 2, 2, 1], 3, -1, 2) --> 3 ``` because: `4*3 + 3*-1 - 3*2 = 3` I tried it in Python, but could not do it. Can you solve it?
#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 servings of Dish A and W servings of dish B. Now he wants to serve the dishes in such a way that if theith plate has serving of Dish A then (i-1)th plate should not have serving of Dish B. Assuming all the Dishes are identical find number of ways Tejas can serve the Clash Team. -----Input----- - The first line of the input contains an integer T denoting the number of test cases . The description of T testcases follow. - The first line of each test case contains two space seperated integers V W . -----Output----- For each test case, output the number of ways Tejas can serve the Clash Team. -----Constraints----- - 1 ≤ T ≤ 100 - 1 ≤ V ≤ 1000 - 1 ≤ W ≤ 1000 -----Example----- Input: 1 3 3 Output: 4 -----Explanation----- In the above example the 4 ways are: AAA AAB ABB BBB I tried it in Python, but could not do it. Can you solve it?
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 between them. The planks are numbered from the left to the right starting from one, the i-th plank has the width of 1 meter and the height of a_{i} meters. Bizon the Champion bought a brush in the shop, the brush's width is 1 meter. He can make vertical and horizontal strokes with the brush. During a stroke the brush's full surface must touch the fence at all the time (see the samples for the better understanding). What minimum number of strokes should Bizon the Champion do to fully paint the fence? Note that you are allowed to paint the same area of the fence multiple times. -----Input----- The first line contains integer n (1 ≤ n ≤ 5000) — the number of fence planks. The second line contains n space-separated integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10^9). -----Output----- Print a single integer — the minimum number of strokes needed to paint the whole fence. -----Examples----- Input 5 2 2 1 2 1 Output 3 Input 2 2 2 Output 2 Input 1 5 Output 1 -----Note----- In the first sample you need to paint the fence in three strokes with the brush: the first stroke goes on height 1 horizontally along all the planks. The second stroke goes on height 2 horizontally and paints the first and second planks and the third stroke (it can be horizontal and vertical) finishes painting the fourth plank. In the second sample you can paint the fence with two strokes, either two horizontal or two vertical strokes. In the third sample there is only one plank that can be painted using a single vertical stroke. I tried it in Python, but could not do it. Can you solve it?
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$, $y_2$, $z_2$ respectively. You can rearrange the elements in both sequences $a$ and $b$ however you like. After that, let's define a sequence $c$ as follows: $c_i = \begin{cases} a_i b_i & \mbox{if }a_i > b_i \\ 0 & \mbox{if }a_i = b_i \\ -a_i b_i & \mbox{if }a_i < b_i \end{cases}$ You'd like to make $\sum_{i=1}^n c_i$ (the sum of all elements of the sequence $c$) as large as possible. What is the maximum possible sum? -----Input----- The first line contains one integer $t$ ($1 \le t \le 10^4$) — the number of test cases. Each test case consists of two lines. The first line of each test case contains three integers $x_1$, $y_1$, $z_1$ ($0 \le x_1, y_1, z_1 \le 10^8$) — the number of $0$-s, $1$-s and $2$-s in the sequence $a$. The second line of each test case also contains three integers $x_2$, $y_2$, $z_2$ ($0 \le x_2, y_2, z_2 \le 10^8$; $x_1 + y_1 + z_1 = x_2 + y_2 + z_2 > 0$) — the number of $0$-s, $1$-s and $2$-s in the sequence $b$. -----Output----- For each test case, print the maximum possible sum of the sequence $c$. -----Example----- Input 3 2 3 2 3 3 1 4 0 1 2 3 0 0 0 1 0 0 1 Output 4 2 0 -----Note----- In the first sample, one of the optimal solutions is: $a = \{2, 0, 1, 1, 0, 2, 1\}$ $b = \{1, 0, 1, 0, 2, 1, 0\}$ $c = \{2, 0, 0, 0, 0, 2, 0\}$ In the second sample, one of the optimal solutions is: $a = \{0, 2, 0, 0, 0\}$ $b = \{1, 1, 0, 1, 0\}$ $c = \{0, 2, 0, 0, 0\}$ In the third sample, the only possible solution is: $a = \{2\}$ $b = \{2\}$ $c = \{0\}$
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 cows are alive after n years. I tried it in Python, but could not do it. Can you solve it?
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-01` (string) should be 1 (int). Good luck 👍 See also [ISO week date](https://en.wikipedia.org/wiki/ISO_week_date) and [Week Number](https://en.wikipedia.org/wiki/Week#Week_numbering) on Wikipedia for further information about calendar weeks. On [whatweekisit.org](http://whatweekisit.org/) you may click through the calender and study calendar weeks in more depth. *heads-up:* `require(xxx)` has been disabled Thanks to @ZED.CWT, @Unnamed and @proxya for their feedback.
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 representation is 0. Can you help Delta to find the total damage he did so he could make an equally sorry face? -----Input:----- - First line will contain $T$, number of testcases. Then the testcases follow. - First line of Each test case a single integer $N$. - Next line contains $N$ integers denoting values of items. -----Output:----- For each testcase, output in a single line the total damage caused by Delta. -----Constraints----- - $1 \leq T \leq 10^3$ - $1 \leq N \leq 10^3$ - $1 \leq value \leq 10^3$ -----Sample Input:----- 1 5 1 2 3 4 5 -----Sample Output:----- 6 -----EXPLANATION:----- Total Damage: $2 + 4 = 6$. I tried it in Python, but could not do it. Can you solve it?
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 is $|i - j|$, that is, the absolute difference between $i$ and $j$. Select any arbitrary index $i$ ($1 \le i \le n$) and flip (change $0$ to $1$ or $1$ to $0$) the bit at this index. The cost of this operation is $1$. Find the minimum cost to make the string $a$ equal to $b$. It is not allowed to modify string $b$. -----Input----- The first line contains a single integer $n$ ($1 \le n \le 10^6$) — the length of the strings $a$ and $b$. The second and third lines contain strings $a$ and $b$ respectively. Both strings $a$ and $b$ have length $n$ and contain only '0' and '1'. -----Output----- Output the minimum cost to make the string $a$ equal to $b$. -----Examples----- Input 3 100 001 Output 2 Input 4 0101 0011 Output 1 -----Note----- In the first example, one of the optimal solutions is to flip index $1$ and index $3$, the string $a$ changes in the following way: "100" $\to$ "000" $\to$ "001". The cost is $1 + 1 = 2$. The other optimal solution is to swap bits and indices $1$ and $3$, the string $a$ changes then "100" $\to$ "001", the cost is also $|1 - 3| = 2$. In the second example, the optimal solution is to swap bits at indices $2$ and $3$, the string $a$ changes as "0101" $\to$ "0011". The cost is $|2 - 3| = 1$. I tried it in Python, but could not do it. Can you solve it?
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 scales. Formally speaking, your task is to determine whether it is possible to place an item of mass m and some weights on the left pan of the scales, and some weights on the right pan of the scales so that the pans of the scales were in balance. -----Input----- The first line contains two integers w, m (2 ≤ w ≤ 10^9, 1 ≤ m ≤ 10^9) — the number defining the masses of the weights and the mass of the item. -----Output----- Print word 'YES' if the item can be weighted and 'NO' if it cannot. -----Examples----- Input 3 7 Output YES Input 100 99 Output YES Input 100 50 Output NO -----Note----- Note to the first sample test. One pan can have an item of mass 7 and a weight of mass 3, and the second pan can have two weights of masses 9 and 1, correspondingly. Then 7 + 3 = 9 + 1. Note to the second sample test. One pan of the scales can have an item of mass 99 and the weight of mass 1, and the second pan can have the weight of mass 100. Note to the third sample test. It is impossible to measure the weight of the item in the manner described in the input.
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 else: print("NO") f = 1 if (m == 0): print("YES") f = 1 st *= w
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 word? Reverse each word and combine first with second, third with fourth and so on... (odd number of words => last one stays alone, but has to be reversed too) 2. Start it again until there's only one word without spaces 3. Return your result... ``` ### Some easy examples: ``` Input: "abc def" Output: "cbafed" Input: "abc def ghi 123" Output: "defabc123ghi" Input: "abc def gh34 434ff 55_eri 123 343" Output: "43hgff434cbafed343ire_55321" ``` I think it's clear?! First there are some static tests, later on random tests too... ### Hope you have fun! :-) I tried it in Python, but could not do it. Can you solve it?
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 do with their color. So on some interval of her way she calculated two values — the number of steps with even and odd numbers. You need to check whether there is an interval of steps from the l-th to the r-th (1 ≤ l ≤ r), for which values that Dasha has found are correct. -----Input----- In the only line you are given two integers a, b (0 ≤ a, b ≤ 100) — the number of even and odd steps, accordingly. -----Output----- In the only line print "YES", if the interval of steps described above exists, and "NO" otherwise. -----Examples----- Input 2 3 Output YES Input 3 1 Output NO -----Note----- In the first example one of suitable intervals is from 1 to 5. The interval contains two even steps — 2 and 4, and three odd: 1, 3 and 5. I tried it in Python, but could not do it. Can you solve it?
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 sender if unknown acronyms are present. Any combination of three or more letters in upper case will be considered an acronym. Acronyms will not be combined with lowercase letters, such as in the case of 'KPIs'. They will be kept isolated as a word/words within a string. For any string: All instances of 'KPI' must become "key performance indicators" All instances of 'EOD' must become "the end of the day" All instances of 'TBD' must become "to be decided" All instances of 'WAH' must become "work at home" All instances of 'IAM' must become "in a meeting" All instances of 'OOO' must become "out of office" All instances of 'NRN' must become "no reply necessary" All instances of 'CTA' must become "call to action" All instances of 'SWOT' must become "strengths, weaknesses, opportunities and threats" If there are any unknown acronyms in the string, Laura wants you to return only the message: '[acronym] is an acronym. I do not like acronyms. Please remove them from your email.' So if the acronym in question was 'BRB', you would return the string: 'BRB is an acronym. I do not like acronyms. Please remove them from your email.' If there is more than one unknown acronym in the string, return only the first in your answer. If all acronyms can be replaced with full words according to the above, however, return only the altered string. If this is the case, ensure that sentences still start with capital letters. '!' or '?' will not be used. I tried it in Python, but could not do it. Can you solve it?
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 threats', 'TBD': 'to be decided', 'WAH': 'work at home' } result = [] for sentence in message.split('.'): tmp = [] for i, word in enumerate(sentence.split()): if word.isupper() and len(word) > 2: try: word = acronyms[word] except KeyError: return ('{} is an acronym. I do not like acronyms. Please' ' remove them from your email.'.format(word)) tmp.append(word[0].upper() + word[1:] if i == 0 else word) result.append(' '.join(tmp)) return '. '.join(result).rstrip()
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 (yes, chemistry in Berland differs from ours). But the rules of transformation are a bit strange. Berland chemists are aware of n materials, numbered in the order they were discovered. Each material can be transformed into some other material (or vice versa). Formally, for each i (2 ≤ i ≤ n) there exist two numbers x_{i} and k_{i} that denote a possible transformation: k_{i} kilograms of material x_{i} can be transformed into 1 kilogram of material i, and 1 kilogram of material i can be transformed into 1 kilogram of material x_{i}. Chemical processing equipment in BerSU allows only such transformation that the amount of resulting material is always an integer number of kilograms. For each i (1 ≤ i ≤ n) Igor knows that the experiment requires a_{i} kilograms of material i, and the laboratory contains b_{i} kilograms of this material. Is it possible to conduct an experiment after transforming some materials (or none)? -----Input----- The first line contains one integer number n (1 ≤ n ≤ 10^5) — the number of materials discovered by Berland chemists. The second line contains n integer numbers b_1, b_2... b_{n} (1 ≤ b_{i} ≤ 10^12) — supplies of BerSU laboratory. The third line contains n integer numbers a_1, a_2... a_{n} (1 ≤ a_{i} ≤ 10^12) — the amounts required for the experiment. Then n - 1 lines follow. j-th of them contains two numbers x_{j} + 1 and k_{j} + 1 that denote transformation of (j + 1)-th material (1 ≤ x_{j} + 1 ≤ j, 1 ≤ k_{j} + 1 ≤ 10^9). -----Output----- Print YES if it is possible to conduct an experiment. Otherwise print NO. -----Examples----- Input 3 1 2 3 3 2 1 1 1 1 1 Output YES Input 3 3 2 1 1 2 3 1 1 1 2 Output NO
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(' '))) # return b = [b[i] - a[i] for i in range(n)] c = [[0, 0]] for i in range(n - 1): line = f.readline().strip().split(' ') c.append([int(line[0]), int(line[1])]) # print(c) for i in range(n - 1, 0, -1): # print(i) fa = c[i][0] - 1 if b[i] >= 0: b[fa] += b[i] else: b[fa] += b[i] * c[i][1] if b[fa] < -1e17: print('NO') return 0 # for x in b: # fo.write(str(x) + '\n') if b[0] >= 0: print('YES') else: print('NO') main()
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` lowercase characters, where `n` is the letter's alphabet position `1-26`. ## Example ```python alpha_seq("ZpglnRxqenU") -> "Eeeee,Ggggggg,Llllllllllll,Nnnnnnnnnnnnnn,Nnnnnnnnnnnnnn,Pppppppppppppppp,Qqqqqqqqqqqqqqqqq,Rrrrrrrrrrrrrrrrrr,Uuuuuuuuuuuuuuuuuuuuu,Xxxxxxxxxxxxxxxxxxxxxxxx,Zzzzzzzzzzzzzzzzzzzzzzzzzz" ``` ## Technical Details - The string will include only letters. - The first letter of each sequence is uppercase followed by `n-1` lowercase. - Each sequence is separated with a comma. - Return value needs to be a string. I tried it in Python, but could not do it. Can you solve it?
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 exactly $n$ pages and the $i$-th page will include $x_i$ tables and $y_i$ formulas. The pages are numbered from $1$ to $n$. Vova fills the pages one after another, he can't go filling page $i + 1$ before finishing page $i$ and he can't skip pages. However, if he draws strictly more than $k$ tables in a row or writes strictly more than $k$ formulas in a row then he will get bored. Vova wants to rearrange tables and formulas in each page in such a way that he doesn't get bored in the process. Vova can't move some table or some formula to another page. Note that the count doesn't reset on the start of the new page. For example, if the page ends with $3$ tables and the next page starts with $5$ tables, then it's counted as $8$ tables in a row. Help Vova to determine if he can rearrange tables and formulas on each page in such a way that there is no more than $k$ tables in a row and no more than $k$ formulas in a row. -----Input----- The first line contains two integers $n$ and $k$ ($1 \le n \le 3 \cdot 10^5$, $1 \le k \le 10^6$). The second line contains $n$ integers $x_1, x_2, \dots, x_n$ ($1 \le x_i \le 10^6$) — the number of tables on the $i$-th page. The third line contains $n$ integers $y_1, y_2, \dots, y_n$ ($1 \le y_i \le 10^6$) — the number of formulas on the $i$-th page. -----Output----- Print "YES" if Vova can rearrange tables and formulas on each page in such a way that there is no more than $k$ tables in a row and no more than $k$ formulas in a row. Otherwise print "NO". -----Examples----- Input 2 2 5 5 2 2 Output YES Input 2 2 5 6 2 2 Output NO Input 4 1 4 1 10 1 3 2 10 1 Output YES -----Note----- In the first example the only option to rearrange everything is the following (let table be 'T' and formula be 'F'): page $1$: "TTFTTFT" page $2$:... I tried it in Python, but could not do it. Can you solve it?
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') return print('YES')
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 to be good when its elevation is higher than those of all observatories that can be reached from Obs. i using just one road. Note that Obs. i is also good when no observatory can be reached from Obs. i using just one road. How many good observatories are there? -----Constraints----- - 2 \leq N \leq 10^5 - 1 \leq M \leq 10^5 - 1 \leq H_i \leq 10^9 - 1 \leq A_i,B_i \leq N - A_i \neq B_i - Multiple roads may connect the same pair of observatories. - All values in input are integers. -----Input----- Input is given from Standard Input in the following format: N M H_1 H_2 ... H_N A_1 B_1 A_2 B_2 : A_M B_M -----Output----- Print the number of good observatories. -----Sample Input----- 4 3 1 2 3 4 1 3 2 3 2 4 -----Sample Output----- 2 - From Obs. 1, you can reach Obs. 3 using just one road. The elevation of Obs. 1 is not higher than that of Obs. 3, so Obs. 1 is not good. - From Obs. 2, you can reach Obs. 3 and 4 using just one road. The elevation of Obs. 2 is not higher than that of Obs. 3, so Obs. 2 is not good. - From Obs. 3, you can reach Obs. 1 and 2 using just one road. The elevation of Obs. 3 is higher than those of Obs. 1 and 2, so Obs. 3 is good. - From Obs. 4, you can reach Obs. 2 using just one road. The elevation of Obs. 4 is higher than that of Obs. 2, so Obs. 4 is good. Thus, the good observatories are Obs. 3 and 4, so there are two good observatories. I tried it in Python, but could not do it. Can you solve it?
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 else: hf[a-1] = 1 print(hf.count(0)) def __starting_point(): main() __starting_point()
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 and endi are 0-indexed. Return the maximum total sum of all requests among all permutations of nums. Since the answer may be too large, return it modulo 109 + 7.   Example 1: Input: nums = [1,2,3,4,5], requests = [[1,3],[0,1]] Output: 19 Explanation: One permutation of nums is [2,1,3,4,5] with the following result: requests[0] -> nums[1] + nums[2] + nums[3] = 1 + 3 + 4 = 8 requests[1] -> nums[0] + nums[1] = 2 + 1 = 3 Total sum: 8 + 3 = 11. A permutation with a higher total sum is [3,5,4,2,1] with the following result: requests[0] -> nums[1] + nums[2] + nums[3] = 5 + 4 + 2 = 11 requests[1] -> nums[0] + nums[1] = 3 + 5 = 8 Total sum: 11 + 8 = 19, which is the best that you can do. Example 2: Input: nums = [1,2,3,4,5,6], requests = [[0,1]] Output: 11 Explanation: A permutation with the max total sum is [6,5,4,3,2,1] with request sums [11]. Example 3: Input: nums = [1,2,3,4,5,10], requests = [[0,2],[1,3],[1,1]] Output: 47 Explanation: A permutation with the max total sum is [4,10,5,3,2,1] with request sums [19,18,10].   Constraints: n == nums.length 1 <= n <= 105 0 <= nums[i] <= 105 1 <= requests.length <= 105 requests[i].length == 2 0 <= starti <= endi < n I tried it in Python, but could not do it. Can you solve it?
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 requests, count number of coverage for each index. counts = [c0, c1] put (c0, 0), (c1, 1) into maxHeap popout maxHeap, each index gets the assigned element from largest to smallest to form new nums calculate sum of requests in new nums Complexity: time: max(O(nlogn), O(mn)) space: O(n) Follow up: 1. use LinkedHashMap 2. \"\"\" if not nums: return -1 # rise IllegalInputArgumentException MOD = 10 ** 9 + 7 result, n, m = 0, len(nums), len(requests) counts = [0 for _ in range(n)] max_heap = [] # O(m*n) #for i in range(m): # for j in range(requests[i][0], requests[i][1] + 1): # counts[j] += 1 # O(max(m, n)): use sweep line records = [] for i in range(m): records.append([requests[i][0], 1]) records.append([requests[i][1]+1, -1]) for index, delta in sorted(records): if index < n: counts[index] += delta for i in range(n): if i != 0: counts[i] = counts[i] + counts[i-1] for i in range(n): heapq.heappush(max_heap, (-counts[i], i)) # O(nlogn) nums.sort() new_nums, cur_max = [0 for _ in range(n)], n - 1 while max_heap and cur_max >= 0: cur = heapq.heappop(max_heap) new_nums[cur[1]] = nums[cur_max] cur_max -= 1 prefixsum = [0 for _ in range(n)] for i in range(n): if i == 0: prefixsum[i] =...
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 and after $C_i$ minutes, removes it from this burner; the dish may not be removed from the burner before those $C_i$ minutes pass, because otherwise it cools down and gets spoiled. Any two dishes may be prepared simultaneously, however, no two dishes may be on the same burner at the same time. Ada may remove a dish from a burner and put another dish on the same burner at the same time. What is the minimum time needed to prepare all dishes, i.e. reach the state where all dishes are prepared? -----Input----- - The first line of the input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows. - The first line of each test case contains a single integer $N$. - The second line contains $N$ space-separated integers $C_1, C_2, \ldots, C_N$. -----Output----- For each test case, print a single line containing one integer ― the minimum number of minutes needed to prepare all dishes. -----Constraints----- - $1 \le T \le 1,000$ - $1 \le N \le 4$ - $1 \le C_i \le 5$ for each valid $i$ -----Subtasks----- Subtask #1 (1 points): $C_1 = C_2 = \ldots = C_N$ Subtask #2 (99 points): original constraints -----Example Input----- 3 3 2 2 2 3 1 2 3 4 2 3 4 5 -----Example Output----- 4 3 7 -----Explanation----- Example case 1: Place the first two dishes on the burners, wait for two minutes, remove both dishes and prepare the last one on one burner. Example case 2: Place the first and third dish on the burners. When the first dish is prepared, remove it and put the second dish on the same burner. Example case 3: Place the third and fourth dish on the burners. When the third dish is prepared, remove it and put the second dish on the same burner. Similarly, replace the fourth dish...
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 Input in the following format: N i -----Output----- Print the answer. -----Sample Input----- 4 2 -----Sample Output----- 3 The second car from the front of a 4-car train is the third car from the back.
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 then leftChild[i] will equal -1, similarly for the right child. Note that the nodes have no values and that we only use the node numbers in this problem.   Example 1: Input: n = 4, leftChild = [1,-1,3,-1], rightChild = [2,-1,-1,-1] Output: true Example 2: Input: n = 4, leftChild = [1,-1,3,-1], rightChild = [2,3,-1,-1] Output: false Example 3: Input: n = 2, leftChild = [1,0], rightChild = [-1,-1] Output: false Example 4: Input: n = 6, leftChild = [1,-1,-1,4,-1,-1], rightChild = [2,-1,-1,5,-1,-1] Output: false   Constraints: 1 <= n <= 10^4 leftChild.length == rightChild.length == n -1 <= leftChild[i], rightChild[i] <= n - 1 I tried it in Python, but could not do it. Can you solve it?
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 k=0 stk=[roots.pop()] while stk: node=stk.pop() k+=1 l,r=left[node],right[node] if l!=-1: stk.append(l) if r!=-1: stk.append(r) return k==n
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 weight of the monster being eaten, and they stand in the queue next to each other. Monsters eat each other instantly. There are no monsters which are being eaten at the same moment. After the monster A eats the monster B, the weight of the monster A increases by the weight of the eaten monster B. In result of such eating the length of the queue decreases by one, all monsters after the eaten one step forward so that there is no empty places in the queue again. A monster can eat several monsters one after another. Initially there were n monsters in the queue, the i-th of which had weight a_{i}. For example, if weights are [1, 2, 2, 2, 1, 2] (in order of queue, monsters are numbered from 1 to 6 from left to right) then some of the options are: the first monster can't eat the second monster because a_1 = 1 is not greater than a_2 = 2; the second monster can't eat the third monster because a_2 = 2 is not greater than a_3 = 2; the second monster can't eat the fifth monster because they are not neighbors; the second monster can eat the first monster, the queue will be transformed to [3, 2, 2, 1, 2]. After some time, someone said a good joke and all monsters recovered. At that moment there were k (k ≤ n) monsters in the queue, the j-th of which had weight b_{j}. Both sequences (a and b) contain the weights of the monsters in the order from the first to the last. You are required to provide one of the possible orders of eating monsters which led to the current queue, or to determine that this could not happen. Assume that the doctor didn't make any appointments while monsters were eating each other. -----Input----- The first line contains single integer n (1 ≤ n ≤ 500) — the number of monsters in the initial...
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: return 1 for i in range(x, y + 1): if a[i] > a[pos1]: pos1 = i if a[i] >= a[pos2]: pos2 = i for i in range(x, y): if a[i] == a[pos2]: if a[i + 1] < a[i]: pos2 = i for i in range(x + 1, y + 1): if a[i] == a[pos1]: if a[i - 1] < a[i]: pos1 = i if pos1 != x or a[pos1] > a[pos1 + 1]: for i in range(0, pos1 - x): ans1.append(pos1 - x + z - i) ans2.append('L') for i in range(0, y - pos1): ans1.append(z) ans2.append('R') elif pos2 != y or a[pos2] > a[pos2 - 1]: for i in range(0, y - pos2): ans1.append(pos2 - x + z) ans2.append('R') for i in range(0, pos2 - x): ans1.append(pos2 - x + z - i) ans2.append('L') else: return 0 return 1 lasti = 0 j = 1 sum = 0 for i in range(1, n+1): if j > k: print('NO') return sum += a[i] #print(i, sum, j) if sum > b[j]: print('NO') return if sum == b[j]: if f(lasti + 1, i, j) == 0: print('NO') return lasti = i j += 1 sum = 0 if j <= k: print('NO') return print('YES') for i in range(0, len(ans1)): print(ans1[i], ans2[i])
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 radioactive substance, the quantity remaining after a given period of time, and the period of time, return the half life of that substance. # Usage Examples ```if:csharp Documentation: Kata.HalfLife Method (Double, Double, Int32) Returns the half-life for a substance given the initial quantity, the remaining quantity, and the elasped time. Syntax public static double HalfLife( double quantityInitial,   double quantityRemaining, int time   ) Parameters quantityInitial Type: System.Double The initial amount of the substance. quantityRemaining Type: System.Double The current amount of the substance. time Type: System.Int32 The amount of time elapsed. Return Value Type: System.Double A floating-point number representing the half-life of the substance. ``` I tried it in Python, but could not do it. Can you solve it?
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: A[1] mod x = 0, A[2] mod x = 0, ..., A[N] mod x = 0, where mod stands for the modulo operation. For example, 8 mod 3 = 2, 2 mod 2 = 0, 100 mod 5 = 0 and so on. If such number does not exist, output -1. -----Input----- The first line of the input contains a single integer T, the number of test cases. T test cases follow. The first line of each test case contains a single integer N, the size of the array A for the corresponding test case. The second line contains N space separated integers A[1], A[2], ..., A[N]. -----Output----- For each test case output a single line containing the answer for the corresponding test case. -----Constraints----- 1 ≤ T ≤ 100000 1 ≤ N ≤ 100000 The sum of values of N in each test file does not exceed 100000 1 ≤ A[i] ≤ 100000 -----Example----- Input: 2 3 2 4 8 3 4 7 5 Output: 2 -1 -----Explanation----- Case 1. Clearly 2 is a divisor of each of the numbers 2, 4 and 8. Since 2 is the least number greater than 1 then it is the answer. Case 2. Let's perform check for several first values of x. x4 mod x7 mod x5 mod x20113112403154206415740584759475 As we see each number up to 9 does not divide all of the numbers in the array. Clearly all larger numbers also will fail to do this. So there is no such number x > 1 and the answer is -1.
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 greatest common divisor simply printing this is incorrect #since gcd divides all the numbers in the array it's divisors will also do the same #find the smallest divisor (smallest prime) if gc ==1: print(-1) elif gc %2 ==0: print(2) else: print(divisor(gc))
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 space-separated strings: the name of the cheese and its type. The name is a string of lowercase English letters between 1 and 10 characters long. The type is either "soft" or "hard. All cheese names are distinct. -----Output----- Output a single number. -----Examples----- Input 9 brie soft camembert soft feta soft goat soft muenster soft asiago hard cheddar hard gouda hard swiss hard Output 3 Input 6 parmesan hard emmental hard edam hard colby hard gruyere hard asiago hard Output 4 I tried it in Python, but could not do it. Can you solve it?
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   Note: 1 <= A.length <= 50000 -10 ^ 5 <= A[i] <= 10 ^ 5 1 <= K <= 10 ^ 9
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() #queue.append((0,0)) ans=float('inf') for i,e in enumerate(s): #print(queue) if len(queue)==0: queue.append((i,e)) elif len(queue) and queue[-1][1]<e: if e-queue[0][1]>=k: while len(queue) and e-queue[0][1]>=k: ans=min(ans,i-queue[0][0]) queue.popleft() queue.append((i,e)) elif len(queue) and queue[-1][1]>=e: while len(queue) and queue[-1][1]>=e: queue.pop() queue.append((i,e)) if len(queue)>1 and queue[-1][1]>=queue[0][1]+k: ans=min(ans,i-queue[-1][0]) return -1 if ans==float('inf') else ans
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 intersection of a sequence of segments is such a maximal set of points (not necesserily having integer coordinates) that each point lies within every segment from the sequence. If the resulting set isn't empty, then it always forms some continuous segment. The length of the intersection is the length of the resulting segment or $0$ in case the intersection is an empty set. For example, the intersection of segments $[1;5]$ and $[3;10]$ is $[3;5]$ (length $2$), the intersection of segments $[1;5]$ and $[5;7]$ is $[5;5]$ (length $0$) and the intersection of segments $[1;5]$ and $[6;6]$ is an empty set (length $0$). Your task is to remove exactly one segment from the given sequence in such a way that the intersection of the remaining $(n - 1)$ segments has the maximal possible length. -----Input----- The first line contains a single integer $n$ ($2 \le n \le 3 \cdot 10^5$) — the number of segments in the sequence. Each of the next $n$ lines contains two integers $l_i$ and $r_i$ ($0 \le l_i \le r_i \le 10^9$) — the description of the $i$-th segment. -----Output----- Print a single integer — the maximal possible length of the intersection of $(n - 1)$ remaining segments after you remove exactly one segment from the sequence. -----Examples----- Input 4 1 3 2 6 0 4 3 3 Output 1 Input 5 2 6 1 3 0 4 1 20 0 4 Output 2 Input 3 4 5 1 2 9 20 Output 0 Input 2 3 10 1 5 Output 7 -----Note----- In the first example you should remove the segment $[3;3]$, the intersection will become $[2;3]$ (length $1$). Removing any other segment will result in the intersection $[3;3]$ (length $0$). In the second example you should remove the segment $[1;3]$ or segment $[2;6]$, the intersection will become $[2;4]$ (length $2$) or $[1;3]$ (length $2$), respectively. Removing any other segment will... I tried it in Python, but could not do it. Can you solve it?
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 <= ls[l2]: l2 = i if r < rs[r1] or r == rs[r1] and l > ls[r1]: r2 = r1 r1 = i elif r2 == -1 or r < rs[r2] or r == rs[r2] and l > ls[r2]: r2 = i if l1 == r1: ans = rs[r2] - ls[l2] elif ls[l1] - ls[l2] > rs[r2] - rs[r1]: ans = rs[r1] - ls[l2] else: ans = rs[r2] - ls[l1] print(max( ans, 0 ))
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 more details visit the related [wikipedia page](http://en.wikipedia.org/wiki/Simple_linear_regression). --- --- #### Task: The function that you have to write accepts two list/array, `$x$` and `$y$`, representing the coordinates of the points to regress (so that, for example, the first point has coordinates (`x[0], y[0]`)). Your function should return a tuple (in Python) or an array (any other language) of two elements: `a` (intercept) and `b` (slope) in this order. You must round your result to the first 4 decimal digits #### Formula: `$x_i$` and `$y_i$` is `$x$` and `$y$` co-ordinate of `$i$`-th point; `$n$` is length of input. `$a = \dfrac{\sum x_i^2\cdot \sum y_i - \sum x_i \cdot\sum x_iy_i}{n\sum x_i^2 - (\sum x_i)^2}$` `$b = \dfrac{n\sum x_i y_i - \sum x_i \cdot \sum y_i}{n\sum x^2_i - (\sum x_i)^2}$` #### Examples: ```python regressionLine([25,30,35,40,45,50], [78,70,65,58,48,42]) == (114.381, -1.4457) regressionLine([56,42,72,36,63,47,55,49,38,42,68,60], [147,125,160,118,149,128,150,145,115,140,152,155]) == (80.7777, 1.138) ``` ----
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 pile of stones, and remove one or more stones from it. - When a player is unable to do the operation, he loses, and the other player wins. When the two players play optimally, there are two possibilities in this game: the player who moves first always wins, or the player who moves second always wins, only depending on the initial number of stones in each pile. In such a situation, Takahashi, the second player to act, is trying to guarantee his win by moving at least zero and at most (A_1 - 1) stones from the 1-st pile to the 2-nd pile before the game begins. If this is possible, print the minimum number of stones to move to guarantee his victory; otherwise, print -1 instead. -----Constraints----- - 2 \leq N \leq 300 - 1 \leq A_i \leq 10^{12} -----Input----- Input is given from Standard Input in the following format: N A_1 \ldots A_N -----Output----- Print the minimum number of stones to move to guarantee Takahashi's win; otherwise, print -1 instead. -----Sample Input----- 2 5 3 -----Sample Output----- 1 Without moving stones, if Aoki first removes 2 stones from the 1-st pile, Takahashi cannot win in any way. If Takahashi moves 1 stone from the 1-st pile to the 2-nd before the game begins so that both piles have 4 stones, Takahashi can always win by properly choosing his actions. I tried it in Python, but could not do it. Can you solve it?
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]: print(-1) return k = x.bit_length() tmp = d # d^tmp はd&x=0からd|tmpと一緒 for i in range(k, -1, -1): if (x >> i) & 1: if tmp|1<<i <= a[0]: tmp |= 1<<i if 0 < tmp <= a[0]: print(a[0]-tmp) else: print(-1) def __starting_point(): main() __starting_point()
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 test cases. Then the test cases follow. -Each test case contains a single line of input, one integer $K$. -----Output:----- For each test case, output as the pattern. -----Constraints----- - $1 \leq T \leq 26$ - $1 \leq K \leq 26$ -----Sample Input:----- 2 2 4 -----Sample Output:----- A 12 A 12 ABC 1234 -----EXPLANATION:----- No need, else pattern can be decode easily. I tried it in Python, but could not do it. Can you solve it?
# 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 the distance between two different vertices x and y is less than or equal to two, x and y have different colors. How many ways are there to paint the tree? Find the count modulo 1\ 000\ 000\ 007. What is tree? A tree is a kind of graph. For detail, please see: Wikipedia "Tree (graph theory)" What is distance? The distance between two vertices x and y is the minimum number of edges one has to traverse to get from x to y. -----Constraints----- - 1 \leq N,K \leq 10^5 - 1 \leq a_i,b_i \leq N - The given graph is a tree. -----Input----- Input is given from Standard Input in the following format: N K a_1 b_1 a_2 b_2 . . . a_{N-1} b_{N-1} -----Output----- Print the number of ways to paint the tree, modulo 1\ 000\ 000\ 007. -----Sample Input----- 4 3 1 2 2 3 3 4 -----Sample Output----- 6 There are six ways to paint the tree.
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,finv,inv def COM(n,r): if n<r or r<0: return 0 else: return ((fac[n]*finv[r])%MOD*finv[n-r])%MOD def dfs(v,p,dep): nonlocal res c=0 for nv in G[v]: if nv==p: continue dfs(nv,v,dep+1) c+=1 if dep==0: res=((res*COM(K-1,c)%MOD)*fac[c])%MOD else: res=((res*COM(K-2,c)%MOD)*fac[c])%MOD N,K=map(int,input().split()) G=[[] for i in range(N)] for i in range(N-1): a,b=map(lambda x:int(x)-1,input().split()) G[a].append(b) G[b].append(a) fac,finv,inv=facinv(max(K,N)) res=K dfs(0,-1,0) print(res%MOD)
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{merge}(a,\emptyset)=a$. In particular, $\mathrm{merge}(\emptyset,\emptyset)=\emptyset$. If both arrays are non-empty, and $a_1<b_1$, then $\mathrm{merge}(a,b)=[a_1]+\mathrm{merge}([a_2,\ldots,a_n],b)$. That is, we delete the first element $a_1$ of $a$, merge the remaining arrays, then add $a_1$ to the beginning of the result. If both arrays are non-empty, and $a_1>b_1$, then $\mathrm{merge}(a,b)=[b_1]+\mathrm{merge}(a,[b_2,\ldots,b_m])$. That is, we delete the first element $b_1$ of $b$, merge the remaining arrays, then add $b_1$ to the beginning of the result. This algorithm has the nice property that if $a$ and $b$ are sorted, then $\mathrm{merge}(a,b)$ will also be sorted. For example, it is used as a subroutine in merge-sort. For this problem, however, we will consider the same procedure acting on non-sorted arrays as well. For example, if $a=[3,1]$ and $b=[2,4]$, then $\mathrm{merge}(a,b)=[2,3,1,4]$. A permutation is an array consisting of $n$ distinct integers from $1$ to $n$ in arbitrary order. For example, $[2,3,1,5,4]$ is a permutation, but $[1,2,2]$ is not a permutation ($2$ appears twice in the array) and $[1,3,4]$ is also not a permutation ($n=3$ but there is $4$ in the array). There is a permutation $p$ of length $2n$. Determine if there exist two arrays $a$ and $b$, each of length $n$ and with no elements in common, so that $p=\mathrm{merge}(a,b)$. -----Input----- The first line contains a single integer $t$ ($1\le t\le 1000$)  — the number of test cases. Next $2t$ lines contain descriptions of test cases. The first line of each test case contains a single integer $n$ ($1\le n\le 2000$). The second line of each test case contains $2n$ integers $p_1,\ldots,p_{2n}$ ($1\le p_i\le 2n$). It is...
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) poss = [[False]*(n+1) for _ in range(len(blocks) + 1)] poss[0][0] = True for i, b in enumerate(blocks): for j in range(n+1): poss[i+1][j] = poss[i][j] if b <= j: poss[i+1][j] |= poss[i][j-b] # print() # print(blocks) # for r in poss: # print(r) print("YES" if poss[len(blocks)][n] else "NO")
python
train
qsol
codeparrot/apps
all