inputs
stringlengths
175
2.22k
targets
stringlengths
10
2.05k
language
stringclasses
1 value
split
stringclasses
2 values
template
stringclasses
2 values
dataset
stringclasses
1 value
config
stringclasses
1 value
I found an interesting problem on https://codeforces.com/problemset/problem/1096/E: Hasan loves playing games and has recently discovered a game called TopScore. In this soccer-like game there are $p$ players doing penalty shoot-outs. Winner is the one who scores the most. In case of ties, one of the top-scorers will be declared as the winner randomly with equal probability. They have just finished the game and now are waiting for the result. But there's a tiny problem! The judges have lost the paper of scores! Fortunately they have calculated sum of the scores before they get lost and also for some of the players they have remembered a lower bound on how much they scored. However, the information about the bounds is private, so Hasan only got to know his bound. According to the available data, he knows that his score is at least $r$ and sum of the scores is $s$. Thus the final state of the game can be represented in form of sequence of $p$ integers $a_1, a_2, \dots, a_p$ ($0 \le a_i$) — player's scores. Hasan is player number $1$, so $a_1 \ge r$. Also $a_1 + a_2 + \dots + a_p = s$. Two states are considered different if there exists some position $i$ such that the value of $a_i$ differs in these states. Once again, Hasan doesn't know the exact scores (he doesn't know his exact score as well). So he considers each of the final states to be equally probable to achieve. Help Hasan find the probability of him winning. It can be shown that it is in the form of $\frac{P}{Q}$ where $P$ and $Q$ are non-negative integers and $Q \ne 0$, $P \le Q$. Report the value of $P \cdot Q^{-1} \pmod {998244353}$. -----Input----- The only line contains three integers $p$, $s$ and $r$ ($1 \le p \le 100$, $0 \le r \le s \le 5000$) — the number of players, the sum of scores of all players and Hasan's score, respectively. -----Output----- Print a single integer — the probability of Hasan winning. It can be shown that it is in the form of $\frac{P}{Q}$ where $P$ and $Q$ are non-negative integers and $Q \ne 0$, $P \le Q$. Report the value of $P \cdot Q^{-1} \pmod... I tried it in Python, but could not do it. Can you solve it?
base=998244353; def power(x, y): if(y==0): return 1 t=power(x, y//2) t=(t*t)%base if(y%2): t=(t*x)%base return t; def inverse(x): return power(x, base-2) f=[1] iv=[1] for i in range(1, 5555): f.append((f[i-1]*i)%base) iv.append(inverse(f[i])) def C(n, k): return (f[n]*iv[k]*iv[n-k])%base def candy(n, k): # print(n, k) return C(n+k-1, k-1) def count_game(k, n, x): #k players, n points total, no player can have x point or more if(k==0): if(n==0): return 1 else: return 0 ans=0 for i in range(0, k+1): t=n-x*i # print(i, C(k, i)) if(t<0): break if(i%2): ans=(ans-C(k, i)*candy(t, k))%base else: ans=(ans+C(k, i)*candy(t, k))%base return ans p, s, r= list(map(int, input().split())) gamesize=count_game(p, s-r, int(1e18)) gamesize=inverse(gamesize) ans=0; for q in range(r, s+1): for i in range(0, p): #exactly i people have the same score t=s-(i+1)*q if(t<0): break # print(q, i, count_game(p-i-1, t, q)); ans=(ans+C(p-1, i)*count_game(p-i-1, t, q)*gamesize*inverse(i+1))%base print(ans)
python
test
abovesol
codeparrot/apps
all
I found an interesting problem on https://codeforces.com/problemset/problem/342/A: Xenia the mathematician has a sequence consisting of n (n is divisible by 3) positive integers, each of them is at most 7. She wants to split the sequence into groups of three so that for each group of three a, b, c the following conditions held: a < b < c; a divides b, b divides c. Naturally, Xenia wants each element of the sequence to belong to exactly one group of three. Thus, if the required partition exists, then it has $\frac{n}{3}$ groups of three. Help Xenia, find the required partition or else say that it doesn't exist. -----Input----- The first line contains integer n (3 ≤ n ≤ 99999) — the number of elements in the sequence. The next line contains n positive integers, each of them is at most 7. It is guaranteed that n is divisible by 3. -----Output----- If the required partition exists, print $\frac{n}{3}$ groups of three. Print each group as values of the elements it contains. You should print values in increasing order. Separate the groups and integers in groups by whitespaces. If there are multiple solutions, you can print any of them. If there is no solution, print -1. -----Examples----- Input 6 1 1 1 2 2 2 Output -1 Input 6 2 2 1 1 4 6 Output 1 2 4 1 2 6 I tried it in Python, but could not do it. Can you solve it?
a=[0 for i in range(8)] N=int(input()) b=list(map(int, input().split())) for k in range(N): a[b[k-1]]=a[b[k-1]]+1; if a[5] or a[7]: print(-1) return A,C=a[4],a[3] B=a[6]-C if A>=0 and B>=0 and C>=0 and A+B==a[2] and A+B+C==a[1]: for i in range(A): print("1 2 4") for i in range(B): print("1 2 6") for i in range(C): print("1 3 6") else: print(-1)
python
test
abovesol
codeparrot/apps
all
I found an interesting problem on https://codeforces.com/problemset/problem/1056/D: There is one apple tree in Arkady's garden. It can be represented as a set of junctions connected with branches so that there is only one way to reach any junctions from any other one using branches. The junctions are enumerated from $1$ to $n$, the junction $1$ is called the root. A subtree of a junction $v$ is a set of junctions $u$ such that the path from $u$ to the root must pass through $v$. Note that $v$ itself is included in a subtree of $v$. A leaf is such a junction that its subtree contains exactly one junction. The New Year is coming, so Arkady wants to decorate the tree. He will put a light bulb of some color on each leaf junction and then count the number happy junctions. A happy junction is such a junction $t$ that all light bulbs in the subtree of $t$ have different colors. Arkady is interested in the following question: for each $k$ from $1$ to $n$, what is the minimum number of different colors needed to make the number of happy junctions be greater than or equal to $k$? -----Input----- The first line contains a single integer $n$ ($1 \le n \le 10^5$) — the number of junctions in the tree. The second line contains $n - 1$ integers $p_2$, $p_3$, ..., $p_n$ ($1 \le p_i < i$), where $p_i$ means there is a branch between junctions $i$ and $p_i$. It is guaranteed that this set of branches forms a tree. -----Output----- Output $n$ integers. The $i$-th of them should be the minimum number of colors needed to make the number of happy junctions be at least $i$. -----Examples----- Input 3 1 1 Output 1 1 2 Input 5 1 1 3 3 Output 1 1 1 2 3 -----Note----- In the first example for $k = 1$ and $k = 2$ we can use only one color: the junctions $2$ and $3$ will be happy. For $k = 3$ you have to put the bulbs of different colors to make all the junctions happy. In the second example for $k = 4$ you can, for example, put the bulbs of color $1$ in junctions $2$ and $4$, and a bulb of color $2$ into junction $5$. The happy junctions are the ones with indices $2$, $3$, $4$ and $5$ then. I tried it in Python, but could not do it. Can you solve it?
# -*- coding:utf-8 -*- """ created by shuangquan.huang at 12/14/18 """ import collections import sys N = int(input()) p = [int(x) for x in input().split()] G = collections.defaultdict(list) for i, v in enumerate(p): u = i + 2 G[u].append(v) G[v].append(u) root = 1 colors = [0] * (N + 1) counts = [0] * (N + 1) q = [root] parents = [0] * (N+1) vis = [0] * (N+1) while q: u = q.pop() if vis[u]: colors[parents[u]] += colors[u] continue children = [v for v in G[u] if v != parents[u]] for v in children: parents[v] = u if children: vis[u] = True q.append(u) q.extend(children) else: vis[u] = True colors[u] = 1 colors[parents[u]] += 1 # # # def dfs(u, parent): # cc, hc = 0, 0 # for v in G[u]: # if v != parent: # a, b = dfs(v, u) # cc += a # hc += b # counts[u] = hc + 1 # cc = cc if cc > 0 else 1 # colors[u] = cc # return cc, hc + 1 # # # dfs(1, -1) # colors = colors[1:] colors.sort() print(' '.join(map(str, colors)))
python
test
abovesol
codeparrot/apps
all
Solve in Python: You are given two strings a and b. You have to remove the minimum possible number of consecutive (standing one after another) characters from string b in such a way that it becomes a subsequence of string a. It can happen that you will not need to remove any characters at all, or maybe you will have to remove all of the characters from b and make it empty. Subsequence of string s is any such string that can be obtained by erasing zero or more characters (not necessarily consecutive) from string s. -----Input----- The first line contains string a, and the second line — string b. Both of these strings are nonempty and consist of lowercase letters of English alphabet. The length of each string is no bigger than 10^5 characters. -----Output----- On the first line output a subsequence of string a, obtained from b by erasing the minimum number of consecutive characters. If the answer consists of zero characters, output «-» (a minus sign). -----Examples----- Input hi bob Output - Input abca accepted Output ac Input abacaba abcdcba Output abcba -----Note----- In the first example strings a and b don't share any symbols, so the longest string that you can get is empty. In the second example ac is a subsequence of a, and at the same time you can obtain it by erasing consecutive symbols cepted from string b.
#import sys #sys.stdin = open('in', 'r') #n = int(input()) #a = [int(x) for x in input().split()] #n,m = map(int, input().split()) s1 = input() s2 = input() l1 = len(s1) l2 = len(s2) dl = {} dr = {} i1 = 0 i2 = 0 while i1 < l1 and i2 < l2: while i1 < l1 and s1[i1] != s2[i2]: i1 += 1 if i1 < l1: dl[i2] = i1 i2 += 1 i1 += 1 lmax = i2 if lmax == l2: print(s2) else: i1 = l1 - 1 i2 = l2 - 1 while i1 >= 0 and i2 >= 0: while i1 >= 0 and s1[i1] != s2[i2]: i1 -= 1 if i1 >= 0: dr[i2] = i1 i2 -= 1 i1 -= 1 rmax = i2 le = -1 re = -1 if l2 - lmax < rmax + 1: rcnt = l2 - lmax ls = 0 rs = lmax else: rcnt = rmax + 1 ls = rmax + 1 rs = l2 rr = rmax + 1 for ll in range(lmax): while rr < l2 and (rr <= ll or dl[ll] >= dr[rr]): rr += 1 if rr < l2: dif = rr - ll - 1 if dif < rcnt: rcnt = dif ls = 0 rs = ll + 1 le = rr re = l2 result = s2[ls:rs] if le != -1: result += s2[le:re] print(result if len(result) > 0 else '-')
python
test
qsol
codeparrot/apps
all
I found an interesting problem on https://www.codechef.com/problems/LEMOUSE: It is well-known that the elephants are afraid of mouses. The Little Elephant from the Zoo of Lviv is not an exception. The Little Elephant is on a board A of n rows and m columns (0-based numeration). At the beginning he is in cell with coordinates (0; 0) and he wants to go to cell with coordinates (n-1; m-1). From cell (x; y) Little Elephant can go either to (x+1; y) or (x; y+1). Each cell of the board contains either 1 or 0. If A[i][j] = 1, then there is a single mouse in cell (i; j). Mouse at cell (i; j) scared Little Elephants if and only if during the path there was at least one such cell (x; y) (which belongs to that path) and |i-x| + |j-y| <= 1. Little Elephant wants to find some correct path from (0; 0) to (n-1; m-1) such that the number of mouses that have scared the Little Elephant is minimal possible. Print that number. -----Input----- First line contains single integer T - the number of test cases. Then T test cases follow. First line of each test case contain pair of integers n and m - the size of the board. Next n lines contain n strings, each of size m and consisted of digits 0 and 1. -----Output----- In T lines print T integer - the answers for the corresponding test. -----Constraints----- 1 <= T <= 50 2 <= n, m <= 100 -----Example----- Input: 2 3 9 001000001 111111010 100100100 7 9 010101110 110110111 010011111 100100000 000010100 011011000 000100101 Output: 9 10 -----Explanation----- Example case 1: The optimized path is: (0, 0) -> (0, 1) -> (0, 2) -> (0, 3) -> (0, 4) -> (0, 5) -> (0, 6) -> (0, 7) -> (0, 8) -> (1, 8) -> (2, 8). The mouses that scared the Little Elephant are at the following cells: (1, 0), (1, 1), (1, 2), (1, 3), (1, 4), (1, 5), (1, 7), (0, 2), (0, 8). Example case 2: The optimized path is: (0, 0) -> (1, 0) -> (1, 1) -> (2, 1) -> (2, 2) -> (3, 2) -> (3, 3) -> (4, 3) -> (4, 4) -> (5, 4) -> (5, 5) -> (6, 5) -> (6, 6) -> (6, 7) -> (6, 8). The 10 mouses that scared the Little Elephant are at the following cells: (0, 1), (1, 0), (1, 1), (2, 1), (3, 3), (4, 4), (5, 4),... I tried it in Python, but could not do it. Can you solve it?
from collections import defaultdict from itertools import product def solve(mouse,n,m): # shadow matrix will contains the count of mice which affect (i,j) position # if there is a mice at position (i,j) then in shadow matrix it will affect         all four adjacent blocks shadow=[[0 for i in range(m)]for j in range(n)] for i,j in product(list(range(n)),list(range(m))): if mouse[i][j]==1: if i>0: shadow[i-1][j]+=1 if j>0: shadow[i][j-1]+=1 if i<n-1: shadow[i+1][j]+=1 if j<m-1: shadow[i][j+1]+=1 # dp is a dictionary which contains a tuple of 3 values (i,j,0)=>we are         coming at destination (i,j) from left side # (i,j,1)=> we are coming at destination (i,j) from top dp=defaultdict(int) # dp[(0,0,0)]=dp[(0,0,1)]=shadow[0][0]-mouse[0][0] # fill only first row # in first row we can only reach at (0,j) from (0,j-1,0) as we can't come         from top. # so here we will assign count of mices which will affect current cell        (shadow[0][i]) + previous result i.e,(0,j-1,0) and # if mouse is in the current cell than we have to subtract it bcoz we have         add it twice i.e, when we enter at this block # and when we leave this block for i in range(1,m): dp[(0,i,0)]=dp[(0,i,1)]=shadow[0][i]-mouse[0][i]+dp[(0,i-1,0)] # same goes for first column # we can only come at (i,0) from (i-1,0) i.e top for i in range(1,n): dp[(i,0,0)]=dp[(i,0,1)]=shadow[i][0]-mouse[i][0]+dp[(i-1,0,1)] # for rest of the blocks # for a block (i,j) we have to add shadow[i][j] and subtract mouse[i][j]         from it for double counting # now for each block we have two choices, either take its previous block         with same direction or take previous block with different # direction and subtract corner double counted mouse. We have to take min of         both to find optimal answer for i,j in product(list(range(1,n)),list(range(1,m))): a=shadow[i][j]-mouse[i][j] b=a a+=min(dp[(i,j-1,0)],dp[(i,j-1,1)]-mouse[i-1][j]) ...
python
train
abovesol
codeparrot/apps
all
I found an interesting problem on https://www.codewars.com/kata/54b72c16cd7f5154e9000457: Part of Series 2/3 This kata is part of a series on the Morse code. Make sure you solve the [previous part](/kata/decode-the-morse-code) before you try this one. After you solve this kata, you may move to the [next one](/kata/decode-the-morse-code-for-real). In this kata you have to write a Morse code decoder for wired electrical telegraph. Electric telegraph is operated on a 2-wire line with a key that, when pressed, connects the wires together, which can be detected on a remote station. The Morse code encodes every character being transmitted as a sequence of "dots" (short presses on the key) and "dashes" (long presses on the key). When transmitting the Morse code, the international standard specifies that: "Dot" – is 1 time unit long. "Dash" – is 3 time units long. Pause between dots and dashes in a character – is 1 time unit long. Pause between characters inside a word – is 3 time units long. Pause between words – is 7 time units long. However, the standard does not specify how long that "time unit" is. And in fact different operators would transmit at different speed. An amateur person may need a few seconds to transmit a single character, a skilled professional can transmit 60 words per minute, and robotic transmitters may go way faster. For this kata we assume the message receiving is performed automatically by the hardware that checks the line periodically, and if the line is connected (the key at the remote station is down), 1 is recorded, and if the line is not connected (remote key is up), 0 is recorded. After the message is fully received, it gets to you for decoding as a string containing only symbols 0 and 1. For example, the message HEY JUDE, that is ···· · −·−−   ·−−− ··− −·· · may be received as follows: 1100110011001100000011000000111111001100111111001111110000000000000011001111110011111100111111000000110011001111110000001111110011001100000011 As you may see, this transmission is perfectly accurate according to the standard, and the hardware sampled the line exactly two times per... I tried it in Python, but could not do it. Can you solve it?
from re import split def decodeBits(bits): unit = min([len(s) for s in split(r'0+',bits.strip('0'))] + [len(s) for s in split(r'1+',bits.strip('0')) if s != '']) return bits.replace('0'*unit*7,' ').replace('0'*unit*3,' ').replace('1'*unit*3,'-').replace('1'*unit,'.').replace('0','') def decodeMorse(morseCode): # ToDo: Accept dots, dashes and spaces, return human-readable message return ' '.join(''.join(MORSE_CODE[letter] for letter in word.split(' ')) for word in morseCode.strip().split(' '))
python
train
abovesol
codeparrot/apps
all
I found an interesting problem on https://codeforces.com/problemset/problem/1249/B1: The only difference between easy and hard versions is constraints. There are $n$ kids, each of them is reading a unique book. At the end of any day, the $i$-th kid will give his book to the $p_i$-th kid (in case of $i = p_i$ the kid will give his book to himself). It is guaranteed that all values of $p_i$ are distinct integers from $1$ to $n$ (i.e. $p$ is a permutation). The sequence $p$ doesn't change from day to day, it is fixed. For example, if $n=6$ and $p=[4, 6, 1, 3, 5, 2]$ then at the end of the first day the book of the $1$-st kid will belong to the $4$-th kid, the $2$-nd kid will belong to the $6$-th kid and so on. At the end of the second day the book of the $1$-st kid will belong to the $3$-th kid, the $2$-nd kid will belong to the $2$-th kid and so on. Your task is to determine the number of the day the book of the $i$-th child is returned back to him for the first time for every $i$ from $1$ to $n$. Consider the following example: $p = [5, 1, 2, 4, 3]$. The book of the $1$-st kid will be passed to the following kids: after the $1$-st day it will belong to the $5$-th kid, after the $2$-nd day it will belong to the $3$-rd kid, after the $3$-rd day it will belong to the $2$-nd kid, after the $4$-th day it will belong to the $1$-st kid. So after the fourth day, the book of the first kid will return to its owner. The book of the fourth kid will return to him for the first time after exactly one day. You have to answer $q$ independent queries. -----Input----- The first line of the input contains one integer $q$ ($1 \le q \le 200$) — the number of queries. Then $q$ queries follow. The first line of the query contains one integer $n$ ($1 \le n \le 200$) — the number of kids in the query. The second line of the query contains $n$ integers $p_1, p_2, \dots, p_n$ ($1 \le p_i \le n$, all $p_i$ are distinct, i.e. $p$ is a permutation), where $p_i$ is the kid which will get the book of the $i$-th kid. -----Output----- For each query, print the answer on it: $n$ integers $a_1, a_2, \dots,... I tried it in Python, but could not do it. Can you solve it?
tc = int(input()) while tc > 0: tc -= 1 n = int(input()) p = [0] + list(map(int, input().split())) ans = [0] * (n + 1) mk = [False] * (n + 1) for i in range(1 , n + 1): if not mk[i]: sz = 1 curr = p[i] mk[i] = True while curr != i: sz += 1 mk[curr] = True curr = p[curr] ans[i] = sz curr = p[i] while curr != i: ans[curr] = sz curr = p[curr] print(" ".join([str(x) for x in ans[1:]]))
python
test
abovesol
codeparrot/apps
all
Solve in Python: Codehorses has just hosted the second Codehorses Cup. This year, the same as the previous one, organizers are giving T-shirts for the winners. The valid sizes of T-shirts are either "M" or from $0$ to $3$ "X" followed by "S" or "L". For example, sizes "M", "XXS", "L", "XXXL" are valid and "XM", "Z", "XXXXL" are not. There are $n$ winners to the cup for both the previous year and the current year. Ksenia has a list with the T-shirt sizes printed for the last year cup and is yet to send the new list to the printing office. Organizers want to distribute the prizes as soon as possible, so now Ksenia is required not to write the whole list from the scratch but just make some changes to the list of the previous year. In one second she can choose arbitrary position in any word and replace its character with some uppercase Latin letter. Ksenia can't remove or add letters in any of the words. What is the minimal number of seconds Ksenia is required to spend to change the last year list to the current one? The lists are unordered. That means, two lists are considered equal if and only if the number of occurrences of any string is the same in both lists. -----Input----- The first line contains one integer $n$ ($1 \le n \le 100$) — the number of T-shirts. The $i$-th of the next $n$ lines contains $a_i$ — the size of the $i$-th T-shirt of the list for the previous year. The $i$-th of the next $n$ lines contains $b_i$ — the size of the $i$-th T-shirt of the list for the current year. It is guaranteed that all the sizes in the input are valid. It is also guaranteed that Ksenia can produce list $b$ from the list $a$. -----Output----- Print the minimal number of seconds Ksenia is required to spend to change the last year list to the current one. If the lists are already equal, print 0. -----Examples----- Input 3 XS XS M XL S XS Output 2 Input 2 XXXL XXL XXL XXXS Output 1 Input 2 M XS XS M Output 0 -----Note----- In the first example Ksenia can replace "M" with "S" and "S" in one of the occurrences of...
n = int(input()) a = [] b = [] for i in range(n): a.append(input()) for i in range(n): k = input() if k in a: a.remove(k) else: b.append(k) c = [0,0,0,0] for i in range(len(a)): c[len(a[i])-1] += 1 print(sum(c))
python
test
qsol
codeparrot/apps
all
I found an interesting problem on https://atcoder.jp/contests/abc109/tasks/abc109_c: There are N cities on a number line. The i-th city is located at coordinate x_i. Your objective is to visit all these cities at least once. In order to do so, you will first set a positive integer D. Then, you will depart from coordinate X and perform Move 1 and Move 2 below, as many times as you like: - Move 1: travel from coordinate y to coordinate y + D. - Move 2: travel from coordinate y to coordinate y - D. Find the maximum value of D that enables you to visit all the cities. Here, to visit a city is to travel to the coordinate where that city is located. -----Constraints----- - All values in input are integers. - 1 \leq N \leq 10^5 - 1 \leq X \leq 10^9 - 1 \leq x_i \leq 10^9 - x_i are all different. - x_1, x_2, ..., x_N \neq X -----Input----- Input is given from Standard Input in the following format: N X x_1 x_2 ... x_N -----Output----- Print the maximum value of D that enables you to visit all the cities. -----Sample Input----- 3 3 1 7 11 -----Sample Output----- 2 Setting D = 2 enables you to visit all the cities as follows, and this is the maximum value of such D. - Perform Move 2 to travel to coordinate 1. - Perform Move 1 to travel to coordinate 3. - Perform Move 1 to travel to coordinate 5. - Perform Move 1 to travel to coordinate 7. - Perform Move 1 to travel to coordinate 9. - Perform Move 1 to travel to coordinate 11. I tried it in Python, but could not do it. Can you solve it?
n,x = [int(x) for x in input().split()] a = [int(x) for x in input().split()] for i in range(n): a[i] = abs(a[i] - x) def gcd(x,y): while y != 0: x, y = y, x % y return x res = a[0] for i in range(n): res = gcd(res,a[i]) print(res)
python
test
abovesol
codeparrot/apps
all
I found an interesting problem on https://codeforces.com/problemset/problem/611/C: They say "years are like dominoes, tumbling one after the other". But would a year fit into a grid? I don't think so. Limak is a little polar bear who loves to play. He has recently got a rectangular grid with h rows and w columns. Each cell is a square, either empty (denoted by '.') or forbidden (denoted by '#'). Rows are numbered 1 through h from top to bottom. Columns are numbered 1 through w from left to right. Also, Limak has a single domino. He wants to put it somewhere in a grid. A domino will occupy exactly two adjacent cells, located either in one row or in one column. Both adjacent cells must be empty and must be inside a grid. Limak needs more fun and thus he is going to consider some queries. In each query he chooses some rectangle and wonders, how many way are there to put a single domino inside of the chosen rectangle? -----Input----- The first line of the input contains two integers h and w (1 ≤ h, w ≤ 500) – the number of rows and the number of columns, respectively. The next h lines describe a grid. Each line contains a string of the length w. Each character is either '.' or '#' — denoting an empty or forbidden cell, respectively. The next line contains a single integer q (1 ≤ q ≤ 100 000) — the number of queries. Each of the next q lines contains four integers r1_{i}, c1_{i}, r2_{i}, c2_{i} (1 ≤ r1_{i} ≤ r2_{i} ≤ h, 1 ≤ c1_{i} ≤ c2_{i} ≤ w) — the i-th query. Numbers r1_{i} and c1_{i} denote the row and the column (respectively) of the upper left cell of the rectangle. Numbers r2_{i} and c2_{i} denote the row and the column (respectively) of the bottom right cell of the rectangle. -----Output----- Print q integers, i-th should be equal to the number of ways to put a single domino inside the i-th rectangle. -----Examples----- Input 5 8 ....#..# .#...... ##.#.... ##..#.## ........ 4 1 1 2 3 4 1 4 1 1 2 4 5 2 5 5 8 Output 4 0 10 15 Input 7... I tried it in Python, but could not do it. Can you solve it?
h, w = list(map(int, input().split())) field = [[c == "." for c in input()] + [False] for i in range(h)] field.append([False] * (w + 1)) subVerts = [[0] * (w + 1) for i in range(h + 1)] subHoriz = [[0] * (w + 1) for i in range(h + 1)] for y in range(h): subVerts[y][0] = 0 subHoriz[y][0] = 0 for x in range(w): subHoriz[0][x] = 0 subVerts[0][x] = 0 for y in range(h): for x in range(w): subVerts[y + 1][x + 1] = subVerts[y + 1][x] + subVerts[y][x + 1] - subVerts[y][x] if field[y][x] and field[y - 1][x]: subVerts[y + 1][x + 1] += 1 subHoriz[y + 1][x + 1] = subHoriz[y + 1][x] + subHoriz[y][x + 1] - subHoriz[y][x] if field[y][x] and field[y][x - 1]: subHoriz[y + 1][x + 1] += 1 q = int(input()) for i in range(q): y1, x1, y2, x2 = [int(x) - 1 for x in input().split()] ansHoriz = subHoriz[y2 + 1][x2 + 1] - subHoriz[y1][x2 + 1] - subHoriz[y2 + 1][x1 + 1] + subHoriz[y1][x1 + 1] ansVerts = subVerts[y2 + 1][x2 + 1] - subVerts[y1 + 1][x2 + 1] - subVerts[y2 + 1][x1] + subVerts[y1 + 1][x1] print(ansHoriz + ansVerts)
python
test
abovesol
codeparrot/apps
all
I found an interesting problem on https://codeforces.com/problemset/problem/285/E: Permutation p is an ordered set of integers p_1, p_2, ..., p_{n}, consisting of n distinct positive integers, each of them doesn't exceed n. We'll denote the i-th element of permutation p as p_{i}. We'll call number n the size or the length of permutation p_1, p_2, ..., p_{n}. We'll call position i (1 ≤ i ≤ n) in permutation p_1, p_2, ..., p_{n} good, if |p[i] - i| = 1. Count the number of permutations of size n with exactly k good positions. Print the answer modulo 1000000007 (10^9 + 7). -----Input----- The single line contains two space-separated integers n and k (1 ≤ n ≤ 1000, 0 ≤ k ≤ n). -----Output----- Print the number of permutations of length n with exactly k good positions modulo 1000000007 (10^9 + 7). -----Examples----- Input 1 0 Output 1 Input 2 1 Output 0 Input 3 2 Output 4 Input 4 1 Output 6 Input 7 4 Output 328 -----Note----- The only permutation of size 1 has 0 good positions. Permutation (1, 2) has 0 good positions, and permutation (2, 1) has 2 positions. Permutations of size 3: (1, 2, 3) — 0 positions $(1,3,2)$ — 2 positions $(2,1,3)$ — 2 positions $(2,3,1)$ — 2 positions $(3,1,2)$ — 2 positions (3, 2, 1) — 0 positions I tried it in Python, but could not do it. Can you solve it?
mod=10**9+7 n,k=list(map(int,input().split())) A=[0]*(n+1) B=[0]*(n+1) C=[0]*(n+1) F=[0]*(n+1) G=[0]*(n+1) F[0]=G[0]=1 for i in range(1,n+1): G[i]=F[i]=F[i-1]*i%mod G[i]=pow(F[i],(mod-2),mod) for i in range(0,n): if i*2>n: break B[i]=(F[n-i]*G[i]*G[n-i*2])%mod for i in range(0,n//2+1): for j in range(0,n//2+1): A[i+j]=(A[i+j]+B[i]*B[j])%mod for i in range(0,n+1): A[i]=A[i]*F[n-i]%mod for i in range(0,n+1): for j in range(0,i+1): C[j]=(C[j]+A[i]*F[i]*G[j]*G[i-j]*(1-(i-j)%2*2))%mod print(C[k]%mod)
python
test
abovesol
codeparrot/apps
all
I found an interesting problem on https://www.codechef.com/SPRT2020/problems/STCKSCAM: $Harshad$ $Mehta$ is planning a new scam with the stocks he is given a stock of integer price S and a number K . $harshad$ has got the power to change the number $S$ at most $K$ times In order to raise the price of stock and now cash it for his benefits Find the largest price at which $harshad$ can sell the stock in order to maximize his profit -----Input:----- - First line will contain $S$ and $K$ , the price of the stock and the number K -----Output:----- Print the largest profit he can make in a single line. -----Constraints----- - S can take value upto 10^18 NOTE: use 64 int number to fit range - K can take value from [0.. 9] -----Sample Input:----- 4483 2 -----Sample Output:----- 9983 -----EXPLANATION:----- First two digits of the number are changed to get the required number. I tried it in Python, but could not do it. Can you solve it?
# cook your dish here n,k = map(int, input().split()) n = str(n) for i in range(len(n)): if(k == 0): break if(n[i]!='9'): n = n[:i]+'9'+n[i+1:] k-=1 print(n)
python
train
abovesol
codeparrot/apps
all
I found an interesting problem on https://leetcode.com/problems/find-words-that-can-be-formed-by-characters/: You are given an array of strings words and a string chars. A string is good if it can be formed by characters from chars (each character can only be used once). Return the sum of lengths of all good strings in words.   Example 1: Input: words = ["cat","bt","hat","tree"], chars = "atach" Output: 6 Explanation: The strings that can be formed are "cat" and "hat" so the answer is 3 + 3 = 6. Example 2: Input: words = ["hello","world","leetcode"], chars = "welldonehoneyr" Output: 10 Explanation: The strings that can be formed are "hello" and "world" so the answer is 5 + 5 = 10.   Note: 1 <= words.length <= 1000 1 <= words[i].length, chars.length <= 100 All strings contain lowercase English letters only. I tried it in Python, but could not do it. Can you solve it?
class Solution: def countCharacters(self, words: List[str], chars: str) -> int: charChars = Counter(chars) counter = 0 for word in words: countC = Counter(word) count = 0 for letter in countC.items(): if letter[0] in charChars and charChars[letter[0]] >= letter[1]: count += 1 if count == len(countC): counter += len(word) return counter
python
train
abovesol
codeparrot/apps
all
I found an interesting problem on https://codeforces.com/problemset/problem/1372/B: In Omkar's last class of math, he learned about the least common multiple, or $LCM$. $LCM(a, b)$ is the smallest positive integer $x$ which is divisible by both $a$ and $b$. Omkar, having a laudably curious mind, immediately thought of a problem involving the $LCM$ operation: given an integer $n$, find positive integers $a$ and $b$ such that $a + b = n$ and $LCM(a, b)$ is the minimum value possible. Can you help Omkar solve his ludicrously challenging math problem? -----Input----- Each test contains multiple test cases. The first line contains the number of test cases $t$ ($1 \leq t \leq 10$). Description of the test cases follows. Each test case consists of a single integer $n$ ($2 \leq n \leq 10^{9}$). -----Output----- For each test case, output two positive integers $a$ and $b$, such that $a + b = n$ and $LCM(a, b)$ is the minimum possible. -----Example----- Input 3 4 6 9 Output 2 2 3 3 3 6 -----Note----- For the first test case, the numbers we can choose are $1, 3$ or $2, 2$. $LCM(1, 3) = 3$ and $LCM(2, 2) = 2$, so we output $2 \ 2$. For the second test case, the numbers we can choose are $1, 5$, $2, 4$, or $3, 3$. $LCM(1, 5) = 5$, $LCM(2, 4) = 4$, and $LCM(3, 3) = 3$, so we output $3 \ 3$. For the third test case, $LCM(3, 6) = 6$. It can be shown that there are no other pairs of numbers which sum to $9$ that have a lower $LCM$. I tried it in Python, but could not do it. Can you solve it?
import math from collections import deque from sys import stdin, stdout input = stdin.readline #print = stdout.write for _ in range(int(input())): x = int(input()) ind = 2 mn = 99999999999999 while ind * ind <= x: if x % ind == 0: mn = min(mn, ind) mn = min(mn, x // ind) ind += 1 if mn == 99999999999999: mn = x print(x // mn, x - x // mn)
python
test
abovesol
codeparrot/apps
all
I found an interesting problem on https://codeforces.com/problemset/problem/1225/E: You are at the top left cell $(1, 1)$ of an $n \times m$ labyrinth. Your goal is to get to the bottom right cell $(n, m)$. You can only move right or down, one cell per step. Moving right from a cell $(x, y)$ takes you to the cell $(x, y + 1)$, while moving down takes you to the cell $(x + 1, y)$. Some cells of the labyrinth contain rocks. When you move to a cell with rock, the rock is pushed to the next cell in the direction you're moving. If the next cell contains a rock, it gets pushed further, and so on. The labyrinth is surrounded by impenetrable walls, thus any move that would put you or any rock outside of the labyrinth is illegal. Count the number of different legal paths you can take from the start to the goal modulo $10^9 + 7$. Two paths are considered different if there is at least one cell that is visited in one path, but not visited in the other. -----Input----- The first line contains two integers $n, m$ — dimensions of the labyrinth ($1 \leq n, m \leq 2000$). Next $n$ lines describe the labyrinth. Each of these lines contains $m$ characters. The $j$-th character of the $i$-th of these lines is equal to "R" if the cell $(i, j)$ contains a rock, or "." if the cell $(i, j)$ is empty. It is guaranteed that the starting cell $(1, 1)$ is empty. -----Output----- Print a single integer — the number of different legal paths from $(1, 1)$ to $(n, m)$ modulo $10^9 + 7$. -----Examples----- Input 1 1 . Output 1 Input 2 3 ... ..R Output 0 Input 4 4 ...R .RR. .RR. R... Output 4 -----Note----- In the first sample case we can't (and don't have to) move, hence the only path consists of a single cell $(1, 1)$. In the second sample case the goal is blocked and is unreachable. Illustrations for the third sample case can be found here: https://assets.codeforces.com/rounds/1225/index.html I tried it in Python, but could not do it. Can you solve it?
def getSum(dp, pos, s, e, type_): if e < s: return 0 if type_=='D': if e==m-1: return dp[pos][s] return dp[pos][s]-dp[pos][e+1] else: if e==n-1: return dp[s][pos] return dp[s][pos]-dp[e+1][pos] mod = 10**9+7 n, m = map(int, input().split()) a = [list(list(map(lambda x: 1 if x=='R' else 0, input()))) for _ in range(n)] SD = [[0]*m for _ in range(n)] SN = [[0]*m for _ in range(n)] dpD = [[0]*m for _ in range(n)] dpN = [[0]*m for _ in range(n)] for i in range(n-1, -1, -1): for j in range(m-1, -1, -1): if i == n-1: SD[i][j]=a[i][j] else: SD[i][j]=SD[i+1][j]+a[i][j] if j == m-1: SN[i][j]=a[i][j] else: SN[i][j]=SN[i][j+1]+a[i][j] for j in range(m-1,-1,-1): if a[n-1][j]==1: break dpD[n-1][j]=1 dpN[n-1][j]=1 for i in range(n-1,-1,-1): if a[i][m-1]==1: break dpD[i][m-1]=1 dpN[i][m-1]=1 for j in range(m-2, -1, -1): if i==n-1: break dpD[n-1][j]+=dpD[n-1][j+1] for i in range(n-2,-1,-1): if j==m-1: break dpN[i][m-1]+=dpN[i+1][m-1] for i in range(n-2,-1,-1): for j in range(m-2,-1,-1): s, e = j, m-SN[i][j]-1 #print(i, j, s, e, 'N') dpN[i][j] = getSum(dpD, i+1, s, e, 'D') dpN[i][j] = (dpN[i][j] + dpN[i+1][j]) % mod s, e = i, n-SD[i][j]-1 #print(i, j, s, e, 'D') dpD[i][j] = getSum(dpN, j+1, s, e, 'N') if i != 0: for j in range(m-2,-1,-1): dpD[i][j] = (dpD[i][j] + dpD[i][j+1]) % mod print(dpD[0][0] % mod)
python
train
abovesol
codeparrot/apps
all
I found an interesting problem on https://codeforces.com/problemset/problem/767/A: According to an old legeng, a long time ago Ankh-Morpork residents did something wrong to miss Fortune, and she cursed them. She said that at some time n snacks of distinct sizes will fall on the city, and the residents should build a Snacktower of them by placing snacks one on another. Of course, big snacks should be at the bottom of the tower, while small snacks should be at the top. Years passed, and once different snacks started to fall onto the city, and the residents began to build the Snacktower. [Image] However, they faced some troubles. Each day exactly one snack fell onto the city, but their order was strange. So, at some days the residents weren't able to put the new stack on the top of the Snacktower: they had to wait until all the bigger snacks fell. Of course, in order to not to anger miss Fortune again, the residents placed each snack on the top of the tower immediately as they could do it. Write a program that models the behavior of Ankh-Morpork residents. -----Input----- The first line contains single integer n (1 ≤ n ≤ 100 000) — the total number of snacks. The second line contains n integers, the i-th of them equals the size of the snack which fell on the i-th day. Sizes are distinct integers from 1 to n. -----Output----- Print n lines. On the i-th of them print the sizes of the snacks which the residents placed on the top of the Snacktower on the i-th day in the order they will do that. If no snack is placed on some day, leave the corresponding line empty. -----Examples----- Input 3 3 1 2 Output 3   2 1 Input 5 4 5 1 2 3 Output   5 4     3 2 1 -----Note----- In the example a snack of size 3 fell on the first day, and the residents immediately placed it. On the second day a snack of size 1 fell, and the residents weren't able to place it because they were missing the snack of size 2. On the third day a snack of size 2 fell, and the residents immediately placed it. Right after that they placed the snack of size 1 which had fallen before. I tried it in Python, but could not do it. Can you solve it?
n = int(input()) maxsn = n-1 a = list(map(int, input().split())) snacks = [0] * 100001 for i in range(n): snacks[a[i]-1] = 1 while snacks[maxsn] == 1: snacks[maxsn] = 0 print(maxsn + 1, end=' ') maxsn -= 1 print()
python
test
abovesol
codeparrot/apps
all
Solve in Python: Iahub is a big fan of tourists. He wants to become a tourist himself, so he planned a trip. There are n destinations on a straight road that Iahub wants to visit. Iahub starts the excursion from kilometer 0. The n destinations are described by a non-negative integers sequence a_1, a_2, ..., a_{n}. The number a_{k} represents that the kth destination is at distance a_{k} kilometers from the starting point. No two destinations are located in the same place. Iahub wants to visit each destination only once. Note that, crossing through a destination is not considered visiting, unless Iahub explicitly wants to visit it at that point. Also, after Iahub visits his last destination, he doesn't come back to kilometer 0, as he stops his trip at the last destination. The distance between destination located at kilometer x and next destination, located at kilometer y, is |x - y| kilometers. We call a "route" an order of visiting the destinations. Iahub can visit destinations in any order he wants, as long as he visits all n destinations and he doesn't visit a destination more than once. Iahub starts writing out on a paper all possible routes and for each of them, he notes the total distance he would walk. He's interested in the average number of kilometers he would walk by choosing a route. As he got bored of writing out all the routes, he asks you to help him. -----Input----- The first line contains integer n (2 ≤ n ≤ 10^5). Next line contains n distinct integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10^7). -----Output----- Output two integers — the numerator and denominator of a fraction which is equal to the wanted average number. The fraction must be irreducible. -----Examples----- Input 3 2 3 5 Output 22 3 -----Note----- Consider 6 possible routes: [2, 3, 5]: total distance traveled: |2 – 0| + |3 – 2| + |5 – 3| = 5; [2, 5, 3]: |2 – 0| + |5 – 2| + |3 – 5| = 7; [3, 2, 5]: |3 – 0| + |2 – 3| + |5 – 2| = 7; [3, 5, 2]: |3 – 0| + |5 – 3| + |2 – 5| = 8; [5, 2, 3]: |5 – 0| + |2 – 5| + |3 – 2| = 9; [5, 3,...
import math n = int(input()) a = list(map(int, input().split())) a.sort(reverse = True) k = 0 s1 = 0 s2 = 0 for i in a: s2 += s1 - k * i s1 += i k += 1 s2 *= 2 s2 += sum(a) gcd = math.gcd(s2, n) print(s2 // gcd, n // gcd)
python
test
qsol
codeparrot/apps
all
Solve in Python: An acrostic is a text in which the first letter of each line spells out a word. It is also a quick and cheap way of writing a poem for somebody, as exemplified below : Write a program that reads an acrostic to identify the "hidden" word. Specifically, your program will receive a list of words (reprensenting an acrostic) and will need to return a string corresponding to the word that is spelled out by taking the first letter of each word in the acrostic.
def read_out(acrostic): return "".join( word[0] for word in acrostic )
python
train
qsol
codeparrot/apps
all
I found an interesting problem on https://codeforces.com/problemset/problem/1342/E: Calculate the number of ways to place $n$ rooks on $n \times n$ chessboard so that both following conditions are met: each empty cell is under attack; exactly $k$ pairs of rooks attack each other. An empty cell is under attack if there is at least one rook in the same row or at least one rook in the same column. Two rooks attack each other if they share the same row or column, and there are no other rooks between them. For example, there are only two pairs of rooks that attack each other in the following picture: [Image] One of the ways to place the rooks for $n = 3$ and $k = 2$ Two ways to place the rooks are considered different if there exists at least one cell which is empty in one of the ways but contains a rook in another way. The answer might be large, so print it modulo $998244353$. -----Input----- The only line of the input contains two integers $n$ and $k$ ($1 \le n \le 200000$; $0 \le k \le \frac{n(n - 1)}{2}$). -----Output----- Print one integer — the number of ways to place the rooks, taken modulo $998244353$. -----Examples----- Input 3 2 Output 6 Input 3 3 Output 0 Input 4 0 Output 24 Input 1337 42 Output 807905441 I tried it in Python, but could not do it. Can you solve it?
def modpow(b, e, mod): ret = 1 pw = b while e > 0: if e % 2 == 1: ret = (ret * pw) % mod e = e >> 1 pw = (pw * pw) % mod return ret n, k = list(map(int, input().split())) mod = 998244353 inv = [0 for _ in range(n + 1)] fac = [0 for _ in range(n + 1)] fac[0] = inv[0] = 1 for i in range(n): fac[i + 1] = (fac[i] * (i + 1)) % mod inv[i + 1] = modpow(fac[i + 1], mod - 2, mod) def nCr(n, r): num = fac[n] den = (inv[r] * inv[n - r]) % mod return (num * den) % mod row = n - k if row < 0 or row > n: print('0') else: ans = 0 for i in range(row): add = (nCr(row, i) * modpow(row - i, n, mod)) % mod if i % 2 == 0: ans = ans + add else: ans = ans - add ans = mod + (ans % mod) mult = 2 if row == n: mult = 1 print((mult * nCr(n, row) * ans) % mod)
python
test
abovesol
codeparrot/apps
all
Solve in Python: You are given a chess board with $n$ rows and $n$ columns. Initially all cells of the board are empty, and you have to put a white or a black knight into each cell of the board. A knight is a chess piece that can attack a piece in cell ($x_2$, $y_2$) from the cell ($x_1$, $y_1$) if one of the following conditions is met: $|x_1 - x_2| = 2$ and $|y_1 - y_2| = 1$, or $|x_1 - x_2| = 1$ and $|y_1 - y_2| = 2$. Here are some examples of which cells knight can attack. In each of the following pictures, if the knight is currently in the blue cell, it can attack all red cells (and only them). [Image] A duel of knights is a pair of knights of different colors such that these knights attack each other. You have to put a knight (a white one or a black one) into each cell in such a way that the number of duels is maximum possible. -----Input----- The first line contains one integer $n$ ($3 \le n \le 100$) — the number of rows (and columns) in the board. -----Output----- Print $n$ lines with $n$ characters in each line. The $j$-th character in the $i$-th line should be W, if the cell ($i$, $j$) contains a white knight, or B, if it contains a black knight. The number of duels should be maximum possible. If there are multiple optimal answers, print any of them. -----Example----- Input 3 Output WBW BBB WBW -----Note----- In the first example, there are $8$ duels: the white knight in ($1$, $1$) attacks the black knight in ($3$, $2$); the white knight in ($1$, $1$) attacks the black knight in ($2$, $3$); the white knight in ($1$, $3$) attacks the black knight in ($3$, $2$); the white knight in ($1$, $3$) attacks the black knight in ($2$, $1$); the white knight in ($3$, $1$) attacks the black knight in ($1$, $2$); the white knight in ($3$, $1$) attacks the black knight in ($2$, $3$); the white knight in ($3$, $3$) attacks the black knight in ($1$, $2$); the white knight in ($3$, $3$) attacks the black knight in ($2$, $1$).
n = int(input()) mat = [[0 for i in range(n)] for j in range(n)] for i in range(n): for j in range(n): if (i + j) % 2 == 1: mat[i][j] = 'W' else: mat[i][j] = 'B' for i in range(n): for j in range(n): if j < n-1: print(mat[i][j], end = "") else: print(mat[i][j])
python
test
qsol
codeparrot/apps
all
Solve in Python: Bobby has decided to hunt some Parrots. There are n horizontal branch of trees aligned parallel to each other. Branches are numbered 1 to n from top to bottom. On each branch there are some parrots sitting next to each other. Supposed there are a[i]$a[i]$ parrots sitting on the i−th$ i-th$ branch. Sometimes Bobby shots one of the parrot and the parrot dies (suppose that this parrots sat at the i−th$i-th$ branch). Consequently all the parrots on the i−th$i-th$ branch to the left of the dead parrot get scared and jump up on the branch number i − 1$i - 1$, if there exists no upper branch they fly away. Also all the parrots to the right of the dead parrot jump down on branch number i + 1$i + 1$, if there exists no such branch they fly away. Bobby has shot m parrots. You're given the initial number of parrots on each branch, tell him how many parrots are sitting on each branch after the shots. -----Input:----- The first line of the input contains an integer N$N$. The next line contains a list of space-separated integers a1, a2, …, an. The third line contains an integer M$M$. Each of the next M$M$ lines contains two integers x[i]$x[i]$ and y[i]$y[i]$. The integers mean that for the i-th time Bobby shoot the y[i]-th (from left) parrot on the x[i]-th branch. It's guaranteed there will be at least y[i] parrot on the x[i]-th branch at that moment. -----Output:----- On the i−th$i-th$ line of the output print the number of parrots on the i−th$i-th$ branch. -----Constraints----- - 1≤N≤100$1 \leq N \leq 100$ - 0≤a[i]≤100$0 \leq a[i] \leq 100$ - 0≤M≤100$0 \leq M \leq 100$ - 1≤x[i]≤n$1 \leq x[i] \leq n$, 1≤y[i]$1 \leq y[i] $ -----Sample Input:----- 5 10 10 10 10 10 5 2 5 3 13 2 12 1 13 4 6 3 2 4 1 1 2 2 -----Sample Output:----- 0 12 5 0 16 3 0 3
n = int(input()) A = list(map(int, input().split())) m = int(input()) for _ in range(m): x, y = map(int, input().split()) x -= 1 y -= 1 left = y right = A[x] - left - 1 A[x] = 0 if x - 1 >= 0: A[x - 1] += left if x + 1 < n: A[x + 1] += right for a in A: print(a)
python
train
qsol
codeparrot/apps
all
Solve in Python: =====Problem Statement===== Mr. Anant Asankhya is the manager at the INFINITE hotel. The hotel has an infinite amount of rooms. One fine day, a finite number of tourists come to stay at the hotel. The tourists consist of: → A Captain. → An unknown group of families consisting of K members per group where K ≠ 1. The Captain was given a separate room, and the rest were given one room per group. Mr. Anant has an unordered list of randomly arranged room entries. The list consists of the room numbers for all of the tourists. The room numbers will appear K times per group except for the Captain's room. Mr. Anant needs you to help him find the Captain's room number. The total number of tourists or the total number of groups of families is not known to you. You only know the value of K and the room number list. =====Input Format===== The first consists of an integer, K, the size of each group. The second line contains the unordered elements of the room number list. =====Constraints===== 1<K<1000 =====Output Format===== Output the Captain's room number.
#!/usr/bin/env python3 def __starting_point(): k = int(input().strip()) numbers = list(map(int, input().strip().split(' '))) print((sum(set(numbers))*k - sum(numbers))//(k-1)) __starting_point()
python
train
qsol
codeparrot/apps
all
Solve in Python: There is a knight - the chess piece - at the origin (0, 0) of a two-dimensional grid. When the knight is at the square (i, j), it can be moved to either (i+1,j+2) or (i+2, j+1). In how many ways can the knight reach the square (X, Y)? Find the number of ways modulo 10^9 + 7. -----Constraints----- - 1 \leq X \leq 10^6 - 1 \leq Y \leq 10^6 - All values in input are integers. -----Input----- Input is given from Standard Input in the following format: X Y -----Output----- Print the number of ways for the knight to reach (X, Y) from (0, 0), modulo 10^9 + 7. -----Sample Input----- 3 3 -----Sample Output----- 2 There are two ways: (0,0) \to (1,2) \to (3,3) and (0,0) \to (2,1) \to (3,3).
X,Y = map(int,input().split()) mod = 10**9+7 N = (X+Y)//3 M = (N+X-Y)//2 if (X+Y)%3!=0 or M<0 or N<M: print(0) else: ans = 1 for m in range(1,M+1): ans*=(N-M+m)*pow(m,mod-2,mod) ans%=mod print(ans)
python
test
qsol
codeparrot/apps
all
I found an interesting problem on https://atcoder.jp/contests/arc094/tasks/arc094_b: 10^{10^{10}} participants, including Takahashi, competed in two programming contests. In each contest, all participants had distinct ranks from first through 10^{10^{10}}-th. The score of a participant is the product of his/her ranks in the two contests. Process the following Q queries: - In the i-th query, you are given two positive integers A_i and B_i. Assuming that Takahashi was ranked A_i-th in the first contest and B_i-th in the second contest, find the maximum possible number of participants whose scores are smaller than Takahashi's. -----Constraints----- - 1 \leq Q \leq 100 - 1\leq A_i,B_i\leq 10^9(1\leq i\leq Q) - All values in input are integers. -----Input----- Input is given from Standard Input in the following format: Q A_1 B_1 : A_Q B_Q -----Output----- For each query, print the maximum possible number of participants whose scores are smaller than Takahashi's. -----Sample Input----- 8 1 4 10 5 3 3 4 11 8 9 22 40 8 36 314159265 358979323 -----Sample Output----- 1 12 4 11 14 57 31 671644785 Let us denote a participant who was ranked x-th in the first contest and y-th in the second contest as (x,y). In the first query, (2,1) is a possible candidate of a participant whose score is smaller than Takahashi's. There are never two or more participants whose scores are smaller than Takahashi's, so we should print 1. I tried it in Python, but could not do it. Can you solve it?
n = int(input()) for i in range(n): a,b= list(map(int, input().split( ))) #解説参照 #何度見ても解けない #どちらかは高橋君より良い #a<=bとする #a=b (1~a-1)*2 #a<b c**2<abとする #c(c+1)>=ab?2c-2 / 2c-1 if a==b: print((2*a-2)) else: c = int((a*b)**(1/2)) if c*c==a*b: c -= 1 if c*c+c>=a*b: print((2*c-2)) else: print((2*c-1))
python
train
abovesol
codeparrot/apps
all
I found an interesting problem on https://www.codechef.com/problems/TRACE: Chef is learning linear algebra. Recently, he learnt that for a square matrix $M$, $\mathop{\rm trace}(M)$ is defined as the sum of all elements on the main diagonal of $M$ (an element lies on the main diagonal if its row index and column index are equal). Now, Chef wants to solve some excercises related to this new quantity, so he wrote down a square matrix $A$ with size $N\times N$. A square submatrix of $A$ with size $l\times l$ is a contiguous block of $l\times l$ elements of $A$. Formally, if $B$ is a submatrix of $A$ with size $l\times l$, then there must be integers $r$ and $c$ ($1\le r, c \le N+1-l$) such that $B_{i,j} = A_{r+i-1, c+j-1}$ for each $1 \le i, j \le l$. Help Chef find the maximum trace of a square submatrix of $A$. -----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$. - $N$ lines follow. For each $i$ ($1 \le i \le N$), the $i$-th of these lines contains $N$ space-separated integers $A_{i,1}, A_{i,2}, \dots, A_{i, N}$ denoting the $i$-th row of the matrix $A$. -----Output----- For each test case, print a single line containing one integer — the maximum possible trace. -----Constraints----- - $1 \le T \le 100$ - $2 \le N \le 100$ - $1 \le A_{i,j} \le 100$ for each valid $i, j$ -----Subtasks----- Subtask #1 (100 points): original constraints -----Example Input----- 1 3 1 2 5 6 3 4 2 7 1 -----Example Output----- 13 -----Explanation----- Example case 1: The submatrix with the largest trace is 6 3 2 7 which has trace equal to $6 + 7 = 13$. (This submatrix is obtained for $r=2, c=1, l=2$.) I tried it in Python, but could not do it. Can you solve it?
# cook your dish here for i in range(int(input())): h = int(input()) f = [] ans = [] for j in range(0,h): f.append(list(map(int,input().split()))) for k in range(0,h): sum1 = 0 sum2 = 0 for l in range(0,k+1): sum1 += f[l][h+l-k-1] sum2 += f[h+l-k-1][l] ans.append(sum1) ans.append(sum2) print(max(ans))
python
train
abovesol
codeparrot/apps
all
I found an interesting problem on https://www.codewars.com/kata/59e1254d0863c7808d0000ef: # Fourier transformations are hard. Fouriest transformations are harder. This Kata is based on the SMBC Comic on fourier transformations. A fourier transformation on a number is one that converts the number to a base in which it has more `4`s ( `10` in base `6` is `14`, which has `1` four as opposed to none, hence, fourier in base `6` ). A number's fouriest transformation converts it to the base in which it has the most `4`s. For example: `35353` is the fouriest in base `6`: `431401`. This kata requires you to create a method `fouriest` that takes a number and makes it the fouriest, telling us in which base this happened, as follows: ```python fouriest(number) -> "{number} is the fouriest ({fouriest_representation}) in base {base}" ``` ## Important notes * For this kata we don't care about digits greater than `9` ( only `0` to `9` ), so we will represent all digits greater than `9` as `'x'`: `10` in base `11` is `'x'`, `119` in base `20` is `'5x'`, `118` in base `20` is also `'5x'` * When a number has several fouriest representations, we want the one with the LOWEST base ```if:haskell,javascript * Numbers below `9` will not be tested ``` ```if:javascript * A `BigNumber` library has been provided; documentation is [here](https://mikemcl.github.io/bignumber.js/) ``` ## Examples ```python "30 is the fouriest (42) in base 7" "15 is the fouriest (14) in base 11" ``` I tried it in Python, but could not do it. Can you solve it?
def change_base(n, b): result = '' while n > 0: rem = n % b if n % b <=9 else 'x' result = str(rem) + result n //= b return result def fouriest(n): bb, br = None, 0 for i in range(2, n): res = list(change_base(n, i)) nf = res.count('4') if br >= len(res): break elif nf > br: br, bb = nf, i return f"{n} is the fouriest ({change_base(n, bb)}) in base {bb}"
python
train
abovesol
codeparrot/apps
all
I found an interesting problem on https://codeforces.com/problemset/problem/1419/A: Everyone knows that agents in Valorant decide, who will play as attackers, and who will play as defenders. To do that Raze and Breach decided to play $t$ matches of a digit game... In each of $t$ matches of the digit game, a positive integer is generated. It consists of $n$ digits. The digits of this integer are numerated from $1$ to $n$ from the highest-order digit to the lowest-order digit. After this integer is announced, the match starts. Agents play in turns. Raze starts. In one turn an agent can choose any unmarked digit and mark it. Raze can choose digits on odd positions, but can not choose digits on even positions. Breach can choose digits on even positions, but can not choose digits on odd positions. The match ends, when there is only one unmarked digit left. If the single last digit is odd, then Raze wins, else Breach wins. It can be proved, that before the end of the match (for every initial integer with $n$ digits) each agent has an ability to make a turn, i.e. there is at least one unmarked digit, that stands on a position of required parity. For each of $t$ matches find out, which agent wins, if both of them want to win and play optimally. -----Input----- First line of input contains an integer $t$ $(1 \le t \le 100)$  — the number of matches. The first line of each match description contains an integer $n$ $(1 \le n \le 10^3)$  — the number of digits of the generated number. The second line of each match description contains an $n$-digit positive integer without leading zeros. -----Output----- For each match print $1$, if Raze wins, and $2$, if Breach wins. -----Example----- Input 4 1 2 1 3 3 102 4 2069 Output 2 1 1 2 -----Note----- In the first match no one can make a turn, the only digit left is $2$, it's even, so Breach wins. In the second match the only digit left is $3$, it's odd, so Raze wins. In the third match Raze can mark the last digit, after that Breach can only mark $0$. $1$ will be the last digit left, it's odd, so Raze wins. In the fourth match no matter... I tried it in Python, but could not do it. Can you solve it?
for _ in range(int(input())): n=int(input()) s=input() if n%2==1: a=[int(i)%2 for i in s[::2]] if 1 in a:print(1) else:print(2) else: a=[int(i)%2 for i in s[1::2]] if 0 in a:print(2) else:print(1)
python
test
abovesol
codeparrot/apps
all
Solve in Python: This is a hard version of the problem. The actual problems are different, but the easy version is almost a subtask of the hard version. Note that the constraints and the output format are different. You are given a string $s$ consisting of $n$ lowercase Latin letters. You have to color all its characters the minimum number of colors (each character to exactly one color, the same letters can be colored the same or different colors, i.e. you can choose exactly one color for each index in $s$). After coloring, you can swap any two neighboring characters of the string that are colored different colors. You can perform such an operation arbitrary (possibly, zero) number of times. The goal is to make the string sorted, i.e. all characters should be in alphabetical order. Your task is to find the minimum number of colors which you have to color the given string in so that after coloring it can become sorted by some sequence of swaps. Note that you have to restore only coloring, not the sequence of swaps. -----Input----- The first line of the input contains one integer $n$ ($1 \le n \le 2 \cdot 10^5$) — the length of $s$. The second line of the input contains the string $s$ consisting of exactly $n$ lowercase Latin letters. -----Output----- In the first line print one integer $res$ ($1 \le res \le n$) — the minimum number of colors in which you have to color the given string so that after coloring it can become sorted by some sequence of swaps. In the second line print any possible coloring that can be used to sort the string using some sequence of swaps described in the problem statement. The coloring is the array $c$ of length $n$, where $1 \le c_i \le res$ and $c_i$ means the color of the $i$-th character. -----Examples----- Input 9 abacbecfd Output 2 1 1 2 1 2 1 2 1 2 Input 8 aaabbcbb Output 2 1 2 1 2 1 2 1 1 Input 7 abcdedc Output 3 1 1 1 1 1 2 3 Input 5 abcde Output 1 1 1 1 1 1
import sys # inf = open('input.txt', 'r') # reader = (line.rstrip() for line in inf) reader = (line.rstrip() for line in sys.stdin) input = reader.__next__ def ceil(tails, L, R, key): while L + 1 < R: m = (L + R) // 2 if key < tails[m]: L = m else: R = m return R def LIS(a, n): tails = [0] * (n + 1) tails[0] = a[0] seq_len = 1 # LIS for a[:1] for i in range(1, n): if (a[i] > tails[0]): # edit for other order tails[0] = a[i] # new LIS start ans.append(1) elif (a[i] < tails[seq_len - 1]): # edit for other order tails[seq_len] = a[i] # extend existing LIS seq_len += 1 ans.append(seq_len) else: # find LIS that ends in a[i] and update tail value for it pos = ceil(tails, -1, seq_len - 1, a[i]) tails[pos] = a[i] ans.append(pos + 1) return seq_len n = int(input()) s = input() ans = [1] res = LIS(s, n) print(res) print(*ans) # inf.close()
python
test
qsol
codeparrot/apps
all
Solve in Python: A grammar is a set of rules that let us define a language. These are called **production rules** and can be derived into many different tools. One of them is **String Rewriting Systems** (also called Semi-Thue Systems or Markov Algorithms). Ignoring technical details, they are a set of rules that substitute ocurrences in a given string by other strings. The rules have the following format: ``` str1 -> str2 ``` We define a rule application as the substitution of a substring following a rule. If this substring appears more than once, only one of this occurences is substituted and any of them is equally valid as an option: ```python 'a' -> 'c' # Substitution rule 'aba' # Base string 'cba' # One application on position 0 'abc' # One application on position 2 'cbc' # Two applications ``` Another valid example of rule application would be the following: ```python # Rules 'l' -> 'de' 'm' -> 'col' 'rr' -> 'wakr' 'akr' -> 'ars' # Application 'mrr' # Starting string 'colrr' # Second rule 'coderr' # First rule 'codewakr' # Third rule 'codewars' # Last rule ``` Note that this example is exhaustive, but Semi-Thue Systems can be potentially infinite: ```python # Rules 'a' -> 'aa' # Application 'a' # Starting string 'aa' # First application 'aaa' # Second application ... ``` The so called **Word Problem** is to decide whether or not a string can be derived from another using these rules. This is an **undecidable problem**, but if we restrict it to a certain number of applications, we can give it a solution. Your task is to write a function that solves the word problem given a maximum number of rule applications. **Python:** The rules are given as tuples where the left and the right handside of the rule correspond to the first and the second element respectively. **Notes:** * Two rules can have the same left handside and a different right handside. * You do not have to worry too much about performance yet. A simple, funtional answer will be enough.
from collections import defaultdict def word_problem(rules, from_str, to_str, applications): d = defaultdict(list) for x, y in rules: d[y].append(x) b, visited = False, set() def dfs(s, p=0): nonlocal b if s == from_str: b = p <= applications return if p >= len(to_str) or s in visited: return for i in range(0, len(s)): for j in range(i+1, len(s)+1): k = s[i:j] if k in d: for v in d[k]: dfs(s[:i] + v + s[j:], p + 1) visited.add(s) dfs(to_str) return b
python
train
qsol
codeparrot/apps
all
I found an interesting problem on https://www.codewars.com/kata/5536aba6e4609cc6a600003d: Once upon a time, a CodeWarrior, after reading a [discussion on what can be the plural](http://www.codewars.com/kata/plural/discuss/javascript), took a look at [this page](http://en.wikipedia.org/wiki/Grammatical_number#Types_of_number ) and discovered that **more than 1** "kind of plural" may exist. For example [Sursurunga Language](http://en.wikipedia.org/wiki/Sursurunga_language) distinguishes 5 types of numbers: **singular** (1 thing), **dual** (2 things), '**trial**' or '**lesser paucal**' (3 or 4), '**greater paucal**' (more than 4) and **plural** (many). In this kata, you'll have to handle only four types of numbers: - **singular**: 0 or 1 thing - **dual**: 2 things - **paucal**: 3 to 9 things - **plural**: more than 9 things To add some flavor the **number-marker** will not be added in same places: - **singular**, no marker : `1 cat` - **dual**, prefixed "`bu`" : `2 cats -> 2 bucat` - **paucal**, suffixed "`zo`" : `4 cats -> 4 catzo` - **plural**, "circumfixed `ga`" : `100 cats -> 100 gacatga` As you all ("hawk eyes") have seen, the final `s` of english plural **disappears**. ( btw these markers, of course, have absolutely nothing to do with true sursurunga language, we're just talking about "**pig**-sursurunga" with **pig** as **pig** in "**pig latin**" ) ## Your Job . . . . . . if you accept it, will be to write a `sursurungal` function which get a `string` as argument and returns this string with words in it eventually converted to their "pig-sursurunga number type". If a `number` ( *ie* 1 or more digit ) + a `space` + a `word` ( letters ) are found then the word should be converted. **Each** group of `number+space+word` found in the string should be evaluated. ### Examples : You may assume at least 1 `number+space+word` group will be provided. **Beware** `s` of english plural should be removed, not ending `s` of some singular words ( *eg* "kiss" ) Good luck! I tried it in Python, but could not do it. Can you solve it?
import re from functools import partial def convert(match): n, s = match.groups() n = int(n) if n == 0 or n == 1: return match.group() elif n == 2: return "2 bu{}".format(s[:-1]) elif 3 <= n <= 9 : return "{} {}zo".format(n, s[:-1]) else: return "{} ga{}ga".format(n, s[:-1]) sursurungal = partial(re.compile(r"(\d+) (\w+)").sub, convert)
python
train
abovesol
codeparrot/apps
all
Solve in Python: You are given a forest — an undirected graph with $n$ vertices such that each its connected component is a tree. The diameter (aka "longest shortest path") of a connected undirected graph is the maximum number of edges in the shortest path between any pair of its vertices. You task is to add some edges (possibly zero) to the graph so that it becomes a tree and the diameter of the tree is minimal possible. If there are multiple correct answers, print any of them. -----Input----- The first line contains two integers $n$ and $m$ ($1 \le n \le 1000$, $0 \le m \le n - 1$) — the number of vertices of the graph and the number of edges, respectively. Each of the next $m$ lines contains two integers $v$ and $u$ ($1 \le v, u \le n$, $v \ne u$) — the descriptions of the edges. It is guaranteed that the given graph is a forest. -----Output----- In the first line print the diameter of the resulting tree. Each of the next $(n - 1) - m$ lines should contain two integers $v$ and $u$ ($1 \le v, u \le n$, $v \ne u$) — the descriptions of the added edges. The resulting graph should be a tree and its diameter should be minimal possible. For $m = n - 1$ no edges are added, thus the output consists of a single integer — diameter of the given tree. If there are multiple correct answers, print any of them. -----Examples----- Input 4 2 1 2 2 3 Output 2 4 2 Input 2 0 Output 1 1 2 Input 3 2 1 3 2 3 Output 2 -----Note----- In the first example adding edges (1, 4) or (3, 4) will lead to a total diameter of 3. Adding edge (2, 4), however, will make it 2. Edge (1, 2) is the only option you have for the second example. The diameter is 1. You can't add any edges in the third example. The diameter is already 2.
import math n,m=map(int,input().split()) neigh=[] for i in range(n): neigh.append([]) for i in range(m): a,b=map(int,input().split()) neigh[a-1].append(b-1) neigh[b-1].append(a-1) seen=set() index=[0]*n diams=[] trees=0 for i in range(n): if i not in seen: trees+=1 index[i]=trees seen.add(i) layer=[i] prev=None pars=[None] while layer!=[]: newlayer=[] newpars=[] for i in range(len(layer)): vert=layer[i] par=pars[i] for child in neigh[vert]: if child!=par: newlayer.append(child) newpars.append(vert) index[child]=trees seen.add(child) prev=layer layer=newlayer pars=newpars far=prev[0] layer=[[far]] pars=[None] prev=None while layer!=[]: newlayer=[] newpars=[] for i in range(len(layer)): vert=layer[i][-1] par=pars[i] for child in neigh[vert]: if child!=par: newlayer.append(layer[i]+[child]) newpars.append(vert) prev=layer layer=newlayer pars=newpars diam=prev[0] lent=len(diam) mid=diam[lent//2] diams.append((lent-1,mid)) diams.sort(reverse=True) poss=[diams[0][0]] if len(diams)>1: poss.append(math.ceil(diams[0][0]/2)+1+math.ceil(diams[1][0]/2)) if len(diams)>2: poss.append(math.ceil(diams[1][0]/2)+2+math.ceil(diams[2][0]/2)) print(max(poss)) cent=diams[0][1] for i in range(len(diams)-1): print(cent+1,diams[i+1][1]+1)
python
test
qsol
codeparrot/apps
all
Solve in Python: Polycarpus loves lucky numbers. Everybody knows that lucky numbers are positive integers, whose decimal representation (without leading zeroes) contain only the lucky digits x and y. For example, if x = 4, and y = 7, then numbers 47, 744, 4 are lucky. Let's call a positive integer a undoubtedly lucky, if there are such digits x and y (0 ≤ x, y ≤ 9), that the decimal representation of number a (without leading zeroes) contains only digits x and y. Polycarpus has integer n. He wants to know how many positive integers that do not exceed n, are undoubtedly lucky. Help him, count this number. -----Input----- The first line contains a single integer n (1 ≤ n ≤ 10^9) — Polycarpus's number. -----Output----- Print a single integer that says, how many positive integers that do not exceed n are undoubtedly lucky. -----Examples----- Input 10 Output 10 Input 123 Output 113 -----Note----- In the first test sample all numbers that do not exceed 10 are undoubtedly lucky. In the second sample numbers 102, 103, 104, 105, 106, 107, 108, 109, 120, 123 are not undoubtedly lucky.
def cnt(s, p): ans = 0 if p > s: ans = 0 elif len(p) == len(s): ans = 1 if len(set(p.lstrip('0'))) <= 2 else 0 elif len(set(p.lstrip('0'))) > 2: ans = 0 elif s[:len(p)] > p: if len(set(p.lstrip('0'))) == 2: ans = 2**(len(s)-len(p)) elif len(set(p.lstrip('0'))) == 1: ans = 1 + 9 * (2**(len(s)-len(p)) - 1) else: # ab for all a, b != 0 ans = 10 + 45 * (2**(len(s)-len(p)) - 2) ans += 36 * sum([2**l-2 for l in range(2,len(s)-len(p))]) else: ans = sum(cnt(s, p+c) for c in '0123456789') return ans print(cnt(input().strip(), '')-1) # Made By Mostafa_Khaled
python
test
qsol
codeparrot/apps
all
I found an interesting problem on https://codeforces.com/problemset/problem/1217/B: You are fighting with Zmei Gorynich — a ferocious monster from Slavic myths, a huge dragon-like reptile with multiple heads! $m$ Initially Zmei Gorynich has $x$ heads. You can deal $n$ types of blows. If you deal a blow of the $i$-th type, you decrease the number of Gorynich's heads by $min(d_i, curX)$, there $curX$ is the current number of heads. But if after this blow Zmei Gorynich has at least one head, he grows $h_i$ new heads. If $curX = 0$ then Gorynich is defeated. You can deal each blow any number of times, in any order. For example, if $curX = 10$, $d = 7$, $h = 10$ then the number of heads changes to $13$ (you cut $7$ heads off, but then Zmei grows $10$ new ones), but if $curX = 10$, $d = 11$, $h = 100$ then number of heads changes to $0$ and Zmei Gorynich is considered defeated. Calculate the minimum number of blows to defeat Zmei Gorynich! You have to answer $t$ independent queries. -----Input----- The first line contains one integer $t$ ($1 \le t \le 100$) – the number of queries. The first line of each query contains two integers $n$ and $x$ ($1 \le n \le 100$, $1 \le x \le 10^9$) — the number of possible types of blows and the number of heads Zmei initially has, respectively. The following $n$ lines of each query contain the descriptions of types of blows you can deal. The $i$-th line contains two integers $d_i$ and $h_i$ ($1 \le d_i, h_i \le 10^9$) — the description of the $i$-th blow. -----Output----- For each query print the minimum number of blows you have to deal to defeat Zmei Gorynich. If Zmei Gorynuch cannot be defeated print $-1$. -----Example----- Input 3 3 10 6 3 8 2 1 4 4 10 4 1 3 2 2 6 1 100 2 15 10 11 14 100 Output 2 3 -1 -----Note----- In the first query you can deal the first blow (after that the number of heads changes to $10 - 6 + 3 = 7$), and then deal the second blow. In the second query you just deal the first blow three times, and Zmei is defeated. In third query you can not defeat Zmei Gorynich. Maybe it's better to convince it to stop fighting? I tried it in Python, but could not do it. Can you solve it?
from bisect import bisect_left as bl from collections import defaultdict as dd for _ in range(int(input())): n, x = [int(i) for i in input().split()] l = [] f = dd(int) for j in range(n): d, h = [int(i) for i in input().split()] l.append(d - h) f[d] = 1 #print(n, x) l.sort(reverse = 1) #print(l) ans = 1 x -= max(f.keys()) if x <= 0: print(ans) else: if l[0] <= 0: ans = -1 else: ans = x // l[0] if (x % l[0]) == 0: ans += 1 else: ans += 2 print(ans)
python
test
abovesol
codeparrot/apps
all
Solve in Python: When a warrior wants to talk with another one about peace or war he uses a smartphone. In one distinct country warriors who spent all time in training kata not always have enough money. So if they call some number they want to know which operator serves this number. Write a function which **accepts number and return name of operator or string "no info"**, if operator can't be defined. number always looks like 8yyyxxxxxxx, where yyy corresponds to operator. Here is short list of operators: * 039 xxx xx xx - Golden Telecom * 050 xxx xx xx - MTS * 063 xxx xx xx - Life:) * 066 xxx xx xx - MTS * 067 xxx xx xx - Kyivstar * 068 xxx xx xx - Beeline * 093 xxx xx xx - Life:) * 095 xxx xx xx - MTS * 096 xxx xx xx - Kyivstar * 097 xxx xx xx - Kyivstar * 098 xxx xx xx - Kyivstar * 099 xxx xx xx - MTS Test [Just return "MTS"]
r = dict(__import__("re").findall(r"(\d{3}).*-\s(.+)", """ 039 xxx xx xx - Golden Telecom 050 xxx xx xx - MTS 063 xxx xx xx - Life:) 066 xxx xx xx - MTS 067 xxx xx xx - Kyivstar 068 xxx xx xx - Beeline 093 xxx xx xx - Life:) 095 xxx xx xx - MTS 096 xxx xx xx - Kyivstar 097 xxx xx xx - Kyivstar 098 xxx xx xx - Kyivstar 099 xxx xx xx - MTS """)) detect_operator = lambda s: r.get(s[1:4], "no info")
python
train
qsol
codeparrot/apps
all
Solve in Python: Dima and Inna are doing so great! At the moment, Inna is sitting on the magic lawn playing with a pink pony. Dima wanted to play too. He brought an n × m chessboard, a very tasty candy and two numbers a and b. Dima put the chessboard in front of Inna and placed the candy in position (i, j) on the board. The boy said he would give the candy if it reaches one of the corner cells of the board. He's got one more condition. There can only be actions of the following types: move the candy from position (x, y) on the board to position (x - a, y - b); move the candy from position (x, y) on the board to position (x + a, y - b); move the candy from position (x, y) on the board to position (x - a, y + b); move the candy from position (x, y) on the board to position (x + a, y + b). Naturally, Dima doesn't allow to move the candy beyond the chessboard borders. Inna and the pony started shifting the candy around the board. They wonder what is the minimum number of allowed actions that they need to perform to move the candy from the initial position (i, j) to one of the chessboard corners. Help them cope with the task! -----Input----- The first line of the input contains six integers n, m, i, j, a, b (1 ≤ n, m ≤ 10^6; 1 ≤ i ≤ n; 1 ≤ j ≤ m; 1 ≤ a, b ≤ 10^6). You can assume that the chessboard rows are numbered from 1 to n from top to bottom and the columns are numbered from 1 to m from left to right. Position (i, j) in the statement is a chessboard cell on the intersection of the i-th row and the j-th column. You can consider that the corners are: (1, m), (n, 1), (n, m), (1, 1). -----Output----- In a single line print a single integer — the minimum number of moves needed to get the candy. If Inna and the pony cannot get the candy playing by Dima's rules, print on a single line "Poor Inna and pony!" without the quotes. -----Examples----- Input 5 7 1 3 2 2 Output 2 Input 5 5 2 3 1 1 Output Poor Inna and pony! -----Note----- Note to sample 1: Inna and the pony can move the candy to position (1 + 2,...
#import math #n, m = input().split() #n = int (n) #m = int (m) #n, m, k= input().split() #n = int (n) #m = int (m) #k = int (k) #l = int(l) #m = int(input()) #s = input() ##t = input() #a = list(map(char, input().split())) #a.append('.') #print(l) #a = list(map(int, input().split())) #c = sorted(c) #x1, y1, x2, y2 =map(int,input().split()) #n = int(input()) #f = [] #t = [0]*n #f = [(int(s1[0]),s1[1]), (int(s2[0]),s2[1]), (int(s3[0]), s3[1])] #f1 = sorted(t, key = lambda tup: tup[0]) x1, y1, x3, y3, x2, y2 = input().split() x1 = int(x1) x2 = int(x2) x3 = int(x3) y1 = int(y1) y2 = int(y2) y3 = int(y3) mi = x1*y1 if((x3-1) % x2 == 0 and (y3-1) % y2 == 0 and ((x3-1) / x2) %2 == ((y3-1)/ y2)%2): mi = min(mi, max((x3-1)/x2,(y3-1)/y2)) if((x3-1) % x2 == 0 and (y1-y3) % y2 == 0 and ((x3-1) / x2) %2 == ((y1-y3)/ y2)%2): mi = min(mi, max((x3-1)/x2,(y1-y3)/y2)) if((x1-x3) % x2 == 0 and (y3-1) % y2 == 0 and ((x1-x3) / x2) % 2 == ((y3-1)/ y2)%2): mi = min(mi, max((x1-x3)/x2,(y3-1)/y2)) if((x1-x3) % x2 == 0 and (y1-y3) % y2 == 0 and ((x1-x3) / x2)%2 == ((y1-y3)/ y2)%2): mi = min(mi, max((x1-x3)/x2,(y1-y3)/y2)) if (mi == x1*y1 or ( (x2 >= x3 and x2 > x1-x3) and mi != 0)or ((y2 >= y3 and y2 > y1-y3) and mi != 0)): print("Poor Inna and pony!") else: print(int(mi))
python
test
qsol
codeparrot/apps
all
I found an interesting problem on https://codeforces.com/problemset/problem/1075/B: Palo Alto is an unusual city because it is an endless coordinate line. It is also known for the office of Lyft Level 5. Lyft has become so popular so that it is now used by all $m$ taxi drivers in the city, who every day transport the rest of the city residents — $n$ riders. Each resident (including taxi drivers) of Palo-Alto lives in its unique location (there is no such pair of residents that their coordinates are the same). The Lyft system is very clever: when a rider calls a taxi, his call does not go to all taxi drivers, but only to the one that is the closest to that person. If there are multiple ones with the same distance, then to taxi driver with a smaller coordinate is selected. But one morning the taxi drivers wondered: how many riders are there that would call the given taxi driver if they were the first to order a taxi on that day? In other words, you need to find for each taxi driver $i$ the number $a_{i}$ — the number of riders that would call the $i$-th taxi driver when all drivers and riders are at their home? The taxi driver can neither transport himself nor other taxi drivers. -----Input----- The first line contains two integers $n$ and $m$ ($1 \le n,m \le 10^5$) — number of riders and taxi drivers. The second line contains $n + m$ integers $x_1, x_2, \ldots, x_{n+m}$ ($1 \le x_1 < x_2 < \ldots < x_{n+m} \le 10^9$), where $x_i$ is the coordinate where the $i$-th resident lives. The third line contains $n + m$ integers $t_1, t_2, \ldots, t_{n+m}$ ($0 \le t_i \le 1$). If $t_i = 1$, then the $i$-th resident is a taxi driver, otherwise $t_i = 0$. It is guaranteed that the number of $i$ such that $t_i = 1$ is equal to $m$. -----Output----- Print $m$ integers $a_1, a_2, \ldots, a_{m}$, where $a_i$ is the answer for the $i$-th taxi driver. The taxi driver has the number $i$ if among all the taxi drivers he lives in the $i$-th smallest coordinate (see examples for better understanding). -----Examples----- Input 3 1 1 2 3 10 0 0 1 0 Output 3 Input 3 2 2 3 4 5 6 1 0 0 0 1 Output 2... I tried it in Python, but could not do it. Can you solve it?
n, m = map(int, input().split()) dist = list(map(int, input().split())) taxists = list(map(int, input().split())) left = [0] * (n + m) right = [0] * (n + m) MAX = 10000000000000000000 value = -MAX cnt = 0 for i in range(n + m): if taxists[i] == 1: cnt += 1 value = i left[i] = value value = MAX for i in range(n + m - 1, -1, -1): if taxists[i] == 1: value = i right[i] = value answer = [0] * (n + m) for i in range(n + m): if left[i] == -MAX: answer[right[i]] += 1 continue if right[i] == MAX: answer[left[i]] += 1 continue if abs(dist[left[i]] - dist[i]) <= abs(dist[i] - dist[right[i]]): answer[left[i]] += 1 else: answer[right[i]] += 1 for i in answer: if i: print(i - 1, end = " ")
python
test
abovesol
codeparrot/apps
all
Solve in Python: Takahashi is going to buy N items one by one. The price of the i-th item he buys is A_i yen (the currency of Japan). He has M discount tickets, and he can use any number of them when buying an item. If Y tickets are used when buying an item priced X yen, he can get the item for \frac{X}{2^Y} (rounded down to the nearest integer) yen. What is the minimum amount of money required to buy all the items? -----Constraints----- - All values in input are integers. - 1 \leq N, M \leq 10^5 - 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 minimum amount of money required to buy all the items. -----Sample Input----- 3 3 2 13 8 -----Sample Output----- 9 We can buy all the items for 9 yen, as follows: - Buy the 1-st item for 2 yen without tickets. - Buy the 2-nd item for 3 yen with 2 tickets. - Buy the 3-rd item for 4 yen with 1 ticket.
import heapq N, M = [int(_) for _ in input().split()] A = [int(_) * -1 for _ in input().split()] heapq.heapify(A) for i in range(M): a = heapq.heappop(A) * -1 heapq.heappush(A, (-1)*(a//2)) print(((-1) * sum(A)))
python
test
qsol
codeparrot/apps
all
Solve in Python: Piegirl found the red button. You have one last chance to change the inevitable end. The circuit under the button consists of n nodes, numbered from 0 to n - 1. In order to deactivate the button, the n nodes must be disarmed in a particular order. Node 0 must be disarmed first. After disarming node i, the next node to be disarmed must be either node (2·i) modulo n or node (2·i) + 1 modulo n. The last node to be disarmed must be node 0. Node 0 must be disarmed twice, but all other nodes must be disarmed exactly once. Your task is to find any such order and print it. If there is no such order, print -1. -----Input----- Input consists of a single integer n (2 ≤ n ≤ 10^5). -----Output----- Print an order in which you can to disarm all nodes. If it is impossible, print -1 instead. If there are multiple orders, print any one of them. -----Examples----- Input 2 Output 0 1 0 Input 3 Output -1 Input 4 Output 0 1 3 2 0 Input 16 Output 0 1 2 4 9 3 6 13 10 5 11 7 15 14 12 8 0
# METO Bot 0.9.9 n=int(input()) if n&1: print(-1) else: D,R=[False]*(10**6),[0]*(10**6) i,j=0,0 while True: D[j]=True R[i]=j i+=1 if not D[(j+n)>>1]: j=(j+n)>>1 elif not D[j>>1]: j=j>>1 else: break print(" ".join(str(R[i]) for i in range(n,-1,-1)))
python
test
qsol
codeparrot/apps
all
Solve in Python: The professional Russian, Dmitri, from the popular youtube channel FPSRussia has hired you to help him move his arms cache between locations without detection by the authorities. Your job is to write a Shortest Path First (SPF) algorithm that will provide a route with the shortest possible travel time between waypoints, which will minimize the chances of detection. One exception is that you can't travel through the same waypoint twice. Once you've been seen there is a higher chance of detection if you travel through that waypoint a second time. Your function shortestPath will take three inputs, a topology/map of the environment, along with a starting point, and an ending point. The topology will be a dictionary with the keys being the different waypoints. The values of each entry will be another dictionary with the keys being the adjacent waypoints, and the values being the time it takes to travel to that waypoint. Take the following topology as an example: topology = {'a' : {'b': 10, 'c': 20}, 'b' : {'a': 10, 'c': 20}, 'c' : {'a': 10, 'b': 20} } In this example, waypoint 'a' has two adjacent waypoints, 'b' and 'c'. And the time it takes to travel from 'a' to 'b' is 10 minutes, and from 'a' to 'c' is 20 minutes. It's important to note that the time between these waypoints is one way travel time and can be different in opposite directions. This is highlighted in the example above where a->c takes 20 minutes, but c->a takes 10 minutes. The starting and ending points will passed to your function as single character strings such as 'a' or 'b', which will match a key in your topology. The return value should be in the form of a list of lists of waypoints that make up the shortest travel time. If there multiple paths that have equal travel time, then you should choose the path with the least number of waypoints. If there are still multiple paths with equal travel time and number of waypoints, then you should return a list of lists with the multiple options. For...
def shortestPath(topology, startPoint, endPoint): graph = {} for key, value in topology.items(): values=[] for k, v in value.items(): values.append(k) graph[key]=values paths=find_all_paths(graph, startPoint, endPoint) if len(paths)==0: return [] pathsAndDistances=[] for path in paths: distance=0 for i,waypoint in enumerate(path): if i < len(path)-1: distance += topology[waypoint][path[i+1]] pathsAndDistances.append((distance,path)) pathsAndDistances=[t for t in pathsAndDistances if t[0]==min(pathsAndDistances)[0]] length=1000 for p in pathsAndDistances: if len(p[1])<length: length=len(p[1]) answer=[] for p in pathsAndDistances: if len(p[1])==length: answer.append(p[1]) return answer def find_all_paths(graph, start, end, path=[]): path = path + [start] if start == end: return [path] if start not in graph: return [] paths = [] for node in graph[start]: if node not in path: newpaths = find_all_paths(graph, node, end, path) for newpath in newpaths: paths.append(newpath) return paths
python
train
qsol
codeparrot/apps
all
I found an interesting problem on https://codeforces.com/problemset/problem/868/A: As technologies develop, manufacturers are making the process of unlocking a phone as user-friendly as possible. To unlock its new phone, Arkady's pet dog Mu-mu has to bark the password once. The phone represents a password as a string of two lowercase English letters. Mu-mu's enemy Kashtanka wants to unlock Mu-mu's phone to steal some sensible information, but it can only bark n distinct words, each of which can be represented as a string of two lowercase English letters. Kashtanka wants to bark several words (not necessarily distinct) one after another to pronounce a string containing the password as a substring. Tell if it's possible to unlock the phone in this way, or not. -----Input----- The first line contains two lowercase English letters — the password on the phone. The second line contains single integer n (1 ≤ n ≤ 100) — the number of words Kashtanka knows. The next n lines contain two lowercase English letters each, representing the words Kashtanka knows. The words are guaranteed to be distinct. -----Output----- Print "YES" if Kashtanka can bark several words in a line forming a string containing the password, and "NO" otherwise. You can print each letter in arbitrary case (upper or lower). -----Examples----- Input ya 4 ah oy to ha Output YES Input hp 2 ht tp Output NO Input ah 1 ha Output YES -----Note----- In the first example the password is "ya", and Kashtanka can bark "oy" and then "ah", and then "ha" to form the string "oyahha" which contains the password. So, the answer is "YES". In the second example Kashtanka can't produce a string containing password as a substring. Note that it can bark "ht" and then "tp" producing "http", but it doesn't contain the password "hp" as a substring. In the third example the string "hahahaha" contains "ah" as a substring. I tried it in Python, but could not do it. Can you solve it?
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,copy,functools sys.setrecursionlimit(10**7) inf = 10**20 eps = 1.0 / 10**15 mod = 10**9+7 def LI(): return [int(x) for x in sys.stdin.readline().split()] def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()] def LF(): return [float(x) for x in sys.stdin.readline().split()] def LS(): return sys.stdin.readline().split() def I(): return int(sys.stdin.readline()) def F(): return float(sys.stdin.readline()) def S(): return input() def main(): s = S() n = I() a = [S() for _ in range(n)] if (s in a) or (s[0] in [x[1] for x in a] and s[1] in [x[0] for x in a]): return 'YES' return 'NO' print(main())
python
train
abovesol
codeparrot/apps
all
I found an interesting problem on https://www.codewars.com/kata/5a15a4db06d5b6d33c000018: Implement a function to calculate the sum of the numerical values in a nested list. For example : ```python sum_nested([1, [2, [3, [4]]]]) -> 10 ``` I tried it in Python, but could not do it. Can you solve it?
def sum_nested(L): if L == []: return 0 if type(L[0]) == int: if len(L) == 1: return L[0] else: return L[0]+sum_nested(L[1:]) else: return sum_nested(L[0])+sum_nested(L[1:]) #the sum of every numerical value in the list and its sublists
python
train
abovesol
codeparrot/apps
all
I found an interesting problem on https://www.codewars.com/kata/56f6380a690784f96e00045d: Alice, Samantha, and Patricia are relaxing on the porch, when Alice suddenly says: _"I'm thinking of two numbers, both greater than or equal to 2. I shall tell Samantha the sum of the two numbers and Patricia the product of the two numbers."_ She takes Samantha aside and whispers in her ear the sum so that Patricia cannot hear it. Then she takes Patricia aside and whispers in her ear the product so that Samantha cannot hear it. After a moment of reflection, Samantha says: **Statement 1:** _"Patricia cannot know what the two numbers are."_ After which Patricia says: **Statement 2:** _"In that case, I do know what the two numbers are."_ To which Samantha replies: **Statement 3:** _"Then I too know what the two numbers are."_ Your first task is to write a function `statement1(s)` that takes an `int` argument `s` and returns `True` if and only if Samantha could have made statement 1 if given the number `s`. You may assume that `s` is the sum of two numbers both greater than or equal to 2. Your second task is to write a function `statement2(p)` that takes an `int` argument `p` and returns `True` if and only if Patricia, when given the number `p`, could have made statement 2 after hearing Samantha make statement 1. You may assume that `p` is the product of two numbers both greater than or equal to 2 and that Patricia would not have been able to determine the two numbers by looking at `p` alone. Your third task is to write a function `statement3(s)` that takes an `int` argument `s` and returns `True` if and only if Samantha, when given the number `s`, could have made statement 3 after hearing Patricia make statement 2. Finally, it is to you to figure out what two numbers Alice was thinking of. Since there are multiple solutions, you must write a function `is_solution(a, b)` that returns `True` if and only if `a` and `b` could have been two numbers that Alice was thinking of. Hint: To get you started, think of what Samantha's first statement implies. Samantha knows that Patricia was not given the... I tried it in Python, but could not do it. Can you solve it?
primes=[2,3,5,7,11,13,17,19,23,29,31] for i in range(37,500,2): if all(i%j for j in primes): primes.append(i) def statement1(s): return s%2 and s-2 not in primes def statement2(p): possible_pairs=set() for i in range(2,int(p**.5)+2): if p%i==0: possible_pairs.add((i,p//i)) good_pairs=[statement1(i+j) for i,j in possible_pairs] return sum(good_pairs)==1 def statement3(s): possible_pairs=set() for i in range(2,s//2+2): possible_pairs.add((i,s-i)) good_pairs=[statement2(i*j) for i,j in possible_pairs] return sum(good_pairs)==1 def is_solution(a, b): return statement1(a+b) and statement2(a*b) and statement3(a+b)
python
train
abovesol
codeparrot/apps
all
Solve in Python: Beroffice text editor has a wide range of features that help working with text. One of the features is an automatic search for typos and suggestions of how to fix them. Beroffice works only with small English letters (i.e. with 26 letters from a to z). Beroffice thinks that a word is typed with a typo if there are three or more consonants in a row in the word. The only exception is that if the block of consonants has all letters the same, then this block (even if its length is greater than three) is not considered a typo. Formally, a word is typed with a typo if there is a block of not less that three consonants in a row, and there are at least two different letters in this block. For example: the following words have typos: "hellno", "hackcerrs" and "backtothefutttture"; the following words don't have typos: "helllllooooo", "tobeornottobe" and "oooooo". When Beroffice editor finds a word with a typo, it inserts as little as possible number of spaces in this word (dividing it into several words) in such a way that each of the resulting words is typed without any typos. Implement this feature of Beroffice editor. Consider the following letters as the only vowels: 'a', 'e', 'i', 'o' and 'u'. All the other letters are consonants in this problem. -----Input----- The only line contains a non-empty word consisting of small English letters. The length of the word is between 1 and 3000 letters. -----Output----- Print the given word without any changes if there are no typos. If there is at least one typo in the word, insert the minimum number of spaces into the word so that each of the resulting words doesn't have any typos. If there are multiple solutions, print any of them. -----Examples----- Input hellno Output hell no Input abacaba Output abacaba Input asdfasdf Output asd fasd f
s = input() j = 0 a = ['a', 'e', 'i', 'o', 'u'] for i in range(len(s)): if (j > 1): if not(s[i] in a): if (not(s[i-1] in a) and not(s[i-2] in a) and not(s[i] == s[i-1] == s[i-2])): print(" ", end = '') j = 0 j += 1 print(s[i], end = '')
python
test
qsol
codeparrot/apps
all
Solve in Python: Print an ordered cross table of a round robin tournament that looks like this: ``` # Player 1 2 3 4 5 6 7 8 9 10 11 12 13 14 Pts SB ========================================================================== 1 Nash King 1 0 = 1 0 = 1 1 0 1 1 1 0 8.0 52.25 2 Karsyn Marks 0 1 1 = 1 = = 1 0 0 1 1 0 7.5 49.75 3 Yandel Briggs 1 0 = 0 = 1 1 1 = 0 1 0 1 7.5 47.25 Luka Harrell = 0 = 1 1 1 = 0 0 1 1 0 1 7.5 47.25 Pierre Medina 0 = 1 0 = 1 = 1 1 = 0 1 = 7.5 47.25 6 Carlos Koch 1 0 = 0 = = = 1 1 = 0 = 1 7.0 43.50 7 Tristan Pitts = = 0 0 0 = 1 0 1 = 1 1 1 7.0 40.75 Luke Schaefer 0 = 0 = = = 0 1 = = 1 1 1 7.0 40.75 9 Tanner Dunn 0 0 0 1 0 0 1 0 1 1 = 1 1 6.5 37.25 10 Haylee Bryan 1 1 = 1 0 0 0 = 0 1 0 0 1 6.0 39.25 11 Dylan Turner 0 1 1 0 = = = = 0 0 1 = = 6.0 38.75 12 Adyson Griffith 0 0 0 0 1 1 0 0 = 1 0 1 1 5.5 31.75 13 Dwayne Shaw 0 0 1 1 0 = 0 0 0 1 = 0 1 5.0 30.50 14 Kadin Rice 1 1 0 0 = 0 0 0 0 0 = 0 0 3.0 22.25 ``` The `#` column contains the rank. Ranks may be tied. A colum with index numbers `i` contains the match against the player on line `i`. `1` / `=` / `0` means win / draw / loss. The `Pts` column contains the score, 1 for each win, 0.5 for each draw. The `SB` column contains the Sonneborn-Berger score (see below). The rank is determined by the score, the Sonneborn-Berger score is used to break ties. Players with the same score and the same SB score share the same rank. In the cross table those tied players are ordered by their surenames. # Sonneborn-Berger score The Sonneborn-Berger score (`SB`) (sometimes also called Neustadtl Sonneborn–Berger or Neustadtl score) is a system to break ties in tournaments. This score is based on the...
def crosstable(players, scores): points, le = {j:sum(k or 0 for k in scores[i]) for i, j in enumerate(players)}, len(players) SB = {j:sum(points[players[k]] / ([1, 2][l == 0.5]) for k, l in enumerate(scores[i]) if l) for i, j in enumerate(players)} SORTED, li = [[i, players.index(i)] for i in sorted(players, key=lambda x: (-points[x], -SB[x], x.split()[1]))], [] ps = [format(i, '.1f') for i in points.values()] Ss = [format(i, '.2f') for i in SB.values()] digit = len(str(le)) name = len(max(players, key=len)) pts = len(str(max(ps, key=lambda x: len(str(x))))) sb = len(str(max(Ss, key=lambda x: len(str(x))))) for i, j in enumerate(SORTED): ten_ = [" ", " "][le >= 10] index = [str(i + 1), " "][points[j[0]] == points[SORTED[i - 1][0]] and SB[j[0]] == SB[SORTED[i - 1][0]]].rjust(digit) name_ = j[0].ljust(name) team = ten_.join(['1=0 '[[1, 0.5, 0, None].index(scores[j[1]][l])] or '_' for k, l in SORTED]) pt = str(format(points[j[0]], ".1f")).rjust(pts) Sb = str(format(SB[j[0]], ".2f")).rjust(sb) li.append(f'{index} {name_}{[" ", " "][le >= 10]}{team} {pt} {Sb}') fline = ' '.join(['#'.rjust(digit) + ' ' + 'Player'.ljust(name) + [' ', ' '][len(players) >= 10] + ''.join([[' ', ' '][i < 10 and le >= 10] + str(i) for i in range(1, le + 1)]).strip() + ' ' + 'Pts'.center(pts) + ' ' + 'SB'.center(sb - [0, 2][sb & 1])]).rstrip() return '\n'.join([fline, '=' * len(max(li, key=len))] + li)
python
train
qsol
codeparrot/apps
all
I found an interesting problem on https://www.codewars.com/kata/5a00a8b5ffe75f8888000080: Given an array containing only zeros and ones, find the index of the zero that, if converted to one, will make the longest sequence of ones. For instance, given the array: ``` [1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, 0, 1, 1] ``` replacing the zero at index 10 (counting from 0) forms a sequence of 9 ones: ``` [1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1] '------------^------------' ``` Your task is to complete the function that determines where to replace a zero with a one to make the maximum length subsequence. **Notes:** - If there are multiple results, return the last one: `[1, 1, 0, 1, 1, 0, 1, 1] ==> 5` - The array will always contain only zeros and ones. Can you do this in one pass? I tried it in Python, but could not do it. Can you solve it?
def replace_zero(arr): labels=[] max=1 ans=-1 # find all the indices that correspond to zero values for i in range(len(arr)): if arr[i]==0: labels.append(i) # try each index and compute the associated length for j in range(len(labels)): arr[labels[j]]=1 count=1 end=0 # check how long the sequence in on the left side. k=labels[j] while end==0 and k!=0: if arr[k-1]: count=count+1 k=k-1 else: end=1 end=0 k=labels[j] # check how long the sequence in on the right side. while end==0 and k!=len(arr)-1: if arr[k+1]: count=count+1 k=k+1 else: end=1 # restore the selected element to zero and check if the new value is a max. arr[labels[j]]=0 if(count>=max): ans=labels[j] max=count return(ans)
python
train
abovesol
codeparrot/apps
all
I found an interesting problem on https://codeforces.com/problemset/problem/868/C: Snark and Philip are preparing the problemset for the upcoming pre-qualification round for semi-quarter-finals. They have a bank of n problems, and they want to select any non-empty subset of it as a problemset. k experienced teams are participating in the contest. Some of these teams already know some of the problems. To make the contest interesting for them, each of the teams should know at most half of the selected problems. Determine if Snark and Philip can make an interesting problemset! -----Input----- The first line contains two integers n, k (1 ≤ n ≤ 10^5, 1 ≤ k ≤ 4) — the number of problems and the number of experienced teams. Each of the next n lines contains k integers, each equal to 0 or 1. The j-th number in the i-th line is 1 if j-th team knows i-th problem and 0 otherwise. -----Output----- Print "YES" (quotes for clarity), if it is possible to make an interesting problemset, and "NO" otherwise. You can print each character either upper- or lowercase ("YeS" and "yes" are valid when the answer is "YES"). -----Examples----- Input 5 3 1 0 1 1 1 0 1 0 0 1 0 0 1 0 0 Output NO Input 3 2 1 0 1 1 0 1 Output YES -----Note----- In the first example you can't make any interesting problemset, because the first team knows all problems. In the second example you can choose the first and the third problems. I tried it in Python, but could not do it. Can you solve it?
def test(masks, wanted): for w in wanted: if w not in masks: return False return True def any_test(masks, tests): for t in tests: if test(masks, t): return True return False def inflate(perm): count = max(perm) masks = [[0 for i in range(len(perm))] for j in range(count)] for i in range(len(perm)): if perm[i] == 0: continue masks[perm[i] - 1][i] = 1 return [tuple(m) for m in masks] def gen(st, lev, teams, tests): if lev >= teams: if max(st) > 1: tests.append(inflate(st)) return for i in range(teams + 1): st[lev] = i gen(st, lev + 1, teams, tests) def gen_tests(teams): tests = [] st = [0 for i in range(teams)] gen(st, 0, teams, tests) return tests def back(masks, teams): tests = gen_tests(teams) return any_test(masks, tests) def main(): probs, teams = list(map(int, input().split())) masks = set() for i in range(probs): conf = tuple(list(map(int, input().split()))) if 1 not in conf: print('YES') return masks.add(conf) if teams == 1: print('NO') return if teams == 2: good = test(masks, [(0, 1), (1, 0)]) else: good = back(masks, teams) print('YES' if good else 'NO') main()
python
test
abovesol
codeparrot/apps
all
Solve in Python: We have N logs of lengths A_1,A_2,\cdots A_N. We can cut these logs at most K times in total. When a log of length L is cut at a point whose distance from an end of the log is t (0<t<L), it becomes two logs of lengths t and L-t. Find the shortest possible length of the longest log after at most K cuts, and print it after rounding up to an integer. -----Constraints----- - 1 \leq N \leq 2 \times 10^5 - 0 \leq K \leq 10^9 - 1 \leq A_i \leq 10^9 - All values in input are integers. -----Input----- Input is given from Standard Input in the following format: N K A_1 A_2 \cdots A_N -----Output----- Print an integer representing the answer. -----Sample Input----- 2 3 7 9 -----Sample Output----- 4 - First, we will cut the log of length 7 at a point whose distance from an end of the log is 3.5, resulting in two logs of length 3.5 each. - Next, we will cut the log of length 9 at a point whose distance from an end of the log is 3, resulting in two logs of length 3 and 6. - Lastly, we will cut the log of length 6 at a point whose distance from an end of the log is 3.3, resulting in two logs of length 3.3 and 2.7. In this case, the longest length of a log will be 3.5, which is the shortest possible result. After rounding up to an integer, the output should be 4.
from collections import defaultdict from collections import deque from collections import Counter import math def readInt(): return int(input()) def readInts(): return list(map(int, input().split())) def readChar(): return input() def readChars(): return input().split() n,k = readInts() a = readInts() a.sort(reverse=True) if n==1: print((math.ceil(a[0]/(k+1)))) return def get(left, right): l = (right-left)//2+left ans = 0 for i in a: ans+=math.ceil(i/l)-1 #print(l, ans, left, right) return ans,l def nibu(left,right): ans,l = get(left, right) if left<right: if ans<=k: return nibu(left,l) else: return nibu(l+1, right) else: return right print((nibu(1,a[0])))
python
test
qsol
codeparrot/apps
all
I found an interesting problem on https://www.codewars.com/kata/5b715fd11db5ce5912000019: Ronny the robot is watching someone perform the Cups and Balls magic trick. The magician has one ball and three cups, he shows Ronny which cup he hides the ball under (b), he then mixes all the cups around by performing multiple two-cup switches (arr). Ronny can record the switches but can't work out where the ball is. Write a programme to help him do this. Rules: - There will only ever be three cups. - Only two cups will be swapped at a time. - The cups and their switches will be refered to by their index in a row of three, beginning at one. So [[1,2]] means the cup at position one, is swapped with the cup at position two. - Arr will be an array of integers 1 - 3 organised in pairs. - There won't be any empty sub-arrays. - If arr is just an empty array b should be returned. Examples: (b) = 2, (arr) = [[1,2]] The ball is under cup number : 1 ------- (b) = 1, (arr) = [[2,3],[1,2],[1,2]] The ball is under cup number : 1 ------- (b) = 2, (arr) = [[1,3],[1,2],[2,1],[2,3]] The ball is under cup number : 3 I tried it in Python, but could not do it. Can you solve it?
def cup_and_balls(b, arr): for switch in arr: if b in switch: b = sum(switch) - b return b
python
train
abovesol
codeparrot/apps
all
Solve in Python: Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. (i.e., [0,0,1,2,2,5,6] might become [2,5,6,0,0,1,2]). You are given a target value to search. If found in the array return true, otherwise return false. Example 1: Input: nums = [2,5,6,0,0,1,2], target = 0 Output: true Example 2: Input: nums = [2,5,6,0,0,1,2], target = 3 Output: false Follow up: This is a follow up problem to Search in Rotated Sorted Array, where nums may contain duplicates. Would this affect the run-time complexity? How and why?
class Solution: def search(self, nums, target): """ :type nums: List[int] :type target: int :rtype: bool """ low = 0 high = len(nums)-1 while low<=high: mid = (low+high)//2 if nums[mid]==target: return True if nums[low]<nums[mid]: if nums[low]<=target and nums[mid]>target: high = mid-1 else: low= mid+1 elif nums[low]>nums[mid]: if nums[mid]<target and nums[high]>=target: low= mid+1 else: high = mid -1 else: low+=1 return False
python
train
qsol
codeparrot/apps
all
I found an interesting problem on https://codeforces.com/problemset/problem/734/A: Anton likes to play chess, and so does his friend Danik. Once they have played n games in a row. For each game it's known who was the winner — Anton or Danik. None of the games ended with a tie. Now Anton wonders, who won more games, he or Danik? Help him determine this. -----Input----- The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the number of games played. The second line contains a string s, consisting of n uppercase English letters 'A' and 'D' — the outcome of each of the games. The i-th character of the string is equal to 'A' if the Anton won the i-th game and 'D' if Danik won the i-th game. -----Output----- If Anton won more games than Danik, print "Anton" (without quotes) in the only line of the output. If Danik won more games than Anton, print "Danik" (without quotes) in the only line of the output. If Anton and Danik won the same number of games, print "Friendship" (without quotes). -----Examples----- Input 6 ADAAAA Output Anton Input 7 DDDAADA Output Danik Input 6 DADADA Output Friendship -----Note----- In the first sample, Anton won 6 games, while Danik — only 1. Hence, the answer is "Anton". In the second sample, Anton won 3 games and Danik won 4 games, so the answer is "Danik". In the third sample, both Anton and Danik won 3 games and the answer is "Friendship". I tried it in Python, but could not do it. Can you solve it?
input() s = input() if s.count('D') == s.count('A'): print('Friendship') # is magic else: print(['Anton', 'Danik'][s.count('D') > s.count('A')])
python
test
abovesol
codeparrot/apps
all
Solve in Python: You are given a rectangular field of n × m cells. Each cell is either empty or impassable (contains an obstacle). Empty cells are marked with '.', impassable cells are marked with '*'. Let's call two empty cells adjacent if they share a side. Let's call a connected component any non-extendible set of cells such that any two of them are connected by the path of adjacent cells. It is a typical well-known definition of a connected component. For each impassable cell (x, y) imagine that it is an empty cell (all other cells remain unchanged) and find the size (the number of cells) of the connected component which contains (x, y). You should do it for each impassable cell independently. The answer should be printed as a matrix with n rows and m columns. The j-th symbol of the i-th row should be "." if the cell is empty at the start. Otherwise the j-th symbol of the i-th row should contain the only digit —- the answer modulo 10. The matrix should be printed without any spaces. To make your output faster it is recommended to build the output as an array of n strings having length m and print it as a sequence of lines. It will be much faster than writing character-by-character. As input/output can reach huge size it is recommended to use fast input/output methods: for example, prefer to use scanf/printf instead of cin/cout in C++, prefer to use BufferedReader/PrintWriter instead of Scanner/System.out in Java. -----Input----- The first line contains two integers n, m (1 ≤ n, m ≤ 1000) — the number of rows and columns in the field. Each of the next n lines contains m symbols: "." for empty cells, "*" for impassable cells. -----Output----- Print the answer as a matrix as described above. See the examples to precise the format of the output. -----Examples----- Input 3 3 *.* .*. *.* Output 3.3 .5. 3.3 Input 4 5 **..* ..*** .*.*. *.*.* Output 46..3 ..732 .6.4. 5.4.3 -----Note----- In first example, if we imagine that the central cell is empty then it will be included to component of size 5 (cross). If...
from sys import stdin,stdout st=lambda:list(stdin.readline().strip()) li=lambda:list(map(int,stdin.readline().split())) mp=lambda:list(map(int,stdin.readline().split())) inp=lambda:int(stdin.readline()) pr=lambda n: stdout.write(str(n)+"\n") def valid(x,y): if x>=n or y>=m or x<0 or y<0: return False if v[x][y] or l[x][y]=='*': return False return True dx=[-1,1,0,0] dy=[0,0,1,-1] def DFS(i,j,val): ans=1 connected=[(i,j)] stack=[(i,j)] v[i][j]=True while stack: a,b=stack.pop() for x in range(4): newX,newY=a+dx[x], b+dy[x] if valid(newX,newY): stack.append((newX,newY)) v[newX][newY]=True connected.append((newX,newY)) ans= ans+1 for i in connected: a,b=i l[a][b]=(ans,val) n,m=mp() l=[st() for i in range(n)] val=0 k=[list(i) for i in l] v=[[False for i in range(m)] for j in range(n)] for i in range(n): for j in range(m): if l[i][j]=='.' and not v[i][j]: DFS(i,j,val) val+=1 for i in range(n): for j in range(m): if l[i][j]=='*': k[i][j]=1 s=set() for x in range(4): newX,newY= i+dx[x], j+dy[x] if newX>=0 and newY>=0 and newX<n and newY<m: if type(l[newX][newY])==tuple: A,B=l[newX][newY] if B not in s: k[i][j]+=A k[i][j]%=10 s.add(B) print('\n'.join([''.join([str(i) for i in j]) for j in k]))
python
test
qsol
codeparrot/apps
all
Solve in Python: Implement pow(x, n), which calculates x raised to the power n (xn). Example 1: Input: 2.00000, 10 Output: 1024.00000 Example 2: Input: 2.10000, 3 Output: 9.26100 Example 3: Input: 2.00000, -2 Output: 0.25000 Explanation: 2-2 = 1/22 = 1/4 = 0.25 Note: -100.0 < x < 100.0 n is a 32-bit signed integer, within the range [−231, 231 − 1]
class Solution: def myPow(self, x, n): """ :type x: float :type n: int :rtype: float """ if n == 0 : return 1.00000 if n < 0 : return 1 / self.myPow(x , -n) if n % 2 != 0 : return x * self.myPow(x , n - 1) return self.myPow(x * x , n / 2)
python
train
qsol
codeparrot/apps
all
I found an interesting problem on https://codeforces.com/problemset/problem/1322/D: A popular reality show is recruiting a new cast for the third season! $n$ candidates numbered from $1$ to $n$ have been interviewed. The candidate $i$ has aggressiveness level $l_i$, and recruiting this candidate will cost the show $s_i$ roubles. The show host reviewes applications of all candidates from $i=1$ to $i=n$ by increasing of their indices, and for each of them she decides whether to recruit this candidate or not. If aggressiveness level of the candidate $i$ is strictly higher than that of any already accepted candidates, then the candidate $i$ will definitely be rejected. Otherwise the host may accept or reject this candidate at her own discretion. The host wants to choose the cast so that to maximize the total profit. The show makes revenue as follows. For each aggressiveness level $v$ a corresponding profitability value $c_v$ is specified, which can be positive as well as negative. All recruited participants enter the stage one by one by increasing of their indices. When the participant $i$ enters the stage, events proceed as follows: The show makes $c_{l_i}$ roubles, where $l_i$ is initial aggressiveness level of the participant $i$. If there are two participants with the same aggressiveness level on stage, they immediately start a fight. The outcome of this is: the defeated participant is hospitalized and leaves the show. aggressiveness level of the victorious participant is increased by one, and the show makes $c_t$ roubles, where $t$ is the new aggressiveness level. The fights continue until all participants on stage have distinct aggressiveness levels. It is allowed to select an empty set of participants (to choose neither of the candidates). The host wants to recruit the cast so that the total profit is maximized. The profit is calculated as the total revenue from the events on stage, less the total expenses to recruit all accepted participants (that is, their total $s_i$). Help the host to make the show as profitable as possible. -----Input----- The first line contains... I tried it in Python, but could not do it. Can you solve it?
import sys input = sys.stdin.readline n,m=list(map(int,input().split())) A=list(map(int,input().split())) C=list(map(int,input().split())) P=list(map(int,input().split())) DP=[[-1<<30]*(n+1) for i in range(5001)] # DP[k][cnt] = Aのmaxがkで, そういう人間がcnt人いるときのprofitの最大値 for i in range(5001): DP[i][0]=0 for i in range(n-1,-1,-1): a,c = A[i]-1,C[i] for j in range(n,-1,-1): if DP[a][j]==-1<<30: continue if DP[a][j] - c + P[a] > DP[a][j+1]: DP[a][j+1] = DP[a][j] - c + P[a] x, w=a, j+1 while x+1<n+m: if DP[x+1][w//2] < DP[x][w] + w//2 * P[x+1]: DP[x+1][w//2] = DP[x][w] + w//2 * P[x+1] x,w=x+1,w//2 else: break ANS=0 for i in range(5001): ANS=max(ANS,DP[i][0],DP[i][1]) print(ANS)
python
test
abovesol
codeparrot/apps
all
I found an interesting problem on https://www.codewars.com/kata/592915cc1fad49252f000006: Write a function that accepts two parameters (a and b) and says whether a is smaller than, bigger than, or equal to b. Here is an example code: var noIfsNoButs = function (a,b) { if(a > b) return a + " is greater than " + b else if(a < b) return a + " is smaller than " + b else if(a == b) return a + " is equal to " + b } There's only one problem... You can't use if statements, and you can't use shorthands like (a < b)?true:false; in fact the word "if" and the character "?" are not allowed in the code. Inputs are guarenteed to be numbers You are always welcome to check out some of my other katas: Very Easy (Kyu 8) Add Numbers Easy (Kyu 7-6) Convert Color image to greyscale Array Transformations Basic Compression Find Primes in Range No Ifs No Buts Medium (Kyu 5-4) Identify Frames In An Image Photoshop Like - Magic Wand Scientific Notation Vending Machine - FSA Find Matching Parenthesis Hard (Kyu 3-2) Ascii Art Generator I tried it in Python, but could not do it. Can you solve it?
def no_ifs_no_buts(a, b): return ([ '%d is smaller than %d', '%d is equal to %d', '%d is greater than %d' ][int(a >= b) + int(a > b)] % (a, b))
python
train
abovesol
codeparrot/apps
all
I found an interesting problem on https://codeforces.com/problemset/problem/1249/F: You are given a tree, which consists of $n$ vertices. Recall that a tree is a connected undirected graph without cycles. [Image] Example of a tree. Vertices are numbered from $1$ to $n$. All vertices have weights, the weight of the vertex $v$ is $a_v$. Recall that the distance between two vertices in the tree is the number of edges on a simple path between them. Your task is to find the subset of vertices with the maximum total weight (the weight of the subset is the sum of weights of all vertices in it) such that there is no pair of vertices with the distance $k$ or less between them in this subset. -----Input----- The first line of the input contains two integers $n$ and $k$ ($1 \le n, k \le 200$) — the number of vertices in the tree and the distance restriction, respectively. The second line of the input contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 10^5$), where $a_i$ is the weight of the vertex $i$. The next $n - 1$ lines contain edges of the tree. Edge $i$ is denoted by two integers $u_i$ and $v_i$ — the labels of vertices it connects ($1 \le u_i, v_i \le n$, $u_i \ne v_i$). It is guaranteed that the given edges form a tree. -----Output----- Print one integer — the maximum total weight of the subset in which all pairs of vertices have distance more than $k$. -----Examples----- Input 5 1 1 2 3 4 5 1 2 2 3 3 4 3 5 Output 11 Input 7 2 2 1 2 1 2 1 1 6 4 1 5 3 1 2 3 7 5 7 4 Output 4 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())) g = {} def dfs(v, p=-1): c = [dfs(child, v) for child in g.get(v, set()) - {p}] c.sort(key=len, reverse=True) r = [] i = 0 while c: if i >= len(c[-1]): c.pop() else: o = max(i, k - i - 1) s = q = 0 for x in c: if len(x) <= o: q = max(q, x[i]) else: s += x[o] q = max(q, x[i] - x[o]) r.append(q + s) i += 1 r.append(0) for i in range(len(r) - 1, 0, -1): r[i - 1] = max(r[i - 1], r[i]) while len(r) > 1 and r[-2] == 0: r.pop() o = (r[k] if k < len(r) else 0) + a[v] r.insert(0, max(o, r[0])) return r for _ in range(1, n): u, v = [int(x) - 1 for x in input().split()] g.setdefault(u, set()).add(v) g.setdefault(v, set()).add(u) print(dfs(0)[0])
python
test
abovesol
codeparrot/apps
all
I found an interesting problem on https://www.codewars.com/kata/574c5075d27783851800169e: #Description Everybody has probably heard of the animal heads and legs problem from the earlier years at school. It goes: ```“A farm contains chickens and cows. There are x heads and y legs. How many chickens and cows are there?” ``` Where x <= 1000 and y <=1000 #Task Assuming there are no other types of animals, work out how many of each animal are there. ```Return a tuple in Python - (chickens, cows) and an array list - [chickens, cows]/{chickens, cows} in all other languages``` If either the heads & legs is negative, the result of your calculation is negative or the calculation is a float return "No solutions" (no valid cases). In the form: ```python (Heads, Legs) = (72, 200) VALID - (72, 200) => (44 , 28) (Chickens, Cows) INVALID - (72, 201) => "No solutions" ``` However, ```if 0 heads and 0 legs are given always return [0, 0]``` since zero heads must give zero animals. There are many different ways to solve this, but they all give the same answer. You will only be given integers types - however negative values (edge cases) will be given. Happy coding! I tried it in Python, but could not do it. Can you solve it?
def animals(heads, legs): solution = (2 * heads - legs/2, legs/2 - heads) return solution if legs % 2 == 0 and solution[0] >= 0 and solution[1] >= 0 else "No solutions"
python
train
abovesol
codeparrot/apps
all
I found an interesting problem on https://codeforces.com/problemset/problem/1305/F: Kuroni is very angry at the other setters for using him as a theme! As a punishment, he forced them to solve the following problem: You have an array $a$ consisting of $n$ positive integers. An operation consists of choosing an element and either adding $1$ to it or subtracting $1$ from it, such that the element remains positive. We say the array is good if the greatest common divisor of all its elements is not $1$. Find the minimum number of operations needed to make the array good. Unable to match Kuroni's intellect, the setters failed to solve the problem. Help them escape from Kuroni's punishment! -----Input----- The first line contains an integer $n$ ($2 \le n \le 2 \cdot 10^5$)  — the number of elements in the array. The second line contains $n$ integers $a_1, a_2, \dots, a_n$. ($1 \le a_i \le 10^{12}$)  — the elements of the array. -----Output----- Print a single integer  — the minimum number of operations required to make the array good. -----Examples----- Input 3 6 2 4 Output 0 Input 5 9 8 7 3 1 Output 4 -----Note----- In the first example, the first array is already good, since the greatest common divisor of all the elements is $2$. In the second example, we may apply the following operations: Add $1$ to the second element, making it equal to $9$. Subtract $1$ from the third element, making it equal to $6$. Add $1$ to the fifth element, making it equal to $2$. Add $1$ to the fifth element again, making it equal to $3$. The greatest common divisor of all elements will then be equal to $3$, so the array will be good. It can be shown that no sequence of three or less operations can make the array good. I tried it in Python, but could not do it. Can you solve it?
import random n = int(input()) best = n l = list(map(int, input().split())) candidates = set() candidates.add(2) def gcd(x, y): while(y): x, y = y, x % y return x def factAdd(n): for c in candidates: while n % c == 0: n //= c test = 3 while test * test <= n: while n % test == 0: candidates.add(test) n //= test test += 2 if n > 1: candidates.add(n) for i in range(100): a = random.randint(0, n - 1) b = random.randint(0, n - 1) diff = [-1, 0, 1] for d1 in diff: a1 = l[a] + d1 if a1: for d2 in diff: a2 = l[b] + d2 if a2: factAdd(gcd(a1, a2)) for cand in candidates: count = 0 for v in l: if v <= cand: count += (cand - v) else: v2 = v % cand count += min(v2, cand - v2) if count < best: best = count print(best)
python
test
abovesol
codeparrot/apps
all
Solve in Python: There are b blocks of digits. Each one consisting of the same n digits, which are given to you in the input. Wet Shark must choose exactly one digit from each block and concatenate all of those digits together to form one large integer. For example, if he chooses digit 1 from the first block and digit 2 from the second block, he gets the integer 12. Wet Shark then takes this number modulo x. Please, tell him how many ways he can choose one digit from each block so that he gets exactly k as the final result. As this number may be too large, print it modulo 10^9 + 7. Note, that the number of ways to choose some digit in the block is equal to the number of it's occurrences. For example, there are 3 ways to choose digit 5 from block 3 5 6 7 8 9 5 1 1 1 1 5. -----Input----- The first line of the input contains four space-separated integers, n, b, k and x (2 ≤ n ≤ 50 000, 1 ≤ b ≤ 10^9, 0 ≤ k < x ≤ 100, x ≥ 2) — the number of digits in one block, the number of blocks, interesting remainder modulo x and modulo x itself. The next line contains n space separated integers a_{i} (1 ≤ a_{i} ≤ 9), that give the digits contained in each block. -----Output----- Print the number of ways to pick exactly one digit from each blocks, such that the resulting integer equals k modulo x. -----Examples----- Input 12 1 5 10 3 5 6 7 8 9 5 1 1 1 1 5 Output 3 Input 3 2 1 2 6 2 2 Output 0 Input 3 2 1 2 3 1 2 Output 6 -----Note----- In the second sample possible integers are 22, 26, 62 and 66. None of them gives the remainder 1 modulo 2. In the third sample integers 11, 13, 21, 23, 31 and 33 have remainder 1 modulo 2. There is exactly one way to obtain each of these integers, so the total answer is 6.
p = 10 ** 9 + 7 n, b, k, x = [int(s) for s in input().split()] block = [int(s) for s in input().split()] D = [0 for i in range(10)] for s in block: D[s] += 1 A = [[0 for t in range(x)]] pows = [pow(10, 1<<j, x) for j in range(b.bit_length())] for i in range(10): A[0][i%x] += D[i] for j in range(b.bit_length()-1): B = A[-1] C = [sum(B[i]*B[(t - i*pows[j])%x] for i in range(x)) % p for t in range(x)] A.append(C) ans = None for j in range(b.bit_length()): if (b>>j)&1: if ans is None: ans = A[j][:] else: ans = [sum(A[j][(t - i*pows[j])%x]*ans[i] for i in range(x)) % p for t in range(x)] print(ans[k])
python
test
qsol
codeparrot/apps
all
Solve in Python: Given a collection of distinct integers, return all possible permutations. Example: Input: [1,2,3] Output: [ [1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], [3,2,1] ]
class Solution: def permute(self, nums): """ :type nums: List[int] :rtype: List[List[int]] """ all_permutes = [] self.permute_nums(all_permutes, nums, []) return all_permutes def permute_nums(self, all_permutes, nums, cur_permute): if len(nums) == 0: all_permutes.append(cur_permute) return for i in range(len(nums)): num = nums[i] self.permute_nums(all_permutes, nums[0:i] + nums[i+1:len(nums)], cur_permute + [num])
python
test
qsol
codeparrot/apps
all
I found an interesting problem on https://codeforces.com/problemset/problem/746/C: The tram in Berland goes along a straight line from the point 0 to the point s and back, passing 1 meter per t_1 seconds in both directions. It means that the tram is always in the state of uniform rectilinear motion, instantly turning around at points x = 0 and x = s. Igor is at the point x_1. He should reach the point x_2. Igor passes 1 meter per t_2 seconds. Your task is to determine the minimum time Igor needs to get from the point x_1 to the point x_2, if it is known where the tram is and in what direction it goes at the moment Igor comes to the point x_1. Igor can enter the tram unlimited number of times at any moment when his and the tram's positions coincide. It is not obligatory that points in which Igor enter and exit the tram are integers. Assume that any boarding and unboarding happens instantly. Igor can move arbitrary along the line (but not faster than 1 meter per t_2 seconds). He can also stand at some point for some time. -----Input----- The first line contains three integers s, x_1 and x_2 (2 ≤ s ≤ 1000, 0 ≤ x_1, x_2 ≤ s, x_1 ≠ x_2) — the maximum coordinate of the point to which the tram goes, the point Igor is at, and the point he should come to. The second line contains two integers t_1 and t_2 (1 ≤ t_1, t_2 ≤ 1000) — the time in seconds in which the tram passes 1 meter and the time in seconds in which Igor passes 1 meter. The third line contains two integers p and d (1 ≤ p ≤ s - 1, d is either 1 or $- 1$) — the position of the tram in the moment Igor came to the point x_1 and the direction of the tram at this moment. If $d = - 1$, the tram goes in the direction from the point s to the point 0. If d = 1, the tram goes in the direction from the point 0 to the point s. -----Output----- Print the minimum time in seconds which Igor needs to get from the point x_1 to the point x_2. -----Examples----- Input 4 2 4 3 4 1 1 Output 8 Input 5 4 0 1 2 3 1 Output 7 -----Note----- In the first example it is profitable for Igor to go by foot and not to wait the tram. Thus, he has to... I tried it in Python, but could not do it. Can you solve it?
s, x1, x2 = list(map(int, input().split())) t1, t2 = list(map(int, input().split())) p, d = list(map(int, input().split())) if x2 < x1: x1, x2 = s - x1, s - x2 d *= -1 p = s - p if t2 <= t1: print(t2 * abs(x1 - x2)) return if p <= x1 and d == 1: print(min(t2 * abs(x1 - x2), t1* abs(p - x2))) elif d == 1: print(min(t2 * abs(x1 - x2), t1*s + t1*(s-p) + t1 * abs(x2))) else: print(min(t2 * abs(x1 - x2), t1*(p) + t1 * abs(x2)))
python
test
abovesol
codeparrot/apps
all
Solve in Python: # One is the loneliest number ## Task The range of vision of a digit is its own value. `1` can see one digit to the left and one digit to the right,` 2` can see two digits, and so on. Thus, the loneliness of a digit `N` is the sum of the digits which it can see. Given a non-negative integer, your funtion must determine if there's at least one digit `1` in this integer such that its loneliness value is minimal. ## Example ``` number = 34315 ``` digit | can see on the left | can see on the right | loneliness --- | --- | --- | --- 3 | - | 431 | 4 + 3 + 1 = 8 4 | 3 | 315 | 3 + 3 + 1 + 5 = 12 3 | 34 | 15 | 3 + 4 + 1 + 5 = 13 1 | 3 | 5 | 3 + 5 = 8 5 | 3431 | - | 3 + 4 + 3 + 1 = 11 Is there a `1` for which the loneliness is minimal? Yes.
def loneliest(number): if (str(number)).count("1")==0: return False if (str(number)).count("1")==len(str(number)): return True number=[int(a) for a in str(number)] score=[] one=[] for idx,nr in enumerate(number): b = idx-nr f = idx+nr+1 s=0 if b<0: b=0 if f>len(number): f=len(number) s+=sum(number[b:idx]) s+=sum(number[idx+1:f]) if nr==1: one.append(s) else: score.append(s) score.sort() one.sort() if score[0]>=one[0]: return True return False
python
train
qsol
codeparrot/apps
all
Solve in Python: Given two integer arrays A and B, return the maximum length of an subarray that appears in both arrays. Example 1: Input: A: [1,2,3,2,1] B: [3,2,1,4,7] Output: 3 Explanation: The repeated subarray with maximum length is [3, 2, 1]. Note: 1 0
class Solution: def findLength(self, A, B): def check(length): seen = {A[i:i+length] for i in range(len(A) - length + 1)} return any(B[j:j+length] in seen for j in range(len(B) - length + 1)) A = ''.join(map(chr, A)) B = ''.join(map(chr, B)) lo, hi = 0, min(len(A), len(B)) + 1 while lo < hi: mi = int((lo + hi) / 2) if check(mi): lo = mi + 1 else: hi = mi return lo - 1
python
train
qsol
codeparrot/apps
all
I found an interesting problem on https://codeforces.com/problemset/problem/1316/B: Vasya has a string $s$ of length $n$. He decides to make the following modification to the string: Pick an integer $k$, ($1 \leq k \leq n$). For $i$ from $1$ to $n-k+1$, reverse the substring $s[i:i+k-1]$ of $s$. For example, if string $s$ is qwer and $k = 2$, below is the series of transformations the string goes through: qwer (original string) wqer (after reversing the first substring of length $2$) weqr (after reversing the second substring of length $2$) werq (after reversing the last substring of length $2$) Hence, the resulting string after modifying $s$ with $k = 2$ is werq. Vasya wants to choose a $k$ such that the string obtained after the above-mentioned modification is lexicographically smallest possible among all choices of $k$. Among all such $k$, he wants to choose the smallest one. Since he is busy attending Felicity 2020, he asks for your help. A string $a$ is lexicographically smaller than a string $b$ if and only if one of the following holds: $a$ is a prefix of $b$, but $a \ne b$; in the first position where $a$ and $b$ differ, the string $a$ has a letter that appears earlier in the alphabet than the corresponding letter in $b$. -----Input----- Each test contains multiple test cases. The first line contains the number of test cases $t$ ($1 \le t \le 5000$). The description of the test cases follows. The first line of each test case contains a single integer $n$ ($1 \le n \le 5000$) — the length of the string $s$. The second line of each test case contains the string $s$ of $n$ lowercase latin letters. It is guaranteed that the sum of $n$ over all test cases does not exceed $5000$. -----Output----- For each testcase output two lines: In the first line output the lexicographically smallest string $s'$ achievable after the above-mentioned modification. In the second line output the appropriate value of $k$ ($1 \leq k \leq n$) that you chose for performing the modification. If there are multiple values of $k$ that give the lexicographically smallest string, output... I tried it in Python, but could not do it. Can you solve it?
import io, sys, atexit, os import math as ma from decimal import Decimal as dec from itertools import permutations from itertools import combinations def li(): return list(map(int, sys.stdin.readline().split())) def num(): return list(map(int, sys.stdin.readline().split())) def nu(): return int(input()) def find_gcd(x, y): while (y): x, y = y, x % y return x def lcm(x, y): gg = find_gcd(x, y) return (x * y // gg) mm = 1000000007 def solve(): t = nu() for tt in range(t): n=nu() s=input() mn=1 val=s for i in range(2,n+1): x=s[0:i-1] y=s[i-1:] op=n-i+1 if(op%2==0): up=y+x else: up=y+x[::-1] if(up<val): val=up mn=i print(val) print(mn) def __starting_point(): solve() __starting_point()
python
test
abovesol
codeparrot/apps
all
Solve in Python: Maxim wants to buy an apartment in a new house at Line Avenue of Metropolis. The house has n apartments that are numbered from 1 to n and are arranged in a row. Two apartments are adjacent if their indices differ by 1. Some of the apartments can already be inhabited, others are available for sale. Maxim often visits his neighbors, so apartment is good for him if it is available for sale and there is at least one already inhabited apartment adjacent to it. Maxim knows that there are exactly k already inhabited apartments, but he doesn't know their indices yet. Find out what could be the minimum possible and the maximum possible number of apartments that are good for Maxim. -----Input----- The only line of the input contains two integers: n and k (1 ≤ n ≤ 10^9, 0 ≤ k ≤ n). -----Output----- Print the minimum possible and the maximum possible number of apartments good for Maxim. -----Example----- Input 6 3 Output 1 3 -----Note----- In the sample test, the number of good apartments could be minimum possible if, for example, apartments with indices 1, 2 and 3 were inhabited. In this case only apartment 4 is good. The maximum possible number could be, for example, if apartments with indices 1, 3 and 5 were inhabited. In this case all other apartments: 2, 4 and 6 are good.
n, k = map(int, input().split()) if k == n or k == 0: a = 0 else: a = 1 b = 0 if n == k or k == 0: b = 0 else: b = min(n // 3, k) * 2 k -= min(n // 3, k) if k != 0: if n % 3 == 1: k -= 1 elif n % 3 == 2: k -= 1 b += 1 b -= k print(a, b)
python
test
qsol
codeparrot/apps
all
I found an interesting problem on https://codeforces.com/problemset/problem/815/A: On the way to school, Karen became fixated on the puzzle game on her phone! [Image] The game is played as follows. In each level, you have a grid with n rows and m columns. Each cell originally contains the number 0. One move consists of choosing one row or column, and adding 1 to all of the cells in that row or column. To win the level, after all the moves, the number in the cell at the i-th row and j-th column should be equal to g_{i}, j. Karen is stuck on one level, and wants to know a way to beat this level using the minimum number of moves. Please, help her with this task! -----Input----- The first line of input contains two integers, n and m (1 ≤ n, m ≤ 100), the number of rows and the number of columns in the grid, respectively. The next n lines each contain m integers. In particular, the j-th integer in the i-th of these rows contains g_{i}, j (0 ≤ g_{i}, j ≤ 500). -----Output----- If there is an error and it is actually not possible to beat the level, output a single integer -1. Otherwise, on the first line, output a single integer k, the minimum number of moves necessary to beat the level. The next k lines should each contain one of the following, describing the moves in the order they must be done: row x, (1 ≤ x ≤ n) describing a move of the form "choose the x-th row". col x, (1 ≤ x ≤ m) describing a move of the form "choose the x-th column". If there are multiple optimal solutions, output any one of them. -----Examples----- Input 3 5 2 2 2 3 2 0 0 0 1 0 1 1 1 2 1 Output 4 row 1 row 1 col 4 row 3 Input 3 3 0 0 0 0 1 0 0 0 0 Output -1 Input 3 3 1 1 1 1 1 1 1 1 1 Output 3 row 1 row 2 row 3 -----Note----- In the first test case, Karen has a grid with 3 rows and 5 columns. She can perform the following 4 moves to beat the level: [Image] In the second test case, Karen has a grid with 3 rows and 3 columns. It is clear that it is impossible to beat the level; performing any move will create three 1s on the grid, but it is required to only have one 1 in the center. In the... I tried it in Python, but could not do it. Can you solve it?
"""Ввод размера матрицы""" nm = [int(s) for s in input().split()] """Ввод массива""" a = [] for i in range(nm[0]): a.append([int(j) for j in input().split()]) rez=[] def stroka(): nonlocal rez rez_row=[] rez_r=0 for i in range(nm[0]): min_row=501 for j in range(nm[1]): if a[i][j]< min_row: min_row=a[i][j] rez_r+=min_row if min_row != 0: for c in range(min_row): rez.append('row ' + str(i+1)) for j in range(nm[1]): if a[i][j]>0: a[i][j]-= min_row def grafa(): nonlocal rez rez_c=0 for j in range(nm[1]): min_col=501 for i in range(nm[0]): if a[i][j]< min_col: min_col=a[i][j] rez_c+=min_col if min_col !=0: for c in range(min_col): rez.append('col '+ str(j+1)) for i in range(nm[0]): if a[i][j]>0: a[i][j] -=min_col if nm[0]<nm[1]: stroka() grafa() else: grafa() stroka() maxEl = max(max(a)) if maxEl == 0: print(len(rez)) for el in rez: print(el) else: print(-1)
python
test
abovesol
codeparrot/apps
all
Solve in Python: There were n groups of students which came to write a training contest. A group is either one person who can write the contest with anyone else, or two people who want to write the contest in the same team. The coach decided to form teams of exactly three people for this training. Determine the maximum number of teams of three people he can form. It is possible that he can't use all groups to form teams. For groups of two, either both students should write the contest, or both should not. If two students from a group of two will write the contest, they should be in the same team. -----Input----- The first line contains single integer n (2 ≤ n ≤ 2·10^5) — the number of groups. The second line contains a sequence of integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 2), where a_{i} is the number of people in group i. -----Output----- Print the maximum number of teams of three people the coach can form. -----Examples----- Input 4 1 1 2 1 Output 1 Input 2 2 2 Output 0 Input 7 2 2 2 1 1 1 1 Output 3 Input 3 1 1 1 Output 1 -----Note----- In the first example the coach can form one team. For example, he can take students from the first, second and fourth groups. In the second example he can't make a single team. In the third example the coach can form three teams. For example, he can do this in the following way: The first group (of two people) and the seventh group (of one person), The second group (of two people) and the sixth group (of one person), The third group (of two people) and the fourth group (of one person).
# IAWT n = int(input()) a = list(map(int, input().split())) x = a.count(1) y = a.count(2) z = min(x, y) x -= z z += x // 3 print(z)
python
test
qsol
codeparrot/apps
all
Solve in Python: You are given a string S consisting of lowercase English letters. Determine whether we can turn S into a palindrome by repeating the operation of swapping two adjacent characters. If it is possible, find the minimum required number of operations. -----Constraints----- - 1 \leq |S| \leq 2 × 10^5 - S consists of lowercase English letters. -----Input----- Input is given from Standard Input in the following format: S -----Output----- If we cannot turn S into a palindrome, print -1. Otherwise, print the minimum required number of operations. -----Sample Input----- eel -----Sample Output----- 1 We can turn S into a palindrome by the following operation: - Swap the 2-nd and 3-rd characters. S is now ele.
from string import ascii_lowercase class Bit: def __init__(self, n): self.size = n self.tree = [0] * (n + 1) def sum(self, i): s = 0 while i > 0: s += self.tree[i] i -= i & -i return s def add(self, i, x): while i <= self.size: self.tree[i] += x i += i & -i def solve(s): indices = {c: [] for c in ascii_lowercase} for i, c in enumerate(s): indices[c].append(i) n = len(s) center = n // 2 bubbles = [-1] * n odd_flag = False lefts, rights = [], [] used = [False] * n for c, ids in list(indices.items()): cnt = len(ids) if cnt & 1: if odd_flag: return -1 odd_flag = True bubbles[ids[cnt // 2]] = center + 1 used[center] = True for i in range(cnt // 2): li, ri = ids[i], ids[-i - 1] if li < center: lefts.append((li, ri)) used[n - li - 1] = True else: rights.append((li, ri)) lefts.sort() rights.sort() r_itr = iter(rights) # print(lefts) # print(rights) for i, (li, ri) in enumerate(lefts): bubbles[li] = i + 1 bubbles[ri] = n - i for i in range(len(lefts), center): li, ri = next(r_itr) bubbles[li] = i + 1 bubbles[ri] = n - i # print(bubbles) ans = 0 bit = Bit(n) for i, m in enumerate(bubbles): ans += i - bit.sum(m) bit.add(m, 1) return ans print((solve(input())))
python
train
qsol
codeparrot/apps
all
Solve in Python: Roger recently built a circular race track with length K$K$. After hosting a few races, he realised that people do not come there to see the race itself, they come to see racers crash into each other (what's wrong with our generation…). After this realisation, Roger decided to hold a different kind of "races": he hired N$N$ racers (numbered 1$1$ through N$N$) whose task is to crash into each other. At the beginning, for each valid i$i$, the i$i$-th racer is Xi$X_i$ metres away from the starting point of the track (measured in the clockwise direction) and driving in the direction Di$D_i$ (clockwise or counterclockwise). All racers move with the constant speed 1$1$ metre per second. The lengths of cars are negligible, but the track is only wide enough for one car, so whenever two cars have the same position along the track, they crash into each other and the direction of movement of each of these cars changes (from clockwise to counterclockwise and vice versa). The cars do not change the directions of their movement otherwise. Since crashes reduce the lifetime of the racing cars, Roger sometimes wonders how many crashes happen. You should answer Q$Q$ queries. In each query, you are given an integer T$T$ and you should find the number of crashes that happen until T$T$ seconds have passed (inclusive). -----Input----- - The first line of the input contains three space-separated integers N$N$, Q$Q$ and K$K$. - N$N$ lines follow. For each i$i$ (1≤i≤N$1 \le i \le N$), the i$i$-th of these lines contains two space-separated integers Di$D_i$ and Xi$X_i$, where Di=1$D_i = 1$ and Di=2$D_i = 2$ denote the clockwise and counterclockwise directions respectively. - Each of the next Q$Q$ lines contain a single integer T$T$ describing a query. -----Output----- For each query, print a single line containing one integer — the number of crashes. -----Constraints----- - 1≤N≤105$1 \le N \le 10^5$ - 1≤Q≤1,000$1 \le Q \le 1,000$ - 1≤K≤1012$1 \le K \le 10^{12}$ - 1≤Di≤2$1 \le D_i \le 2$ for each valid i$i$ - 0≤Xi≤K−1$0 \le X_i \le...
import numpy as np from numba import njit i8 = np.int64 @njit def solve(a, b, t, K, N): t1 = t // K d = t % K * 2 # b が a から a + d の位置にあれば衝突する x = 0 y = 0 ans = 0 for c in a: while b[x] < c: x += 1 while b[y] <= c + d: y += 1 ans += y - x ans += t1 * len(a) * (N - len(a)) * 2 return ans def set_ini(DX, K): a = DX[1][DX[0] == 1] a = np.sort(a) b = DX[1][DX[0] == 2] b = np.sort(b) b = np.hstack((b, b + K, b + 2 * K, [3 * K])) return a, b def main(): f = open('/dev/stdin', 'rb') vin = np.fromstring(f.read(), i8, sep=' ') N, Q, K = vin[0:3] head = 3 DX = vin[head:head + 2*N].reshape(-1, 2).T a, b = set_ini(DX, K) head += 2 * N T = vin[head: head + Q] for t in T: print(solve(a, b, t, K, N)) def __starting_point(): main() __starting_point()
python
train
qsol
codeparrot/apps
all
Solve in Python: # Task: Given a list of numbers, determine whether the sum of its elements is odd or even. Give your answer as a string matching `"odd"` or `"even"`. If the input array is empty consider it as: `[0]` (array with a zero). ## Example: ``` odd_or_even([0]) == "even" odd_or_even([0, 1, 4]) == "odd" odd_or_even([0, -1, -5]) == "even" ``` Have fun!
def odd_or_even(n:list): if len(n) == 0: return [0] elif sum(n) % 2 == 0: return "even" else: return "odd"
python
train
qsol
codeparrot/apps
all
Solve in Python: Mrs Jefferson is a great teacher. One of her strategies that helped her to reach astonishing results in the learning process is to have some fun with her students. At school, she wants to make an arrangement of her class to play a certain game with her pupils. For that, she needs to create the arrangement with **the minimum amount of groups that have consecutive sizes**. Let's see. She has ```14``` students. After trying a bit she could do the needed arrangement: ```[5, 4, 3, 2]``` - one group of ```5``` students - another group of ```4``` students - then, another one of ```3``` - and finally, the smallest group of ```2``` students. As the game was a success, she was asked to help to the other classes to teach and show the game. That's why she desperately needs some help to make this required arrangements that make her spend a lot of time. To make things worse, she found out that there are some classes with some special number of students that is impossible to get that arrangement. Please, help this teacher! Your code will receive the number of students of the class. It should output the arrangement as an array with the consecutive sizes of the groups in decreasing order. For the special case that no arrangement of the required feature is possible the code should output ```[-1] ``` The value of n is unknown and may be pretty high because some classes joined to to have fun with the game. You may see more example tests in the Example Tests Cases Box.
def shortest_arrang(n): r = n // 2 + 2 a = [i for i in range(r, 0, -1)] for i in range(r): for j in range(r + 1): if sum(a[i:j]) == n: return a[i:j] return [-1]
python
train
qsol
codeparrot/apps
all
Solve in Python: At an arcade, Takahashi is playing a game called RPS Battle, which is played as follows: - The player plays N rounds of Rock Paper Scissors against the machine. (See Notes for the description of Rock Paper Scissors. A draw also counts as a round.) - Each time the player wins a round, depending on which hand he/she uses, he/she earns the following score (no points for a draw or a loss): - R points for winning with Rock; - S points for winning with Scissors; - P points for winning with Paper. - However, in the i-th round, the player cannot use the hand he/she used in the (i-K)-th round. (In the first K rounds, the player can use any hand.) Before the start of the game, the machine decides the hand it will play in each round. With supernatural power, Takahashi managed to read all of those hands. The information Takahashi obtained is given as a string T. If the i-th character of T (1 \leq i \leq N) is r, the machine will play Rock in the i-th round. Similarly, p and s stand for Paper and Scissors, respectively. What is the maximum total score earned in the game by adequately choosing the hand to play in each round? -----Notes----- In this problem, Rock Paper Scissors can be thought of as a two-player game, in which each player simultaneously forms Rock, Paper, or Scissors with a hand. - If a player chooses Rock and the other chooses Scissors, the player choosing Rock wins; - if a player chooses Scissors and the other chooses Paper, the player choosing Scissors wins; - if a player chooses Paper and the other chooses Rock, the player choosing Paper wins; - if both players play the same hand, it is a draw. -----Constraints----- - 2 \leq N \leq 10^5 - 1 \leq K \leq N-1 - 1 \leq R,S,P \leq 10^4 - N,K,R,S, and P are all integers. - |T| = N - T consists of r, p, and s. -----Input----- Input is given from Standard Input in the following format: N K R S P T -----Output----- Print the maximum total score earned in the game. -----Sample Input----- 5 2 8 7 6 rsrpr -----Sample Output----- 27 The machine...
n, k = list(map(int, input().split())) r, s, p = list(map(int, input().split())) t = input() tt = list(t) d = {'r':p, 's': r, 'p':s} dp = [d[t[i]] for i in range(n)] for i in range(n-k): if tt[i]==tt[i+k]: dp[i+k] = 0 tt[i+k] = 'x' print((sum(dp)))
python
test
qsol
codeparrot/apps
all
Solve in Python: Not so long ago company R2 bought company R1 and consequently, all its developments in the field of multicore processors. Now the R2 laboratory is testing one of the R1 processors. The testing goes in n steps, at each step the processor gets some instructions, and then its temperature is measured. The head engineer in R2 is keeping a report record on the work of the processor: he writes down the minimum and the maximum measured temperature in his notebook. His assistant had to write down all temperatures into his notebook, but (for unknown reasons) he recorded only m. The next day, the engineer's assistant filed in a report with all the m temperatures. However, the chief engineer doubts that the assistant wrote down everything correctly (naturally, the chief engineer doesn't doubt his notes). So he asked you to help him. Given numbers n, m, min, max and the list of m temperatures determine whether you can upgrade the set of m temperatures to the set of n temperatures (that is add n - m temperatures), so that the minimum temperature was min and the maximum one was max. -----Input----- The first line contains four integers n, m, min, max (1 ≤ m < n ≤ 100; 1 ≤ min < max ≤ 100). The second line contains m space-separated integers t_{i} (1 ≤ t_{i} ≤ 100) — the temperatures reported by the assistant. Note, that the reported temperatures, and the temperatures you want to add can contain equal temperatures. -----Output----- If the data is consistent, print 'Correct' (without the quotes). Otherwise, print 'Incorrect' (without the quotes). -----Examples----- Input 2 1 1 2 1 Output Correct Input 3 1 1 3 2 Output Correct Input 2 1 1 3 2 Output Incorrect -----Note----- In the first test sample one of the possible initial configurations of temperatures is [1, 2]. In the second test sample one of the possible initial configurations of temperatures is [2, 1, 3]. In the third test sample it is impossible to add one temperature to obtain the minimum equal to 1 and the maximum equal to 3.
I=lambda:list(map(int,input().split())) n,m,N,X=I() t=I() r=min(t)!=N r+=max(t)!=X print(['C','Inc'][m+r>n or min(t)<N or max(t)>X]+'orrect')
python
test
qsol
codeparrot/apps
all
I found an interesting problem on https://www.codewars.com/kata/5aa3e2b0373c2e4b420009af: # Task Write a function that accepts `msg` string and returns local tops of string from the highest to the lowest. The string's tops are from displaying the string in the below way: ``` 7891012 TUWvXY 6 3 ABCDE S Z 5 lmno z F R 1 4 abc k p v G Q 2 3 .34..9 d...j q....x H.....P 3......2 125678 efghi rstuwy IJKLMNO 45678901 ``` The next top is always 1 character higher than the previous one. For the above example, the solution for the `123456789abcdefghijklmnopqrstuwyxvzABCDEFGHIJKLMNOPQRSTUWvXYZ123456789012345678910123` input string is `7891012TUWvXYABCDElmnoabc34`. - When the `msg` string is empty, return an empty string. - The input strings may be very long. Make sure your solution has good performance. - The (.)dots on the sample dispaly of string are only there to help you to understand the pattern Check the test cases for more samples. # Series - [String tops](https://www.codewars.com/kata/59b7571bbf10a48c75000070) - [Square string tops](https://www.codewars.com/kata/5aa3e2b0373c2e4b420009af) I tried it in Python, but could not do it. Can you solve it?
def tops(msg): n = len(msg) res,i,j,k = "",2,2,7 while i < n: res = msg[i:i+j] + res i,j,k=i+k,j+1,k+4 return res
python
train
abovesol
codeparrot/apps
all
I found an interesting problem on https://www.codechef.com/problems/DIFNEIGH: You are given an empty grid with $N$ rows (numbered $1$ through $N$) and $M$ columns (numbered $1$ through $M$). You should fill this grid with integers in a way that satisfies the following rules: - For any three cells $c_1$, $c_2$ and $c_3$ such that $c_1$ shares a side with $c_2$ and another side with $c_3$, the integers written in cells $c_2$ and $c_3$ are distinct. - Let's denote the number of different integers in the grid by $K$; then, each of these integers should lie between $1$ and $K$ inclusive. - $K$ should be minimum possible. Find the minimum value of $K$ and a resulting (filled) grid. If there are multiple solutions, you may find any one. -----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 and only line of each test case contains two space-separated integers $N$ and $M$. -----Output----- - For each test case, print $N+1$ lines. - The first line should contain a single integer — the minimum $K$. - Each of the following $N$ lines should contain $M$ space-separated integers between $1$ and $K$ inclusive. For each valid $i, j$, the $j$-th integer on the $i$-th line should denote the number in the $i$-th row and $j$-th column of the grid. -----Constraints----- - $1 \le T \le 500$ - $1 \le N, M \le 50$ - the sum of $N \cdot M$ over all test cases does not exceed $7 \cdot 10^5$ -----Subtasks----- Subtask #1 (100 points): original constraints -----Example Input----- 2 1 1 2 3 -----Example Output----- 1 1 3 1 1 2 2 3 3 -----Explanation----- Example case 1: There is only one cell in the grid, so the only valid way to fill it is to write $1$ in this cell. Note that we cannot use any other integer than $1$. Example case 2: For example, the integers written in the neighbours of cell $(2, 2)$ are $1$, $2$ and $3$; all these numbers are pairwise distinct and the integer written inside the cell $(2, 2)$ does not matter. Note that there are pairs of neighbouring cells with the same integer... I tried it in Python, but could not do it. Can you solve it?
for _ in range(int(input())): n, m = list(map(int, input().split())) ans = [[0 for i in range(m)] for i in range(n)] k = 0 if n == 1: for i in range(m): if i%4 == 0 or i%4 == 1: t = 1 else: t = 2 ans[0][i] = t k = max(k, ans[0][i]) elif m == 1: for i in range(n): if i%4 == 0 or i%4 == 1: t = 1 else: t = 2 ans[i][0] = t k = max(k, ans[i][0]) elif n == 2: t = 1 for i in range(m): ans[0][i] = t ans[1][i] = t t = (t)%3 + 1 k = max(k, ans[0][i]) elif m == 2: t = 1 for i in range(n): ans[i][0] = t ans[i][1] = t t = t%3 + 1 k = max(k, ans[i][0]) else: for i in range(n): if i%4 == 0 or i%4 == 1: t = 0 else: t = 2 for j in range(m): ans[i][j] = (t%4) + 1 t += 1 k = max(k, ans[i][j]) print(k) for i in range(n): print(*ans[i])
python
train
abovesol
codeparrot/apps
all
I found an interesting problem on https://www.codewars.com/kata/5bc5cfc9d38567e29600019d: ## Story Your company migrated the last 20 years of it's *very important data* to a new platform, in multiple phases. However, something went wrong: some of the essential time-stamps were messed up! It looks like that some servers were set to use the `dd/mm/yyyy` date format, while others were using the `mm/dd/yyyy` format during the migration. Unfortunately, the original database got corrupted in the process and there are no backups available... Now it's up to you to assess the damage. ## Task You will receive a list of records as strings in the form of `[start_date, end_date]` given in the ISO `yyyy-mm-dd` format, and your task is to count how many of these records are: * **correct**: there can be nothing wrong with the dates, the month/day cannot be mixed up, or it would not make a valid timestamp in any other way; e.g. `["2015-04-04", "2015-05-13"]` * **recoverable**: invalid in its current form, but the original timestamp can be recovered, because there is only one valid combination possible; e.g. `["2011-10-08", "2011-08-14"]` * **uncertain**: one or both dates are ambiguous, and they may generate multiple valid timestamps, so the original cannot be retrieved; e.g. `["2002-02-07", "2002-12-10"]` **Note:** the original records always defined a *non-negative* duration Return your findings in an array: `[ correct_count, recoverable_count, uncertain_count ]` ## Examples --- ## My other katas If you enjoyed this kata then please try [my other katas](https://www.codewars.com/collections/katas-created-by-anter69)! :-) I tried it in Python, but could not do it. Can you solve it?
from datetime import date def less(d1, d2): if d1 == None or d2 == None: return 0 return 1 if d1 <= d2 else 0 def check_dates(records): correct = recoverable = uncertain = 0 for interval in records: start = interval[0].split('-') end = interval[1].split('-') try: start1 = date(int(start[0]), int(start[1].lstrip('0')), int(start[2].lstrip('0'))) except: start1 = None try: start2 = date(int(start[0]), int(start[2].lstrip('0')), int(start[1].lstrip('0'))) except: start2 = None try: end1 = date(int(end[0]), int(end[1].lstrip('0')), int(end[2].lstrip('0'))) except: end1 = None try: end2 = date(int(end[0]), int(end[2].lstrip('0')), int(end[1].lstrip('0'))) except: end2 = None combinations = less(start1, end1) + less(start1, end2) + less(start2, end1) + less(start2, end2) if start1 == start2: combinations -= 1 if end1 == end2: combinations -= 1 if start1 == start2 and end1 == end2: combinations -= 1 if less(start1, end1) == 1 and combinations == 1: correct += 1 elif combinations == 1: recoverable += 1 else: uncertain += 1 return [correct, recoverable, uncertain]
python
train
abovesol
codeparrot/apps
all
Solve in Python: Ksenia has an array $a$ consisting of $n$ positive integers $a_1, a_2, \ldots, a_n$. In one operation she can do the following: choose three distinct indices $i$, $j$, $k$, and then change all of $a_i, a_j, a_k$ to $a_i \oplus a_j \oplus a_k$ simultaneously, where $\oplus$ denotes the bitwise XOR operation. She wants to make all $a_i$ equal in at most $n$ operations, or to determine that it is impossible to do so. She wouldn't ask for your help, but please, help her! -----Input----- The first line contains one integer $n$ ($3 \leq n \leq 10^5$) — the length of $a$. The second line contains $n$ integers, $a_1, a_2, \ldots, a_n$ ($1 \leq a_i \leq 10^9$) — elements of $a$. -----Output----- Print YES or NO in the first line depending on whether it is possible to make all elements equal in at most $n$ operations. If it is possible, print an integer $m$ ($0 \leq m \leq n$), which denotes the number of operations you do. In each of the next $m$ lines, print three distinct integers $i, j, k$, representing one operation. If there are many such operation sequences possible, print any. Note that you do not have to minimize the number of operations. -----Examples----- Input 5 4 2 1 7 2 Output YES 1 1 3 4 Input 4 10 4 49 22 Output NO -----Note----- In the first example, the array becomes $[4 \oplus 1 \oplus 7, 2, 4 \oplus 1 \oplus 7, 4 \oplus 1 \oplus 7, 2] = [2, 2, 2, 2, 2]$.
def solve(n, arr): xor_sum = arr[0] for i in range(1, n): xor_sum ^= arr[i] if n % 2 == 0: if xor_sum: print("NO") return else: n -= 1 if n == 3: print(1) print(1, 2, 3) return print("YES") print(n-2) for i in range(1, n-1, 2): print(i, i+1, i+2) for i in range(n-4, 0, -2): print(i, i+1, i+2) n = int(input()) arr = list(map(int, input().split())) solve(n, arr)
python
test
qsol
codeparrot/apps
all
Solve in Python: Introduction Mr. Safety loves numeric locks and his Nokia 3310. He locked almost everything in his house. He is so smart and he doesn't need to remember the combinations. He has an algorithm to generate new passcodes on his Nokia cell phone. Task Can you crack his numeric locks? Mr. Safety's treasures wait for you. Write an algorithm to open his numeric locks. Can you do it without his Nokia 3310? Input The `str` or `message` (Python) input string consists of lowercase and upercase characters. It's a real object that you want to unlock. Output Return a string that only consists of digits. Example ``` unlock("Nokia") // => 66542 unlock("Valut") // => 82588 unlock("toilet") // => 864538 ```
table = str.maketrans("abcdefghijklmnopqrstuvwxyz", "22233344455566677778889999") def unlock(message): return message.lower().translate(table)
python
train
qsol
codeparrot/apps
all
Solve in Python: Nobody knows, but $N$ frogs live in Chef's garden. Now they are siting on the X-axis and want to speak to each other. One frog can send a message to another one if the distance between them is less or equal to $K$. Chef knows all $P$ pairs of frogs, which want to send messages. Help him to define can they or not! Note : More than $1$ frog can be on the same point on the X-axis. -----Input----- - The first line contains three integers $N$, $K$ and $P$. - The second line contains $N$ space-separated integers $A_1$, $A_2$, …, $A_N$ denoting the x-coordinates of frogs". - Each of the next $P$ lines contains two integers $A$ and $B$ denoting the numbers of frogs according to the input. -----Output----- For each pair print "Yes" without a brackets if frogs can speak and "No" if they cannot. -----Constraints----- - $1 \le N, P \le 10^5$ - $0 \le A_i, K \le 10^9$ - $1 \le A, B \le N$ -----Example----- -----Sample Input:----- 5 3 3 0 3 8 5 12 1 2 1 3 2 5 -----Sample Output:----- Yes Yes No -----Explanation----- - For pair $(1, 2)$ frog $1$ can directly speak to the frog $2$ as the distance between them is $3 - 0 = 3 \le K$ . - For pair $(1, 3)$ frog $1$ can send a message to frog $2$, frog $2$ can send it to frog $4$ and it can send it to frog $3$. - For pair $(2, 5)$ frogs can't send a message under current constraints.
n,k,p=map(int,input().split()) l=list(map(int,input().split())) t_1=[] for i in range(n): t_1.append([i,l[i]]) t_1=sorted(t_1,key=lambda x:x[1],reverse=True) dis={} for i in range(n): if i==0: dis[i]=t_1[i][1]+k continue if (t_1[i-1][1]-t_1[i][1])<=k: dis[i]=dis[i-1] else: dis[i]=t_1[i][1]+k trans={} for i in range(n): trans[t_1[i][0]]=i for i in range(p): a,b=map(int,input().split()) t_2=a-1 t_3=b-1 if dis[trans[t_2]]==dis[trans[t_3]]: print('Yes') else: print('No')
python
train
qsol
codeparrot/apps
all
Solve in Python: Naman owns a very famous Ice Cream parlour in Pune. He has a wide range of flavours with different pricing. Every flavour costs ₹ X per gram and quantity of each flavour in the parlour is indefinite. Now, Naman has received an order for a party wherein he is asked to prepare each Ice Cream with N number of flavours. He needs to prepare each Ice Cream of W grams and at the same time has to keep the cost minimum. Can you help him out? Note: If it is not possible to prepare such an Ice Cream, print “Not Possible”. -----Input:----- First line contains an integer T denoting the number of test cases. First line of every test case contains an integer N denoting the number of flavours. The second line of every test case by N space separated integers denoting the cost per gram of each flavour. Second line of every test case contains two space separated integers W and Y denoting the weight of Ice Cream in grams and the number of flavours to be used respectively. -----Output:----- For each test case, print the total cost of the Ice Cream in a single line. -----Constraints:----- 1 ≤ T ≤ 100 1 ≤ N,W,Y ≤ 40000 -----Example:-----Input: 2 5 4 6 8 1 10 10 3 2 1 2 1 2Output: 18 Not Possible -----Explanation:----- In the first test case to achieve the minimum cost, the Ice Cream will consist of 8 grams of flavour costing ₹1, 1 gram of flavour costing ₹4 and 1 gram of flavour costing ₹6. In the second test case it is not possible to make an ice-cream weighing 1 gram using 2 flavours.
test = int(input()) for i in range(test): flavor = int(input()) rate = input() gaf = input() gaf = gaf.split() gaf = [int(x) for x in gaf] rate = rate.split() rate = [int(x) for x in rate] rate.sort() c = gaf[0] - gaf[1] sum = rate[0]*c t = True if gaf[0] < gaf[1]: t = False j = 0 while(j<gaf[1] and t): sum = sum + rate[j] j = j + 1 if t : print(sum) else: print("Not Possible")
python
train
qsol
codeparrot/apps
all
I found an interesting problem on https://codeforces.com/problemset/problem/1076/A: You are given a string $s$ consisting of $n$ lowercase Latin letters. You have to remove at most one (i.e. zero or one) character of this string in such a way that the string you obtain will be lexicographically smallest among all strings that can be obtained using this operation. String $s = s_1 s_2 \dots s_n$ is lexicographically smaller than string $t = t_1 t_2 \dots t_m$ if $n < m$ and $s_1 = t_1, s_2 = t_2, \dots, s_n = t_n$ or there exists a number $p$ such that $p \le min(n, m)$ and $s_1 = t_1, s_2 = t_2, \dots, s_{p-1} = t_{p-1}$ and $s_p < t_p$. For example, "aaa" is smaller than "aaaa", "abb" is smaller than "abc", "pqr" is smaller than "z". -----Input----- The first line of the input contains one integer $n$ ($2 \le n \le 2 \cdot 10^5$) — the length of $s$. The second line of the input contains exactly $n$ lowercase Latin letters — the string $s$. -----Output----- Print one string — the smallest possible lexicographically string that can be obtained by removing at most one character from the string $s$. -----Examples----- Input 3 aaa Output aa Input 5 abcda Output abca -----Note----- In the first example you can remove any character of $s$ to obtain the string "aa". In the second example "abca" < "abcd" < "abcda" < "abda" < "acda" < "bcda". I tried it in Python, but could not do it. Can you solve it?
n=int(input()) s=input() l=[] for i in range(1,n): if(s[i]<s[i-1]): x=s[:i-1]+s[i:] print(x) break if(i==n-1): print(s[:n-1]) break
python
test
abovesol
codeparrot/apps
all
I found an interesting problem on https://www.codechef.com/ICM2020/problems/ICM2003: Everyone loves short problem statements. Given a function $ f(x) $ find its minimum value over the range $ 0 < x < π/2$ $ f(x) = ( x^2 + b*x + c ) / sin( x ) $ -----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, two real numbers $b, c$. -----Output:----- For each test case, output the minimum value of $ f(x) $ over the given range. Absolute error of $10^{-6}$ is allowed. -----Constraints----- - $1 \leq T \leq 100000$ - $1 \leq b,c \leq 20$ -----Sample Input:----- 1 2 2 -----Sample Output:----- 5.8831725615 I tried it in Python, but could not do it. Can you solve it?
import sys import math input=sys.stdin.readline def binary(l,r,co,b,c): x=(l+r)/2 #print(x) val1=(2*x+b)*math.sin(x) val2=(x**2+b*x+c)*math.cos(x) x=(l+r)/2 val=val1-val2 if(abs(val)<.0000001 or co==150): return (l+r)/2 if(val<0): return binary((l+r)/2,r,co+1,b,c) else: return binary(l,(l+r)/2,co+1,b,c) t=int(input()) for _ in range(t): b,c=list(map(float,input().split())) x=binary(.0000000001,math.pi/2-.0000000001,0,b,c) #print("t=",_) val=(x*x+b*x+c)/math.sin(x) print(val)
python
train
abovesol
codeparrot/apps
all
I found an interesting problem on https://atcoder.jp/contests/abc060/tasks/abc060_b: We ask you to select some number of positive integers, and calculate the sum of them. It is allowed to select as many integers as you like, and as large integers as you wish. You have to follow these, however: each selected integer needs to be a multiple of A, and you need to select at least one integer. Your objective is to make the sum congruent to C modulo B. Determine whether this is possible. If the objective is achievable, print YES. Otherwise, print NO. -----Constraints----- - 1 ≤ A ≤ 100 - 1 ≤ B ≤ 100 - 0 ≤ C < B -----Input----- Input is given from Standard Input in the following format: A B C -----Output----- Print YES or NO. -----Sample Input----- 7 5 1 -----Sample Output----- YES For example, if you select 7 and 14, the sum 21 is congruent to 1 modulo 5. I tried it in Python, but could not do it. Can you solve it?
a, b, c = list(map(int, input().split())) for i in range(a, (a * b) + 1, a): if i % b == c: print("YES") return print("NO")
python
test
abovesol
codeparrot/apps
all
I found an interesting problem on https://www.codechef.com/problems/BUCKETS: There are $N$ buckets numbered $1$ through $N$. The buckets contain balls; each ball has a color between $1$ and $K$. Let's denote the number of balls with color $j$ that are initially in bucket $i$ by $a_{i, j}$. For each $i$ from $1$ to $N-1$ (in this order), someone draws a ball uniformly at random from bucket $i$ and puts it into bucket $i+1$, then continues to draw the next ball. After putting a ball in bucket $N$, this person draws a ball, again uniformly at random, from bucket $N$. For each color from $1$ to $K$, find the probability that the ball drawn from bucket $N$ has this color. -----Input----- - The first line of the input contains two space-separated integers $N$ and $K$. - $N$ lines follow. For each $i$ ($1 \le i \le N$), the $i$-th of these lines contains $K$ space-separated integers $a_{i, 1}, a_{i, 2}, \ldots, a_{i, K}$. -----Output----- Print a single line containing $K$ space-separated real numbers. For each valid $i$, the $i$-th of these numbers should denote the probability that the last drawn ball has color $i$. your answer will be considered correct if absolute or relative error does not exceed $10^{-6}$ -----Constraints----- - $1 \le N, K \le 1,000$ - $0 \le a_{i, j} \le 10$ for each valid $i, j$ - initially, there is at least one ball in bucket $1$ -----Subtasks----- Subtask #1 (30 points): $1 \le N, K \le 100$ Subtask #2 (70 points): original constraints -----Example Input----- 2 2 0 1 1 1 -----Example Output----- 0.333333 0.666667 -----Explanation----- I tried it in Python, but could not do it. Can you solve it?
""" Url: https://www.codechef.com/problems/BUCKETS """ __author__ = "Ronald Kaiser" __email__ = "raios dot catodicos at gmail dot com" N, K = list(map(int, input().split())) a = list(map(int, input().split())) s = sum(a) p = list([v/s for v in a]) for _ in range(N-1): a = list(map(int, input().split())) sa = sum(a) + 1 p = [p[i]*(a[i] + 1)/sa + (1-p[i])*(a[i]/sa) for i in range(K)] print(*p)
python
train
abovesol
codeparrot/apps
all
I found an interesting problem on https://codeforces.com/problemset/problem/590/A: A schoolboy named Vasya loves reading books on programming and mathematics. He has recently read an encyclopedia article that described the method of median smoothing (or median filter) and its many applications in science and engineering. Vasya liked the idea of the method very much, and he decided to try it in practice. Applying the simplest variant of median smoothing to the sequence of numbers a_1, a_2, ..., a_{n} will result a new sequence b_1, b_2, ..., b_{n} obtained by the following algorithm: b_1 = a_1, b_{n} = a_{n}, that is, the first and the last number of the new sequence match the corresponding numbers of the original sequence. For i = 2, ..., n - 1 value b_{i} is equal to the median of three values a_{i} - 1, a_{i} and a_{i} + 1. The median of a set of three numbers is the number that goes on the second place, when these three numbers are written in the non-decreasing order. For example, the median of the set 5, 1, 2 is number 2, and the median of set 1, 0, 1 is equal to 1. In order to make the task easier, Vasya decided to apply the method to sequences consisting of zeros and ones only. Having made the procedure once, Vasya looked at the resulting sequence and thought: what if I apply the algorithm to it once again, and then apply it to the next result, and so on? Vasya tried a couple of examples and found out that after some number of median smoothing algorithm applications the sequence can stop changing. We say that the sequence is stable, if it does not change when the median smoothing is applied to it. Now Vasya wonders, whether the sequence always eventually becomes stable. He asks you to write a program that, given a sequence of zeros and ones, will determine whether it ever becomes stable. Moreover, if it ever becomes stable, then you should determine what will it look like and how many times one needs to apply the median smoothing algorithm to initial sequence in order to obtain a stable one. -----Input----- The first input line of the input contains a single integer n (3 ≤... I tried it in Python, but could not do it. Can you solve it?
import sys input=sys.stdin.readline n=int(input()) a=list(map(int,input().split())) d=[] e=[] for i in range(1,n-1): if a[i]!=a[i-1] and a[i]!=a[i+1]: e.append([a[i],i]) else: if e!=[]: d.append(e) e=[] if e!=[]: d.append(e) if len(d)==0: print(0) print(*a) else: e=[] for i in range(len(d)): if d[i][0][0]==0: if len(d[i])%2==0: m=len(d[i]) e.append(m//2) for j in range(m//2): a[d[i][j][1]]=1 a[d[i][m-j-1][1]]=0 else: m=len(d[i]) e.append(m//2+1) for j in range(m): a[d[i][j][1]]=1 if d[i][0][0]==1: if len(d[i])%2==0: m=len(d[i]) e.append(m//2) for j in range(m//2): a[d[i][j][1]]=0 a[d[i][m-j-1][1]]=1 else: m=len(d[i]) e.append(m//2+1) for j in range(m): a[d[i][j][1]]=0 print(max(e)) print(*a)
python
train
abovesol
codeparrot/apps
all
Solve in Python: An integer X is called a Harshad number if X is divisible by f(X), where f(X) is the sum of the digits in X when written in base 10. Given an integer N, determine whether it is a Harshad number. -----Constraints----- - 1?N?10^8 - N is an integer. -----Input----- Input is given from Standard Input in the following format: N -----Output----- Print Yes if N is a Harshad number; print No otherwise. -----Sample Input----- 12 -----Sample Output----- Yes f(12)=1+2=3. Since 12 is divisible by 3, 12 is a Harshad number.
#!/usr/bin/env python3 import sys sys.setrecursionlimit(10**6) n = int(input()) fx = sum([int(i) for i in str(n)]) if n % fx == 0: print("Yes") else: print("No")
python
test
qsol
codeparrot/apps
all
Solve in Python: Arkady is playing Battleship. The rules of this game aren't really important. There is a field of $n \times n$ cells. There should be exactly one $k$-decker on the field, i. e. a ship that is $k$ cells long oriented either horizontally or vertically. However, Arkady doesn't know where it is located. For each cell Arkady knows if it is definitely empty or can contain a part of the ship. Consider all possible locations of the ship. Find such a cell that belongs to the maximum possible number of different locations of the ship. -----Input----- The first line contains two integers $n$ and $k$ ($1 \le k \le n \le 100$) — the size of the field and the size of the ship. The next $n$ lines contain the field. Each line contains $n$ characters, each of which is either '#' (denotes a definitely empty cell) or '.' (denotes a cell that can belong to the ship). -----Output----- Output two integers — the row and the column of a cell that belongs to the maximum possible number of different locations of the ship. If there are multiple answers, output any of them. In particular, if no ship can be placed on the field, you can output any cell. -----Examples----- Input 4 3 #..# #.#. .... .### Output 3 2 Input 10 4 #....##... .#...#.... ..#..#..#. ...#.#.... .#..##.#.. .....#...# ...#.##... .#...#.#.. .....#..#. ...#.#...# Output 6 1 Input 19 6 ##..............### #......#####.....## .....#########..... ....###########.... ...#############... ..###############.. .#################. .#################. .#################. .#################. #####....##....#### ####............### ####............### #####...####...#### .#####..####..##### ...###........###.. ....###########.... .........##........ #.................# Output 1 8 -----Note----- The picture below shows the three possible locations of the ship that contain the cell $(3, 2)$ in the first sample. [Image]
n, k = list(map(int, input().split())) m = [list(input()) for _ in range(n)] p = [[0 for _ in range(n)] for _ in range(n)] for i in range(n): for j in range(n): s = True if i + k - 1 < n: for l in range(k): if m[i + l][j] != '.': s = False break if s: for l in range(k): p[i + l][j] += 1 s = True if j + k - 1 < n: for l in range(k): if m[i][j + l] != '.': s = False break if s: for l in range(k): p[i][j + l] += 1 mx = -1 for i in range(n): for j in range(n): if p[i][j] > mx: ans = (i + 1, j + 1) mx = p[i][j] print(*ans)
python
test
qsol
codeparrot/apps
all
I found an interesting problem on https://codeforces.com/problemset/problem/1368/D: Gottfried learned about binary number representation. He then came up with this task and presented it to you. You are given a collection of $n$ non-negative integers $a_1, \ldots, a_n$. You are allowed to perform the following operation: choose two distinct indices $1 \leq i, j \leq n$. If before the operation $a_i = x$, $a_j = y$, then after the operation $a_i = x~\mathsf{AND}~y$, $a_j = x~\mathsf{OR}~y$, where $\mathsf{AND}$ and $\mathsf{OR}$ are bitwise AND and OR respectively (refer to the Notes section for formal description). The operation may be performed any number of times (possibly zero). After all operations are done, compute $\sum_{i=1}^n a_i^2$ — the sum of squares of all $a_i$. What is the largest sum of squares you can achieve? -----Input----- The first line contains a single integer $n$ ($1 \leq n \leq 2 \cdot 10^5$). The second line contains $n$ integers $a_1, \ldots, a_n$ ($0 \leq a_i < 2^{20}$). -----Output----- Print a single integer — the largest possible sum of squares that can be achieved after several (possibly zero) operations. -----Examples----- Input 1 123 Output 15129 Input 3 1 3 5 Output 51 Input 2 349525 699050 Output 1099509530625 -----Note----- In the first sample no operation can be made, thus the answer is $123^2$. In the second sample we can obtain the collection $1, 1, 7$, and $1^2 + 1^2 + 7^2 = 51$. If $x$ and $y$ are represented in binary with equal number of bits (possibly with leading zeros), then each bit of $x~\mathsf{AND}~y$ is set to $1$ if and only if both corresponding bits of $x$ and $y$ are set to $1$. Similarly, each bit of $x~\mathsf{OR}~y$ is set to $1$ if and only if at least one of the corresponding bits of $x$ and $y$ are set to $1$. For example, $x = 3$ and $y = 5$ are represented as $011_2$ and $101_2$ (highest bit first). Then, $x~\mathsf{AND}~y = 001_2 = 1$, and $x~\mathsf{OR}~y = 111_2 = 7$. I tried it in Python, but could not do it. Can you solve it?
n=int(input()) a=list(map(int,input().split())) x=[0]*20 for i in range(n): s="{0:b}".format(a[i]) b=[] for j in range(len(s)): b.append(s[j]) b.reverse() for j in range(20-len(s)): b.append('0') b.reverse() for j in range(20): if b[j]=='1': x[j]+=1 ans=0 for i in range(n): s=[] for j in range(20): if x[j]>0: s.append('1') x[j]-=1 else: s.append('0') ans+=int(''.join(s), 2)**2 print(ans)
python
test
abovesol
codeparrot/apps
all
Solve in Python: You went shopping to buy cakes and donuts with X yen (the currency of Japan). First, you bought one cake for A yen at a cake shop. Then, you bought as many donuts as possible for B yen each, at a donut shop. How much do you have left after shopping? -----Constraints----- - 1 \leq A, B \leq 1 000 - A + B \leq X \leq 10 000 - X, A and B are integers. -----Input----- Input is given from Standard Input in the following format: X A B -----Output----- Print the amount you have left after shopping. -----Sample Input----- 1234 150 100 -----Sample Output----- 84 You have 1234 - 150 = 1084 yen left after buying a cake. With this amount, you can buy 10 donuts, after which you have 84 yen left.
X = int(input()) A = int(input()) B = int(input()) print((X - A) % B)
python
test
qsol
codeparrot/apps
all
I found an interesting problem on https://codeforces.com/problemset/problem/1030/E: Vasya has a sequence $a$ consisting of $n$ integers $a_1, a_2, \dots, a_n$. Vasya may pefrom the following operation: choose some number from the sequence and swap any pair of bits in its binary representation. For example, Vasya can transform number $6$ $(\dots 00000000110_2)$ into $3$ $(\dots 00000000011_2)$, $12$ $(\dots 000000001100_2)$, $1026$ $(\dots 10000000010_2)$ and many others. Vasya can use this operation any (possibly zero) number of times on any number from the sequence. Vasya names a sequence as good one, if, using operation mentioned above, he can obtain the sequence with bitwise exclusive or of all elements equal to $0$. For the given sequence $a_1, a_2, \ldots, a_n$ Vasya'd like to calculate number of integer pairs $(l, r)$ such that $1 \le l \le r \le n$ and sequence $a_l, a_{l + 1}, \dots, a_r$ is good. -----Input----- The first line contains a single integer $n$ ($1 \le n \le 3 \cdot 10^5$) — length of the sequence. The second line contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 10^{18}$) — the sequence $a$. -----Output----- Print one integer — the number of pairs $(l, r)$ such that $1 \le l \le r \le n$ and the sequence $a_l, a_{l + 1}, \dots, a_r$ is good. -----Examples----- Input 3 6 7 14 Output 2 Input 4 1 2 1 16 Output 4 -----Note----- In the first example pairs $(2, 3)$ and $(1, 3)$ are valid. Pair $(2, 3)$ is valid since $a_2 = 7 \rightarrow 11$, $a_3 = 14 \rightarrow 11$ and $11 \oplus 11 = 0$, where $\oplus$ — bitwise exclusive or. Pair $(1, 3)$ is valid since $a_1 = 6 \rightarrow 3$, $a_2 = 7 \rightarrow 13$, $a_3 = 14 \rightarrow 14$ and $3 \oplus 13 \oplus 14 = 0$. In the second example pairs $(1, 2)$, $(2, 3)$, $(3, 4)$ and $(1, 4)$ are valid. I tried it in Python, but could not do it. Can you solve it?
#!/usr/bin/env python3 import sys def rint(): return list(map(int, sys.stdin.readline().split())) #lines = stdin.readlines() def get_num1(i): cnt = 0 while i: if i%2: cnt +=1 i //=2 return cnt n = int(input()) a = list(rint()) b = [get_num1(aa) for aa in a] ans = 0 #S0[i] : 1 if sum of 1s in ragne (0, i) is odd, else 0 S0 = [0]*n S0[0] = b[0]%2 for i in range(1, n): S0[i] = (S0[i-1] + b[i])%2 #total even pairs in (0, n) even_cnt = S0.count(0) ans = even_cnt # check total even pairs in (i, n) for i in range(1, n): if b[i-1] %2: even_cnt = n - i - even_cnt else: even_cnt -= 1 ans += even_cnt for i in range(n): max_value = 0 sum_value = 0 for j in range(1, 62): if i + j > n: break sum_value += b[i+j-1] max_value = max(max_value, b[i+j-1]) if 2 * max_value > sum_value and sum_value%2 == 0: ans -= 1 print(ans)
python
test
abovesol
codeparrot/apps
all
Solve in Python: Nian is a monster which lives deep in the oceans. Once a year, it shows up on the land, devouring livestock and even people. In order to keep the monster away, people fill their villages with red colour, light, and cracking noise, all of which frighten the monster out of coming. Little Tommy has n lanterns and Big Banban has m lanterns. Tommy's lanterns have brightness a_1, a_2, ..., a_{n}, and Banban's have brightness b_1, b_2, ..., b_{m} respectively. Tommy intends to hide one of his lanterns, then Banban picks one of Tommy's non-hidden lanterns and one of his own lanterns to form a pair. The pair's brightness will be the product of the brightness of two lanterns. Tommy wants to make the product as small as possible, while Banban tries to make it as large as possible. You are asked to find the brightness of the chosen pair if both of them choose optimally. -----Input----- The first line contains two space-separated integers n and m (2 ≤ n, m ≤ 50). The second line contains n space-separated integers a_1, a_2, ..., a_{n}. The third line contains m space-separated integers b_1, b_2, ..., b_{m}. All the integers range from - 10^9 to 10^9. -----Output----- Print a single integer — the brightness of the chosen pair. -----Examples----- Input 2 2 20 18 2 14 Output 252 Input 5 3 -1 0 1 2 3 -1 0 1 Output 2 -----Note----- In the first example, Tommy will hide 20 and Banban will choose 18 from Tommy and 14 from himself. In the second example, Tommy will hide 3 and Banban will choose 2 from Tommy and 1 from himself.
n, m = map(int, input().split()) l1 = list(map(int, input().split())) l2 = list(map(int, input().split())) ans1 = [] for i in range(n): ans = -10 ** 18 - 1 for j in range(n): if j != i: for q in range(m): if ans < l1[j] * l2[q]: ans = l1[j] * l2[q] ans1.append(ans) print(min(ans1))
python
test
qsol
codeparrot/apps
all
Solve in Python: # Story&Task There are three parties in parliament. The "Conservative Party", the "Reformist Party", and a group of independants. You are a member of the “Conservative Party” and you party is trying to pass a bill. The “Reformist Party” is trying to block it. In order for a bill to pass, it must have a majority vote, meaning that more than half of all members must approve of a bill before it is passed . The "Conservatives" and "Reformists" always vote the same as other members of thier parties, meaning that all the members of each party will all vote yes, or all vote no . However, independants vote individually, and the independant vote is often the determining factor as to whether a bill gets passed or not. Your task is to find the minimum number of independents that have to vote for your party's (the Conservative Party's) bill so that it is passed . In each test case the makeup of the Parliament will be different . In some cases your party may make up the majority of parliament, and in others it may make up the minority. If your party is the majority, you may find that you do not neeed any independants to vote in favor of your bill in order for it to pass . If your party is the minority, it may be possible that there are not enough independants for your bill to be passed . If it is impossible for your bill to pass, return `-1`. # Input/Output - `[input]` integer `totalMembers` The total number of members. - `[input]` integer `conservativePartyMembers` The number of members in the Conservative Party. - `[input]` integer `reformistPartyMembers` The number of members in the Reformist Party. - `[output]` an integer The minimum number of independent members that have to vote as you wish so that the bill is passed, or `-1` if you can't pass it anyway. # Example For `n = 8, m = 3 and k = 3`, the output should be `2`. It means: ``` Conservative Party member --> 3 Reformist Party member --> 3 the independent members --> 8 - 3 - 3 = 2 If 2 independent members...
def pass_the_bill(par, con, ref): return -1 if ref >= (par / 2) else max(0, par // 2 + 1 - con)
python
train
qsol
codeparrot/apps
all
I found an interesting problem on https://www.codechef.com/ZCOPRAC/problems/ZCO12001: Zonal Computing Olympiad 2012, 26 Nov 2011 A sequence of opening and closing brackets is well-bracketed if we can pair up each opening bracket with a matching closing bracket in the usual sense. For instance, the sequences (), (()) and ()(()) are well-bracketed, while (, ()), (()(), and )( are not well-bracketed. The nesting depth of a well-bracketed sequence tells us the maximum number of levels of inner matched brackets enclosed within outer matched brackets. For instance, the nesting depth of () and ()()() is 1, the nesting depth of (()) and ()(()) is 2, the nesting depth of ((())) is 3, and so on. Given a well-bracketed sequence, we are interested in computing the following: - The nesting depth, and the first position where it occurs–this will be the position of the first opening bracket at this nesting depth, where the positions are numbered starting with 1. - The maximum number of symbols between any pair of matched brackets, including both the outer brackets, and the first position where this occurs–that is, the position of the first opening bracket of this segment For instance, the nesting depth of ()(())()(()())(()()) is 2 and the first position where this occurs is 4. The opening bracket at position 10 is also at nesting depth 2 but we have to report the first position where this occurs, which is 4. In this sequence, the maximum number of symbols between a pair of matched bracket is 6, starting at position 9. There is another such sequence of length 6 starting at position 15, but this is not the first such position. -----Input format----- The input consists of two lines. The first line is a single integer N, the length of the bracket sequence. Positions in the sequence are numbered 1,2,…,N. The second line is a sequence of N space-separated integers that encode the bracket expression as follows: 1 denotes an opening bracket ( and 2 denotes a closing bracket ). Nothing other than 1 or 2 appears in the second line of input and the corresponding expression is guaranteed to be... I tried it in Python, but could not do it. Can you solve it?
# cook your dish here import sys n=int(input().strip()) stringa=input().strip().split() stringa=''.join(stringa) counter=0 max_width=0 max_depth=0 for i in range(n): if stringa[i]=='1': if counter==0: start=i counter+=1 else: if counter>max_depth: max_depth=counter depth_idx=i counter-=1 if counter==0: end=i if end-start+1>max_width: max_width=end-start+1 start_idx=start+1 print(max_depth, depth_idx, max_width, start_idx)
python
train
abovesol
codeparrot/apps
all
Solve in Python: =====Problem Statement===== The itertools module standardizes a core set of fast, memory efficient tools that are useful by themselves or in combination. Together, they form an iterator algebra making it possible to construct specialized tools succinctly and efficiently in pure Python. You are given a list of N lowercase English letters. For a given integer K, you can select any K indices (assume 1-based indexing) with a uniform probability from the list. Find the probability that at least one of the K indices selected will contain the letter: ''. =====Input Format===== The input consists of three lines. The first line contains the integer N, denoting the length of the list. The next line consists of N space-separated lowercase English letters, denoting the elements of the list. The third and the last line of input contains the integer K, denoting the number of indices to be selected. =====Output Format===== Output a single line consisting of the probability that at least one of the K indices selected contains the letter: 'a'. Note: The answer must be correct up to 3 decimal places. =====Constraints===== 1≤N≤10 1≤K≤N
#!/usr/bin/env python3 import string symbols = string.ascii_lowercase from itertools import combinations def __starting_point(): n = int(input().strip()) arr = list(map(str, input().strip().split(' '))) times = int(input().strip()) cmbts = list(combinations(sorted(arr), times)) print(("{:.4f}".format(len(list([a for a in cmbts if a[0] == 'a']))/(len(cmbts))))) __starting_point()
python
train
qsol
codeparrot/apps
all
I found an interesting problem on https://www.codewars.com/kata/565b112d09c1adfdd500019c: Complete the function that takes an array of words. You must concatenate the `n`th letter from each word to construct a new word which should be returned as a string, where `n` is the position of the word in the list. For example: ``` ["yoda", "best", "has"] --> "yes" ^ ^ ^ n=0 n=1 n=2 ``` **Note:** Test cases contain valid input only - i.e. a string array or an empty array; and each word will have enough letters. I tried it in Python, but could not do it. Can you solve it?
def nth_char(w): return ''.join(w[i][i] for i in range(len(w)))
python
train
abovesol
codeparrot/apps
all
I found an interesting problem on https://www.codechef.com/problems/CLPNT: You may have helped Chef and prevented Doof from destroying the even numbers. But, it has only angered Dr Doof even further. However, for his next plan, he needs some time. Therefore, Doof has built $N$ walls to prevent Chef from interrupting him. You have to help Chef by telling him the number of walls he needs to destroy in order to reach Dr Doof. Formally, the whole area can be represented as the first quadrant with the origin at the bottom-left corner. Dr. Doof is located at the origin $(0, 0)$. There are $N$ walls, the i-th wall is a straight line segment joining the points $(a_i, 0)$ and $(0, a_i)$. For every initial position of Chef $(x_j, y_j)$, find the number of walls he needs to break before reaching Doof. Obviously, chef can't start from a point on the wall. Therefore, if $(x_j, y_j)$ lies on any of the given walls, print $-1$ in a new line. -----Input----- - First line contains $T$, denoting the number of testcases. - The first line of every test case contains a single integer $N$ denoting the number of walls Dr Doof has built. - The next line contains $N$ space separated distinct integers each denoting $a_i$. - The next line contains a single integer $Q$ denoting the number of times Chef asks for your help. - The next $Q$ lines contains two space separated integers $x_j$ and $y_j$, each denoting the co-ordinates of the starting point of Chef. -----Output----- For each query, print the number of walls Chef needs to break in order to reach Dr Doof in a separate line. If Chef tries to start from a point on any of the walls, print $-1$. -----Constraints----- - $1 \leq T \leq 2 * 10^2$ - $1 \leq N, Q \leq 2 * 10^5$ - $1 \leq a_i \leq 10^9$ - $0 \leq x_j, y_j \leq 10^9$ - $a_1 < a_2 < a_3 < .... < a_N$ - Sum of $N$ and $Q$ over all testcases for a particular test file does not exceed $2 * 10^5$ -----Sample Input----- 1 2 1 3 5 0 0 2 0 0 4 1 1 1 2 -----Sample Output----- 0 1 2 1 -1 -----Explanation----- The sample input can be represented by the graph given below: If Chef starts from $(0, 0)$,... I tried it in Python, but could not do it. Can you solve it?
import sys from sys import stdin,stdout from bisect import bisect_right from os import path #cin=sys.stdin.readline cout=sys.stdout.write if (path.exists('input.txt')): #------------------Sublime--------------------------------------# sys.stdin=open('input.txt','r');sys.stdout=open('output.txt','w'); def cinN():return (int(input())) def cin():return(map(int,input().split())) else: #------------------PYPY FAst I/o--------------------------------# def cinN():return (int(stdin.readline())) def cin():return(map(int,stdin.readline().split())) def find_le(a, x): 'Find rightmost value less than or equal to x' i = bisect_right(a, x) if i: return i-1 return -1 def func(): st='' n=cinN() l=list(cin()) l.sort() qn=cinN() for _ in range(qn): x,y=cin() k=x+y t=find_le(l,k) if t==-1: ans=(0) else: if l[t]==k: ans=(-1) else:ans=(t+1) print(ans) #cout(str(ans)) def __starting_point(): test=cinN() for _ in range(test):func() __starting_point()
python
train
abovesol
codeparrot/apps
all
I found an interesting problem on https://codeforces.com/problemset/problem/394/A: When new students come to the Specialized Educational and Scientific Centre (SESC) they need to start many things from the beginning. Sometimes the teachers say (not always unfairly) that we cannot even count. So our teachers decided to teach us arithmetics from the start. And what is the best way to teach students add and subtract? — That's right, using counting sticks! An here's our new task: An expression of counting sticks is an expression of type:[ A sticks][sign +][B sticks][sign =][C sticks] (1 ≤ A, B, C). Sign + consists of two crossed sticks: one vertical and one horizontal. Sign = consists of two horizontal sticks. The expression is arithmetically correct if A + B = C. We've got an expression that looks like A + B = C given by counting sticks. Our task is to shift at most one stick (or we can shift nothing) so that the expression became arithmetically correct. Note that we cannot remove the sticks from the expression, also we cannot shift the sticks from the signs + and =. We really aren't fabulous at arithmetics. Can you help us? -----Input----- The single line contains the initial expression. It is guaranteed that the expression looks like A + B = C, where 1 ≤ A, B, C ≤ 100. -----Output----- If there isn't a way to shift the stick so the expression becomes correct, print on a single line "Impossible" (without the quotes). If there is a way, print the resulting expression. Follow the format of the output from the test samples. Don't print extra space characters. If there are multiple correct answers, print any of them. For clarifications, you are recommended to see the test... I tried it in Python, but could not do it. Can you solve it?
import re s = input() l = re.compile('[|]+').findall(s) diff = len(l[0]) + len(l[1]) - len(l[2]) if diff == 0: print(s) elif diff == -2: print(l[0]+'|+' + l[1] + '=' + l[2][:-1]) elif diff == 2: l[2] += '|' if len(l[0]) == 1: l[1] = l[1][:-1] else: l[0] = l[0][:-1] print(l[0]+'+'+l[1]+'='+l[2]) else: print('Impossible')
python
test
abovesol
codeparrot/apps
all
I found an interesting problem on https://codeforces.com/problemset/problem/909/F: Given an integer N, find two permutations: Permutation p of numbers from 1 to N such that p_{i} ≠ i and p_{i} & i = 0 for all i = 1, 2, ..., N. Permutation q of numbers from 1 to N such that q_{i} ≠ i and q_{i} & i ≠ 0 for all i = 1, 2, ..., N. & is the bitwise AND operation. -----Input----- The input consists of one line containing a single integer N (1 ≤ N ≤ 10^5). -----Output----- For each subtask, if the required permutation doesn't exist, output a single line containing the word "NO"; otherwise output the word "YES" in the first line and N elements of the permutation, separated by spaces, in the second line. If there are several possible permutations in a subtask, output any of them. -----Examples----- Input 3 Output NO NO Input 6 Output YES 6 5 4 3 2 1 YES 3 6 2 5 1 4 I tried it in Python, but could not do it. Can you solve it?
from math import log2, floor n=int(input()) # n=100 if n%2: print('NO') else: print("YES") k=floor(log2(n))+1 res = [0 for i in range(n)] occupied = [0 for i in range(n)] switch = 0 for i in range(n,0,-1): val = 2**k-1-i if val > n: k-=1 val = 2**k-1-i if occupied[val-1]: while occupied[val-1]: k-=1 val = 2**k-1-i val = 2**k-1-i occupied[val-1] = 1 res[i-1] = val for i in res: print(i,end=' ') print() if n in [1,2,3,4,5]: print('NO') elif int(log2(n)) == log2(n): print('NO') elif n == 6: print('YES') print('3 6 2 5 1 4') else: print('YES') print('7 3 2 5 6 4 1',end=' ') for i in range(8,n): p = pow(2,floor(log2(i))+1) if i < pow(2,floor(log2(n))): print(p*3//2-1-i,end=' ') else: print(i+1,end=' ') if n > 7: print(pow(2,floor(log2(n))))
python
test
abovesol
codeparrot/apps
all
I found an interesting problem on https://www.codewars.com/kata/595ddfe2fc339d8a7d000089: # Introduction Hamsters are rodents belonging to the subfamily Cricetinae. The subfamily contains about 25 species, classified in six or seven genera. They have become established as popular small house pets, and, partly because they are easy to breed in captivity, hamsters are often used as laboratory animals. # Task Write a function that accepts two inputs: `code` and `message` and returns an encrypted string from `message` using the `code`. The `code` is a string that generates the key in the way shown below: ``` 1 | h a m s t e r 2 | i b n u f 3 | j c o v g 4 | k d p w 5 | l q x 6 | y 7 | z ``` All letters from `code` get number `1`. All letters which directly follow letters from `code` get number `2` (unless they already have a smaller number assigned), etc. It's difficult to describe but it should be easy to understand from the example below: ``` 1 | a e h m r s t 2 | b f i n u 3 | c g j o v 4 | d k p w 5 | l q x 6 | y 7 | z ``` How does the encoding work using the `hamster` code? ``` a => a1 b => a2 c => a3 d => a4 e => e1 f => e2 ... ``` And applying it to strings : ``` hamsterMe('hamster', 'hamster') => h1a1m1s1t1e1r1 hamsterMe('hamster', 'helpme') => h1e1h5m4m1e1 ``` And you probably started wondering what will happen if there is no `a` in the `code`. Just add these letters after the last available letter (in alphabetic order) in the `code`. The key for code `hmster` is: ``` 1 | e h m r s t 2 | f i n u 3 | g j o v 4 | k p w 5 | l q x 6 | y 7 | z 8 | a 9 | b 10 | c 11 | d ``` # Additional notes The `code` will have at least 1 letter. Duplication of letters in `code` is possible and should be handled. The `code` and `message` consist of only lowercase letters. I tried it in Python, but could not do it. Can you solve it?
from string import ascii_lowercase id = {c:i for i,c in enumerate(ascii_lowercase)} char = (ascii_lowercase+ascii_lowercase).__getitem__ def hamster_me(code, message): res, L = {}, sorted(map(id.get, code)) for i,j in zip(L, L[1:]+[26+L[0]]): start = char(i) for k,x in enumerate(map(char, range(i, j)), 1): res[x] = f"{start}{k}" return ''.join(map(res.get, message))
python
train
abovesol
codeparrot/apps
all
I found an interesting problem on https://www.codewars.com/kata/5600e00e42bcb7b9dc00014e: The image shows how we can obtain the Harmonic Conjugated Point of three aligned points A, B, C. - We choose any point L, that is not in the line with A, B and C. We form the triangle ABL - Then we draw a line from point C that intersects the sides of this triangle at points M and N respectively. - We draw the diagonals of the quadrilateral ABNM; they are AN and BM and they intersect at point K - We unit, with a line L and K, and this line intersects the line of points A, B and C at point D The point D is named the Conjugated Harmonic Point of the points A, B, C. You can get more knowledge related with this point at: (https://en.wikipedia.org/wiki/Projective_harmonic_conjugate) If we apply the theorems of Ceva (https://en.wikipedia.org/wiki/Ceva%27s_theorem) and Menelaus (https://en.wikipedia.org/wiki/Menelaus%27_theorem) we will have this formula: AC, in the above formula is the length of the segment of points A to C in this direction and its value is: ```AC = xA - xC``` Transform the above formula using the coordinates ```xA, xB, xC and xD``` The task is to create a function ```harmon_pointTrip()```, that receives three arguments, the coordinates of points xA, xB and xC, with values such that : ```xA < xB < xC```, this function should output the coordinates of point D for each given triplet, such that `xA < xD < xB < xC`, or to be clearer let's see some cases: ```python harmon_pointTrip(xA, xB, xC) ------> xD # the result should be expressed up to four decimals (rounded result) harmon_pointTrip(2, 10, 20) -----> 7.1429 # (2 < 7.1429 < 10 < 20, satisfies the constraint) harmon_pointTrip(3, 9, 18) -----> 6.75 ``` Enjoy it and happy coding!! I tried it in Python, but could not do it. Can you solve it?
def harmon_pointTrip(a, b, c): return round((a*c + b*c - 2*a*b) / (2*c - a - b), 4)
python
train
abovesol
codeparrot/apps
all
Solve in Python: Mohit's girlfriend is playing a game with Nicky. The description of the game is as follows: - Initially on a table Player 1 will put N gem-stones. - Players will play alternatively, turn by turn. - At each move a player can take at most M gem-stones (at least 1 gem-stone must be taken) from the available gem-stones on the table.(Each gem-stone has same cost.) - Each players gem-stone are gathered in player's side. - The player that empties the table purchases food from it (using all his gem-stones; one gem-stone can buy one unit of food), and the other one puts all his gem-stones back on to the table. Again the game continues with the "loser" player starting. - The game continues until all the gem-stones are used to buy food. - The main objective of the game is to consume maximum units of food. Mohit's girlfriend is weak in mathematics and prediction so she asks help from Mohit, in return she shall kiss Mohit. Mohit task is to predict the maximum units of food her girlfriend can eat, if, she starts first. Being the best friend of Mohit, help him in predicting the answer. -----Input----- - Single line contains two space separated integers N and M. -----Output----- - The maximum units of food Mohit's girlfriend can eat. -----Constraints and Subtasks----- - 1 <= M <= N <= 100 Subtask 1: 10 points - 1 <= M <= N <= 5 Subtask 2: 20 points - 1 <= M <= N <= 10 Subtask 3: 30 points - 1 <= M <= N <= 50 Subtask 3: 40 points - Original Constraints. -----Example----- Input: 4 2 Output: 2
n,m = list(map(int,input().split())) l = [ [1], [1,2], [2,2,3], [1,2,3,4], [4,3,3,4,5] ] print(l[n-1][m-1])
python
train
qsol
codeparrot/apps
all