input
stringlengths
50
13.9k
output_program
stringlengths
5
655k
output_answer
stringlengths
5
655k
split
stringclasses
1 value
dataset
stringclasses
1 value
# Convert Improper Fraction to Mixed Number You will need to convert an [improper fraction](https://www.mathplacementreview.com/arithmetic/fractions.php#improper-fractions) to a [mixed number](https://www.mathplacementreview.com/arithmetic/fractions.php#mixed-number). For example: ```python get_mixed_num('18/11') # Should return '1 7/11' get_mixed_num('13/5') # Should return '2 3/5' get_mixed_num('75/10') # Should return '7 5/10' ``` NOTE: All fractions will be greater than 0.
def get_mixed_num(f): [a, b] = map(int, f.split('/')) return "{} {}/{}".format(a//b, a%b, b)
def get_mixed_num(f): [a, b] = map(int, f.split('/')) return "{} {}/{}".format(a//b, a%b, b)
train
APPS_structured
Make a program that filters a list of strings and returns a list with only your friends name in it. If a name has exactly 4 letters in it, you can be sure that it has to be a friend of yours! Otherwise, you can be sure he's not... Ex: Input = ["Ryan", "Kieran", "Jason", "Yous"], Output = ["Ryan", "Yous"] i.e. Note: keep the original order of the names in the output.
def friend(x): return [x for x in x if x is x and all([not not x, x[0:4][::-1] == x[-1:-5:-1], len(x) == 65536 ** 0.125])]
def friend(x): return [x for x in x if x is x and all([not not x, x[0:4][::-1] == x[-1:-5:-1], len(x) == 65536 ** 0.125])]
train
APPS_structured
My friend John likes to go to the cinema. He can choose between system A and system B. ``` System A : he buys a ticket (15 dollars) every time System B : he buys a card (500 dollars) and a first ticket for 0.90 times the ticket price, then for each additional ticket he pays 0.90 times the price paid for the previous ticket. ``` #Example: If John goes to the cinema 3 times: ``` System A : 15 * 3 = 45 System B : 500 + 15 * 0.90 + (15 * 0.90) * 0.90 + (15 * 0.90 * 0.90) * 0.90 ( = 536.5849999999999, no rounding for each ticket) ``` John wants to know how many times he must go to the cinema so that the *final result* of System B, when rounded *up* to the next dollar, will be cheaper than System A. The function `movie` has 3 parameters: `card` (price of the card), `ticket` (normal price of a ticket), `perc` (fraction of what he paid for the previous ticket) and returns the first `n` such that ``` ceil(price of System B) < price of System A. ``` More examples: ``` movie(500, 15, 0.9) should return 43 (with card the total price is 634, with tickets 645) movie(100, 10, 0.95) should return 24 (with card the total price is 235, with tickets 240) ```
import math def movie(card, ticket, perc): curr_card_price = card curr_ticket_price = 0 next_card_purchase = ticket * perc trips = 0 while math.ceil(curr_card_price) >= curr_ticket_price: curr_card_price += next_card_purchase curr_ticket_price += ticket trips += 1 next_card_purchase *= perc return trips
import math def movie(card, ticket, perc): curr_card_price = card curr_ticket_price = 0 next_card_purchase = ticket * perc trips = 0 while math.ceil(curr_card_price) >= curr_ticket_price: curr_card_price += next_card_purchase curr_ticket_price += ticket trips += 1 next_card_purchase *= perc return trips
train
APPS_structured
Tennis is a popular game. Consider a simplified view of a tennis game from directly above. The game will appear to be played on a 2 dimensional rectangle, where each player has his own court, a half of the rectangle. Consider the players and the ball to be points moving on this 2D plane. The ball can be assumed to always move with fixed velocity (speed and direction) when it is hit by a player. The ball changes its velocity when hit by the other player. And so on, the game continues. Chef also enjoys playing tennis, but in n+1$n + 1$ dimensions instead of just 3. From the perspective of the previously discussed overhead view, Chef's court is an n$n$-dimensional hyperrectangle which is axis-aligned with one corner at (0,0,0,…,0)$(0, 0, 0, \dots, 0)$ and the opposite corner at (l1,l2,l3,…,ln$(l_1, l_2, l_3, \dots, l_n$). The court of his opponent is the reflection of Chef's court across the n−1$n - 1$ dimensional surface with equation x1=0$x_1 = 0$. At time t=0$t=0$, Chef notices that the ball is at position (0,b2,…,bn)$(0, b_2, \dots, b_n)$ after being hit by his opponent. The velocity components of the ball in each of the n$n$ dimensions are also immediately known to Chef, the component in the ith$i^{th}$ dimension being vi$v_i$. The ball will continue to move with fixed velocity until it leaves Chef's court. The ball is said to leave Chef's court when it reaches a position strictly outside the bounds of Chef's court. Chef is currently at position (c1,c2,…,cn)$(c_1, c_2, \dots, c_n)$. To hit the ball back, Chef must intercept the ball before it leaves his court, which means at a certain time the ball's position and Chef's position must coincide. To achieve this, Chef is free to change his speed and direction at any time starting from time t=0$t=0$. However, Chef is lazy so he does not want to put in more effort than necessary. Chef wants to minimize the maximum speed that he needs to acquire at any point in time until he hits the ball. Find this minimum value of speed smin$s_{min}$. Note: If an object moves with fixed velocity →v$\vec{v}$ and is at position →x$\vec{x}$ at time 0$0$, its position at time t$t$ is given by →x+→v⋅t$\vec{x} + \vec{v} \cdot t$. -----Input----- - The first line contains t$t$, the number of test cases. t$t$ cases follow. - The first line of each test case contains n$n$, the number of dimensions. - The next line contains n$n$ integers l1,l2,…,ln$l_1, l_2, \dots, l_n$, the bounds of Chef's court. - The next line contains n$n$ integers b1,b2,…,bn$b_1, b_2, \dots, b_n$, the position of the ball at t=0$t=0$. - The next line contains n$n$ integers v1,v2,…,vn$v_1, v_2, \dots, v_n$, the velocity components of the ball. - The next line contains n$n$ integers, c1,c2,…,cn$c_1, c_2, \dots, c_n$, Chef's position at t=0$t=0$. -----Output----- - For each test case, output a single line containing the value of smin$s_{min}$. Your answer will be considered correct if the absolute error does not exceed 10−2$10^{-2}$. -----Constraints----- - 1≤t≤1500$1 \leq t \leq 1500$ - 2≤n≤50$2 \leq n \leq 50$ - 1≤li≤50$1 \leq l_i \leq 50$ - 0≤bi≤li$0 \leq b_i \leq l_i$ and b1=0$b_1 = 0$ - −10≤vi≤10$-10 \leq v_i \leq 10$ and v1>0$v_1 > 0$ - 0≤ci≤li$0 \leq c_i \leq l_i$ - It is guaranteed that the ball stays in the court for a non-zero amount of time. -----Sample Input----- 2 2 3 4 0 2 2 -2 2 2 3 10 10 10 0 0 0 1 1 1 5 5 5 -----Sample Output----- 2.0000 0.0000 -----Explanation----- Case 1: The court is 2-dimentional. The ball's trajectory is marked in red. For Chef it is optimal to move along the blue line at a constant speed of 2 until he meets the ball at the boundary. Case 2: The court is 3-dimensional and the ball is coming straight at Chef. So it is best for Chef to not move at all, thus smin=0$s_{min} = 0$.
eps=1e-8 t=int(input()) for ii in range(t): n=int(input()) l=[int(i) for i in input().split() ] b=[int(i) for i in input().split() ] v=[int(i) for i in input().split() ] c=[int(i) for i in input().split() ] greatest_time=l[0]/v[0] for i in range(1,n): if v[i]>0: greatest_time=min(greatest_time,(l[i]-b[i])/v[i]) elif v[i]<0: greatest_time=min(greatest_time,-b[i]/v[i]) p = sum((b[i] - c[i]) ** 2 for i in range(n)) q = sum(2 * (b[i] - c[i]) * v[i] for i in range(n)) r = sum(vi ** 2 for vi in v) func = lambda t: p/t/t + q/t + r #ternary search def ternsearch(): if b==c: return(0) lo,hi=0,greatest_time while hi-lo>eps: d=(hi-lo)/3 m1=lo+d m2=m1+d if func(m1)<=func(m2): hi=m2 else: lo=m1 #print(hi,lo) #print(func(lo)**(0.5)) return max(0,func(lo))**(0.5) ans=ternsearch() print('%.12f' % (ans,))
eps=1e-8 t=int(input()) for ii in range(t): n=int(input()) l=[int(i) for i in input().split() ] b=[int(i) for i in input().split() ] v=[int(i) for i in input().split() ] c=[int(i) for i in input().split() ] greatest_time=l[0]/v[0] for i in range(1,n): if v[i]>0: greatest_time=min(greatest_time,(l[i]-b[i])/v[i]) elif v[i]<0: greatest_time=min(greatest_time,-b[i]/v[i]) p = sum((b[i] - c[i]) ** 2 for i in range(n)) q = sum(2 * (b[i] - c[i]) * v[i] for i in range(n)) r = sum(vi ** 2 for vi in v) func = lambda t: p/t/t + q/t + r #ternary search def ternsearch(): if b==c: return(0) lo,hi=0,greatest_time while hi-lo>eps: d=(hi-lo)/3 m1=lo+d m2=m1+d if func(m1)<=func(m2): hi=m2 else: lo=m1 #print(hi,lo) #print(func(lo)**(0.5)) return max(0,func(lo))**(0.5) ans=ternsearch() print('%.12f' % (ans,))
train
APPS_structured
You are given a list of non-negative integers, a1, a2, ..., an, and a target, S. Now you have 2 symbols + and -. For each integer, you should choose one from + and - as its new symbol. Find out how many ways to assign symbols to make sum of integers equal to target S. Example 1: Input: nums is [1, 1, 1, 1, 1], S is 3. Output: 5 Explanation: -1+1+1+1+1 = 3 +1-1+1+1+1 = 3 +1+1-1+1+1 = 3 +1+1+1-1+1 = 3 +1+1+1+1-1 = 3 There are 5 ways to assign symbols to make the sum of nums be target 3. Note: The length of the given array is positive and will not exceed 20. The sum of elements in the given array will not exceed 1000. Your output answer is guaranteed to be fitted in a 32-bit integer.
class Solution: def findTargetSumWays(self, nums, S): """ :type nums: List[int] :type S: int :rtype: int """ if sum(nums)<S: return 0 if (S+sum(nums))%2==1: return 0 target = (S+sum(nums))//2 dp = [0]*(target+1) dp[0] = 1 for n in nums: i = target while(i>=n): dp[i] = dp[i] + dp[i-n] i = i-1 return dp[target]
class Solution: def findTargetSumWays(self, nums, S): """ :type nums: List[int] :type S: int :rtype: int """ if sum(nums)<S: return 0 if (S+sum(nums))%2==1: return 0 target = (S+sum(nums))//2 dp = [0]*(target+1) dp[0] = 1 for n in nums: i = target while(i>=n): dp[i] = dp[i] + dp[i-n] i = i-1 return dp[target]
train
APPS_structured
An AI has infected a text with a character!! This text is now **fully mutated** to this character. If the text or the character are empty, return an empty string. There will never be a case when both are empty as nothing is going on!! **Note:** The character is a string of length 1 or an empty string. # Example ```python text before = "abc" character = "z" text after = "zzz" ```
contamination=lambda t,c: c*len(t)
contamination=lambda t,c: c*len(t)
train
APPS_structured
Your task is to build a model^(1) which can predict y-coordinate. You can pass tests if predicted y-coordinates are inside error margin. You will receive train set which should be used to build a model. After you build a model tests will call function ```predict``` and pass x to it. Error is going to be calculated with RMSE. Side note: Points in test cases are from different polynomials (up to 5th degree). Easier version: Data mining #1 Blocked libraries: sklearn, pandas, tensorflow, numpy, scipy Explanation [1] A mining model is created by applying an algorithm to data, but it is more than an algorithm or a metadata container: it is a set of data, statistics, and patterns that can be applied to new data to generate predictions and make inferences about relationships.
def reduced_echelon_form(matrix): matrix = matrix[::] if not matrix: return lead = 0 row_count = len(matrix) column_count = len(matrix[0]) for r in range(row_count): if lead >= column_count: return matrix i = r while matrix[i][lead] == 0: i += 1 if i == row_count: i = r lead += 1 if column_count == lead: return matrix matrix[i], matrix[r] = matrix[r], matrix[i] lv = matrix[r][lead] matrix[r] = [mrx / float(lv) for mrx in matrix[r]] for i in range(row_count): if i != r: lv = matrix[i][lead] matrix[i] = [iv - lv * rv for rv, iv in zip(matrix[r], matrix[i])] lead += 1 return matrix class Poly: def __init__(self, k, coef, lambda_=[1]): vector = [(_[1], e)for e, _ in enumerate( zip(range(0, k+1), coef) )] # _[1]:coef self.poly = vector self.lambda_ = lambda_ def eval_poly(self, x): return sum(l* pe[0]*x**pe[1] for pe, l in zip(self.poly, self.lambda_)) def _to_string(self): s = "" for p, e in self.poly[::-1]: s += "{}{}x^{}" . format("+" if p>=0 else "", p, e) s = s.strip("+") return s class Datamining: def __init__(self, train_set): self.train = train_set self.copy = train_set[::] self._learn() def _mse(self, corr, pred): s = [(c - p) ** 2 for c, p in zip(corr, pred)] return sum(s) / len(s) def frange(self, start, end, step): while start < end: yield start start += step def _learn(self): from random import shuffle train_perc = 0.65 iterations = 18 best = set() deg = 0 lmbds = self.frange(0.7, 1.3, 0.1) degrees = range(2,6) for l in lmbds: for d in degrees: for iter in range(iterations): # make matrix # required deg+1 points m = [] tmp = [] for p in self.train[:deg+1+d]: x = p[0] y = p[1] tmp = [x**e for e in range(deg+1+d)] tmp.append(y) m.append(tmp) # reduced form mtx = reduced_echelon_form(m) coef = [r[-1] for r in mtx] shuffle(self.copy) ntrain = int(len(self.copy)*train_perc) train = self.copy[:ntrain] test = self.copy[ntrain:] poly = Poly(deg+d, coef, lambda_=[l for _ in range(deg+d)]) model = poly.eval_poly predicted = [model(p[0]) for p in test] correct = [p[1] for p in test] best.add( (self._mse(predicted, correct), poly) ) _, poly = min(best, key=lambda x: x[0]) self.model = poly.eval_poly def predict(self, x): return self.model(x)
def reduced_echelon_form(matrix): matrix = matrix[::] if not matrix: return lead = 0 row_count = len(matrix) column_count = len(matrix[0]) for r in range(row_count): if lead >= column_count: return matrix i = r while matrix[i][lead] == 0: i += 1 if i == row_count: i = r lead += 1 if column_count == lead: return matrix matrix[i], matrix[r] = matrix[r], matrix[i] lv = matrix[r][lead] matrix[r] = [mrx / float(lv) for mrx in matrix[r]] for i in range(row_count): if i != r: lv = matrix[i][lead] matrix[i] = [iv - lv * rv for rv, iv in zip(matrix[r], matrix[i])] lead += 1 return matrix class Poly: def __init__(self, k, coef, lambda_=[1]): vector = [(_[1], e)for e, _ in enumerate( zip(range(0, k+1), coef) )] # _[1]:coef self.poly = vector self.lambda_ = lambda_ def eval_poly(self, x): return sum(l* pe[0]*x**pe[1] for pe, l in zip(self.poly, self.lambda_)) def _to_string(self): s = "" for p, e in self.poly[::-1]: s += "{}{}x^{}" . format("+" if p>=0 else "", p, e) s = s.strip("+") return s class Datamining: def __init__(self, train_set): self.train = train_set self.copy = train_set[::] self._learn() def _mse(self, corr, pred): s = [(c - p) ** 2 for c, p in zip(corr, pred)] return sum(s) / len(s) def frange(self, start, end, step): while start < end: yield start start += step def _learn(self): from random import shuffle train_perc = 0.65 iterations = 18 best = set() deg = 0 lmbds = self.frange(0.7, 1.3, 0.1) degrees = range(2,6) for l in lmbds: for d in degrees: for iter in range(iterations): # make matrix # required deg+1 points m = [] tmp = [] for p in self.train[:deg+1+d]: x = p[0] y = p[1] tmp = [x**e for e in range(deg+1+d)] tmp.append(y) m.append(tmp) # reduced form mtx = reduced_echelon_form(m) coef = [r[-1] for r in mtx] shuffle(self.copy) ntrain = int(len(self.copy)*train_perc) train = self.copy[:ntrain] test = self.copy[ntrain:] poly = Poly(deg+d, coef, lambda_=[l for _ in range(deg+d)]) model = poly.eval_poly predicted = [model(p[0]) for p in test] correct = [p[1] for p in test] best.add( (self._mse(predicted, correct), poly) ) _, poly = min(best, key=lambda x: x[0]) self.model = poly.eval_poly def predict(self, x): return self.model(x)
train
APPS_structured
Chef had a sequence of positive integers with length $N + K$. He managed to calculate the arithmetic average of all elements of this sequence (let's denote it by $V$), but then, his little brother deleted $K$ elements from it. All deleted elements had the same value. Chef still knows the remaining $N$ elements — a sequence $A_1, A_2, \ldots, A_N$. Help him with restoring the original sequence by finding the value of the deleted elements or deciding that there is some mistake and the described scenario is impossible. Note that the if it is possible for the deleted elements to have the same value, then it can be proven that it is unique. Also note that this value must be a positive integer. -----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 three space-separated integers $N$, $K$ and $V$. - The second line contains $N$ space-separated integers $A_1, A_2, \ldots, A_N$. -----Output----- For each test case, print a single line containing one integer — the value of the deleted elements, or $-1$ if there is a mistake. -----Constraints----- - $1 \le T \le 100$ - $1 \le N, K \le 100$ - $1 \le V \le 10^5$ - $1 \le A_i \le 10^5$ for each valid $i$ -----Subtasks----- Subtask #1 (100 points): original constraints -----Example Input----- 3 3 3 4 2 7 3 3 1 4 7 6 5 3 3 4 2 8 3 -----Example Output----- 4 -1 -1
# cook your dish here for _ in range(int(input())): n,k,v=list(map(int,input().split())) a=list(map(int,input().split())) s=v*(n+k) s-=sum(a) l=s//k if l<1 or s%k!=0: print(-1) else: print(l)
# cook your dish here for _ in range(int(input())): n,k,v=list(map(int,input().split())) a=list(map(int,input().split())) s=v*(n+k) s-=sum(a) l=s//k if l<1 or s%k!=0: print(-1) else: print(l)
train
APPS_structured
John Doe started thinking about graphs. After some thought he decided that he wants to paint an undirected graph, containing exactly k cycles of length 3. A cycle of length 3 is an unordered group of three distinct graph vertices a, b and c, such that each pair of them is connected by a graph edge. John has been painting for long, but he has not been a success. Help him find such graph. Note that the number of vertices there shouldn't exceed 100, or else John will have problems painting it. -----Input----- A single line contains an integer k (1 ≤ k ≤ 10^5) — the number of cycles of length 3 in the required graph. -----Output----- In the first line print integer n (3 ≤ n ≤ 100) — the number of vertices in the found graph. In each of next n lines print n characters "0" and "1": the i-th character of the j-th line should equal "0", if vertices i and j do not have an edge between them, otherwise it should equal "1". Note that as the required graph is undirected, the i-th character of the j-th line must equal the j-th character of the i-th line. The graph shouldn't contain self-loops, so the i-th character of the i-th line must equal "0" for all i. -----Examples----- Input 1 Output 3 011 101 110 Input 10 Output 5 01111 10111 11011 11101 11110
n, k = 0, int(input()) p = [['0'] * 100 for i in range(100)] while k: for i in range(n): if i > k: break p[n][i] = p[i][n] = '1' k -= i n += 1 print(n) for i in range(n): print(''.join(p[i][:n]))
n, k = 0, int(input()) p = [['0'] * 100 for i in range(100)] while k: for i in range(n): if i > k: break p[n][i] = p[i][n] = '1' k -= i n += 1 print(n) for i in range(n): print(''.join(p[i][:n]))
train
APPS_structured
You are given a string s of length n. Does a tree with n vertices that satisfies the following conditions exist? - The vertices are numbered 1,2,..., n. - The edges are numbered 1,2,..., n-1, and Edge i connects Vertex u_i and v_i. - If the i-th character in s is 1, we can have a connected component of size i by removing one edge from the tree. - If the i-th character in s is 0, we cannot have a connected component of size i by removing any one edge from the tree. If such a tree exists, construct one such tree. -----Constraints----- - 2 \leq n \leq 10^5 - s is a string of length n consisting of 0 and 1. -----Input----- Input is given from Standard Input in the following format: s -----Output----- If a tree with n vertices that satisfies the conditions does not exist, print -1. If a tree with n vertices that satisfies the conditions exist, print n-1 lines. The i-th line should contain u_i and v_i with a space in between. If there are multiple trees that satisfy the conditions, any such tree will be accepted. -----Sample Input----- 1111 -----Sample Output----- -1 It is impossible to have a connected component of size n after removing one edge from a tree with n vertices.
#from collections import deque #from heapq import heapify, heappop, heappush #from bisect import insort, bisect_left #import sys #sys.setrecursionlimit(10**9) #from math import gcd #from decimal import Decimal #mod = 1000000007 #mod = 998244353 #N = int(input()) #N, K = map(int, input().split()) S = input() eda = [] flag = False N = len(S) if S[-1] == '1': flag = True if S[0] == '0': flag = True if S[-2] == '0': flag = True for k in range((N-1)//2): if S[k] != S[-k-2]: flag = True if S[k] == '1': eda.append(k+1) if N%2 == 0: if S[N//2 -1] == '1': eda.append(N//2) if flag: print((-1)) return ans = [] eda.reverse() before = eda.pop() while eda: after = eda.pop() for k in range(before, after): ans.append((k, after)) before = after ans.append((before, before+1)) for k in range(before+2, N+1): ans.append((before+1, k)) while ans: item = ans.pop() print((item[0], item[1])) #ans = 0 #for k in range(N): #print(ans) #print('Yes') #print('No')
#from collections import deque #from heapq import heapify, heappop, heappush #from bisect import insort, bisect_left #import sys #sys.setrecursionlimit(10**9) #from math import gcd #from decimal import Decimal #mod = 1000000007 #mod = 998244353 #N = int(input()) #N, K = map(int, input().split()) S = input() eda = [] flag = False N = len(S) if S[-1] == '1': flag = True if S[0] == '0': flag = True if S[-2] == '0': flag = True for k in range((N-1)//2): if S[k] != S[-k-2]: flag = True if S[k] == '1': eda.append(k+1) if N%2 == 0: if S[N//2 -1] == '1': eda.append(N//2) if flag: print((-1)) return ans = [] eda.reverse() before = eda.pop() while eda: after = eda.pop() for k in range(before, after): ans.append((k, after)) before = after ans.append((before, before+1)) for k in range(before+2, N+1): ans.append((before+1, k)) while ans: item = ans.pop() print((item[0], item[1])) #ans = 0 #for k in range(N): #print(ans) #print('Yes') #print('No')
train
APPS_structured
Given an integer array nums, return the sum of divisors of the integers in that array that have exactly four divisors. If there is no such integer in the array, return 0. Example 1: Input: nums = [21,4,7] Output: 32 Explanation: 21 has 4 divisors: 1, 3, 7, 21 4 has 3 divisors: 1, 2, 4 7 has 2 divisors: 1, 7 The answer is the sum of divisors of 21 only. Constraints: 1 <= nums.length <= 10^4 1 <= nums[i] <= 10^5
class Solution: def find_factors(self, n): factors = [] i = 1 j = n while True: if i*j == n: factors.append(i) if i == j: break factors.append(j) i += 1 j = n // i if i > j: break return factors def sumFourDivisors(self, nums: List[int]) -> int: d = 0 for i in nums: f = self.find_factors(i) if len(f)==4: d+=f[0]+f[1]+f[2]+f[3] return d
class Solution: def find_factors(self, n): factors = [] i = 1 j = n while True: if i*j == n: factors.append(i) if i == j: break factors.append(j) i += 1 j = n // i if i > j: break return factors def sumFourDivisors(self, nums: List[int]) -> int: d = 0 for i in nums: f = self.find_factors(i) if len(f)==4: d+=f[0]+f[1]+f[2]+f[3] return d
train
APPS_structured
Oh no! You have stumbled upon a mysterious signal consisting of beeps of various lengths, and it is of utmost importance that you find out the secret message hidden in the beeps. There are long and short beeps, the longer ones roughly three times as long as the shorter ones. Hmm... that sounds familiar. That's right: your job is to implement a decoder for the Morse alphabet. Rather than dealing with actual beeps, we will use a common string encoding of Morse. A long beep is represened by a dash (`-`) and a short beep by a dot (`.`). A series of long and short beeps make up a letter, and letters are separated by spaces (` `). Words are separated by double spaces. You should implement the International Morse Alphabet. You need to support letters a-z and digits 0-9 as follows: a .- h .... o --- u ..- 1 .---- 6 -.... b -... i .. p .--. v ...- 2 ..--- 7 --... c -.-. j .--- q --.- w .-- 3 ...-- 8 ---.. d -.. k -.- r .-. x -..- 4 ....- 9 ----. e . l .-.. s ... y -.-- 5 ..... 0 ----- f ..-. m -- t - z --.. g --. n -. ## Examples .... . .-.. .-.. --- .-- --- .-. .-.. -.. → "hello world" .---- ... - .- -. -.. ..--- -. -.. → "1st and 2nd" ```if:python A dictionnary `TOME` is preloaded for you, with the information above to convert morse code to letters. ``` ```if:javascrip An object `TOME` is preloaded for you, with the information above to convert morse code to letters. ``` ```if:ruby A Hashmap `$dict` is preloaded for you, with the information above to convert morse code to letters. ```
lm = ['.-', '-...', '-.-.', '-..', '.', '..-.', '--.', '....', '..', '.---', '-.-', '.-..', '--', '-.', '---', '.--.', '--.-', '.-.', '...', '-', '..-', '...-', '.--', '-..-', '-.--', '--..', '-----', '.----', '..---', '...--', '....-', '.....', '-....', '--...', '---..', '----.'] ll = "abcdefghijklmnopqrstuvwxyz0123456789" repldict = {'.-': 'a', '-...': 'b'} for i in range(2, len((ll))): repldict.update({lm[i]: ll[i]}) print(repldict) def decode(encoded): if encoded ==" " or encoded =="": return encoded words = encoded.split(" ") engwords = [] for word in words: engword = [] letters = word.split(" ") for letter in letters: engword.append(repldict.get(letter)) engword.append(" ") engwords.append("".join(engword)) r = "".join(engwords) return r[0:len(r)-1]
lm = ['.-', '-...', '-.-.', '-..', '.', '..-.', '--.', '....', '..', '.---', '-.-', '.-..', '--', '-.', '---', '.--.', '--.-', '.-.', '...', '-', '..-', '...-', '.--', '-..-', '-.--', '--..', '-----', '.----', '..---', '...--', '....-', '.....', '-....', '--...', '---..', '----.'] ll = "abcdefghijklmnopqrstuvwxyz0123456789" repldict = {'.-': 'a', '-...': 'b'} for i in range(2, len((ll))): repldict.update({lm[i]: ll[i]}) print(repldict) def decode(encoded): if encoded ==" " or encoded =="": return encoded words = encoded.split(" ") engwords = [] for word in words: engword = [] letters = word.split(" ") for letter in letters: engword.append(repldict.get(letter)) engword.append(" ") engwords.append("".join(engword)) r = "".join(engwords) return r[0:len(r)-1]
train
APPS_structured
Your task is to define a function that understands basic mathematical expressions and solves them. For example: ```python calculate("1 + 1") # => 2 calculate("18 + 4*6") # => 42 calculate("245 - 826") # => -581 calculate("09 + 000482") # => 491 calculate("8 / 4 + 6") # => 8 calculate("5 + 1 / 5") # => 5.2 calculate("1+2+3") # => 6 calculate("9 /3 + 12/ 6") # => 5 ``` Notes: - Input string will contain numbers (may be integers and floats) and arithmetic operations. - Input string may contain spaces, and all space characters should be ignored. - Operations that will be used: addition (+), subtraction (-), multiplication (*), and division (/) - Operations must be done in the order of operations: First multiplication and division, then addition and subtraction. - In this kata, input expression will not have negative numbers. (ex: "-4 + 5") - If output is an integer, return as integer. Else return as float. - If input string is empty, contains letters, has a wrong syntax, contains division by zero or is not a string, return False.
from re import sub def calculate(input): try: return eval(sub(r'([^\d])0+(\d)', r'\1\2', input)) except: return False
from re import sub def calculate(input): try: return eval(sub(r'([^\d])0+(\d)', r'\1\2', input)) except: return False
train
APPS_structured
You have $n$ barrels lined up in a row, numbered from left to right from one. Initially, the $i$-th barrel contains $a_i$ liters of water. You can pour water from one barrel to another. In one act of pouring, you can choose two different barrels $x$ and $y$ (the $x$-th barrel shouldn't be empty) and pour any possible amount of water from barrel $x$ to barrel $y$ (possibly, all water). You may assume that barrels have infinite capacity, so you can pour any amount of water in each of them. Calculate the maximum possible difference between the maximum and the minimum amount of water in the barrels, if you can pour water at most $k$ times. Some examples: if you have four barrels, each containing $5$ liters of water, and $k = 1$, you may pour $5$ liters from the second barrel into the fourth, so the amounts of water in the barrels are $[5, 0, 5, 10]$, and the difference between the maximum and the minimum is $10$; if all barrels are empty, you can't make any operation, so the difference between the maximum and the minimum amount is still $0$. -----Input----- The first line contains one integer $t$ ($1 \le t \le 1000$) — the number of test cases. The first line of each test case contains two integers $n$ and $k$ ($1 \le k < n \le 2 \cdot 10^5$) — the number of barrels and the number of pourings you can make. The second line contains $n$ integers $a_1, a_2, \dots, a_n$ ($0 \le a_i \le 10^{9}$), where $a_i$ is the initial amount of water the $i$-th barrel has. It's guaranteed that the total sum of $n$ over test cases doesn't exceed $2 \cdot 10^5$. -----Output----- For each test case, print the maximum possible difference between the maximum and the minimum amount of water in the barrels, if you can pour water at most $k$ times. -----Example----- Input 2 4 1 5 5 5 5 3 2 0 0 0 Output 10 0
import sys input = sys.stdin.readline t = int(input()) for i in range(t): n,k = map(int,input().split()) a = list(map(int,input().split())) a.sort() a.reverse() cum = [a[0]] for i in range(n-1): cum.append(cum[i]+a[i+1]) cum.append(cum[-1]) print(cum[k])
import sys input = sys.stdin.readline t = int(input()) for i in range(t): n,k = map(int,input().split()) a = list(map(int,input().split())) a.sort() a.reverse() cum = [a[0]] for i in range(n-1): cum.append(cum[i]+a[i+1]) cum.append(cum[-1]) print(cum[k])
train
APPS_structured
Given an unsorted integer array, find the smallest missing positive integer. Example 1: Input: [1,2,0] Output: 3 Example 2: Input: [3,4,-1,1] Output: 2 Example 3: Input: [7,8,9,11,12] Output: 1 Note: Your algorithm should run in O(n) time and uses constant extra space.
class Solution: def firstMissingPositive(self, nums): """ :type nums: List[int] :rtype: int """ n = len(nums) for i in range(n): while nums[i] > 0 and nums[i] <= n and nums[i] != i+1 and nums[i] != nums[nums[i]-1]: nums[nums[i] - 1], nums[i] = nums[i], nums[nums[i]-1] for i in range(n): if nums[i] != i + 1: return i + 1 return n + 1
class Solution: def firstMissingPositive(self, nums): """ :type nums: List[int] :rtype: int """ n = len(nums) for i in range(n): while nums[i] > 0 and nums[i] <= n and nums[i] != i+1 and nums[i] != nums[nums[i]-1]: nums[nums[i] - 1], nums[i] = nums[i], nums[nums[i]-1] for i in range(n): if nums[i] != i + 1: return i + 1 return n + 1
train
APPS_structured
In this Kata, you will be given a string and your task will be to return a list of ints detailing the count of uppercase letters, lowercase, numbers and special characters, as follows. ```Haskell Solve("*'&ABCDabcde12345") = [4,5,5,3]. --the order is: uppercase letters, lowercase, numbers and special characters. ``` More examples in the test cases. Good luck!
import re def solve(s): return [len(re.findall(i,s)) for i in ('[A-Z]','[a-z]','\d','[^a-zA-Z0-9]')]
import re def solve(s): return [len(re.findall(i,s)) for i in ('[A-Z]','[a-z]','\d','[^a-zA-Z0-9]')]
train
APPS_structured
=====Function Descriptions===== Calendar Module The calendar module allows you to output calendars and provides additional useful functions for them. class calendar.TextCalendar([firstweekday]) This class can be used to generate plain text calendars. Sample Code >>> import calendar >>> >>> print calendar.TextCalendar(firstweekday=6).formatyear(2015) 2015 January February March Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa 1 2 3 1 2 3 4 5 6 7 1 2 3 4 5 6 7 4 5 6 7 8 9 10 8 9 10 11 12 13 14 8 9 10 11 12 13 14 11 12 13 14 15 16 17 15 16 17 18 19 20 21 15 16 17 18 19 20 21 18 19 20 21 22 23 24 22 23 24 25 26 27 28 22 23 24 25 26 27 28 25 26 27 28 29 30 31 29 30 31 April May June Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa 1 2 3 4 1 2 1 2 3 4 5 6 5 6 7 8 9 10 11 3 4 5 6 7 8 9 7 8 9 10 11 12 13 12 13 14 15 16 17 18 10 11 12 13 14 15 16 14 15 16 17 18 19 20 19 20 21 22 23 24 25 17 18 19 20 21 22 23 21 22 23 24 25 26 27 26 27 28 29 30 24 25 26 27 28 29 30 28 29 30 31 July August September Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa 1 2 3 4 1 1 2 3 4 5 5 6 7 8 9 10 11 2 3 4 5 6 7 8 6 7 8 9 10 11 12 12 13 14 15 16 17 18 9 10 11 12 13 14 15 13 14 15 16 17 18 19 19 20 21 22 23 24 25 16 17 18 19 20 21 22 20 21 22 23 24 25 26 26 27 28 29 30 31 23 24 25 26 27 28 29 27 28 29 30 30 31 October November December Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa 1 2 3 1 2 3 4 5 6 7 1 2 3 4 5 4 5 6 7 8 9 10 8 9 10 11 12 13 14 6 7 8 9 10 11 12 11 12 13 14 15 16 17 15 16 17 18 19 20 21 13 14 15 16 17 18 19 18 19 20 21 22 23 24 22 23 24 25 26 27 28 20 21 22 23 24 25 26 25 26 27 28 29 30 31 29 30 27 28 29 30 31 =====Problem Statement===== You are given a date. Your task is to find what the day is on that date. =====Input Format===== A single line of input containing the space separated month, day and year, respectively, in MM DD YYYY format. =====Constraints===== 2000<year<3000 =====Output Format===== Output the correct day in capital letters.
import calendar def __starting_point(): date = list(map(int, input().strip().split(' '))) print(calendar.day_name[calendar.weekday(date[2], date[0], date[1])].upper()) __starting_point()
import calendar def __starting_point(): date = list(map(int, input().strip().split(' '))) print(calendar.day_name[calendar.weekday(date[2], date[0], date[1])].upper()) __starting_point()
train
APPS_structured
Part 2/3 of my kata series. [Part 1](http://www.codewars.com/kata/riemann-sums-i-left-side-rule) The description changes little in this second part. Here we simply want to improve our approximation of the integral by using trapezoids instead of rectangles. The left/right side rules have a serious bias and the trapezoidal rules averages those approximations! The same assumptions exist but are pasted here for convenience. - f will always take a single float argument - f will always be a "nice" function, don't worry about NaN - n will always be a natural number (0, N] - b > a - and n will be chosen appropriately given the length of [a, b] (as in I will not have step sizes smaller than machine epsilon) - *!!! round answers to the nearest hundredth!!!*
def riemann_trapezoidal(f, n, a, b): dx = (b - a) / n return round(dx * sum(sum(f(a + (i+di)*dx) for di in (0, 1)) / 2 for i in range(n)), 2)
def riemann_trapezoidal(f, n, a, b): dx = (b - a) / n return round(dx * sum(sum(f(a + (i+di)*dx) for di in (0, 1)) / 2 for i in range(n)), 2)
train
APPS_structured
Wilson primes satisfy the following condition. Let ```P``` represent a prime number. Then ```((P-1)! + 1) / (P * P)``` should give a whole number. Your task is to create a function that returns ```true``` if the given number is a Wilson prime.
def am_i_wilson(n): L = [5,13,563] return n in L
def am_i_wilson(n): L = [5,13,563] return n in L
train
APPS_structured
Below is a right-angled triangle: ``` |\ | \ | \ | \ o | \ h | \ | θ \ |_______\ a ``` Your challange is to write a function (```missingAngle``` in C/C#, ```missing_angle``` in Ruby), that calculates the angle θ in degrees to the nearest integer. You will be given three arguments representing each side: o, h and a. One of the arguments equals zero. Use the length of the two other sides to calculate θ. You will not be expected to handle any erronous data in your solution.
import math def missing_angle(h, a, o): if h == 0: radians = math.atan(o/a) elif a == 0: radians = math.asin(o/h) else: radians = math.acos(a/h) return round(math.degrees(radians))
import math def missing_angle(h, a, o): if h == 0: radians = math.atan(o/a) elif a == 0: radians = math.asin(o/h) else: radians = math.acos(a/h) return round(math.degrees(radians))
train
APPS_structured
Chef loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. Chef has a positive integer N. He can apply any of the following operations as many times as he want in any order: - Add 1 to the number N. - Take some digit of N and replace it by any non-zero digit. - Add any non-zero leading digit to N. Find the minimum number of operations that is needed for changing N to the lucky number. -----Input----- The first line contains a single positive integer T, the number of test cases. T test cases follow. The only line of each test case contains a positive integer N without leading zeros. -----Output----- For each T test cases print one integer, the minimum number of operations that is needed for changing N to the lucky number. -----Constraints----- 1 ≤ T ≤ 10 1 ≤ N < 10100000 -----Example----- Input: 3 25 46 99 Output: 2 1 2
# cook your dish here t=int(input()) for _ in range(t): n=input().strip() cnt=0 for i in n: if i!='4' and i!='7': cnt+=1 print(cnt)
# cook your dish here t=int(input()) for _ in range(t): n=input().strip() cnt=0 for i in n: if i!='4' and i!='7': cnt+=1 print(cnt)
train
APPS_structured
## Task Given a positive integer as input, return the output as a string in the following format: Each element, corresponding to a digit of the number, multiplied by a power of 10 in such a way that with the sum of these elements you can obtain the original number. ## Examples Input | Output --- | --- 0 | "" 56 | "5\*10+6" 60 | "6\*10" 999 | "9\*100+9\*10+9" 10004 | "1\*10000+4" Note: `input >= 0`
def simplify(n): s = str(n) l = len(s) result = [] for i, d in enumerate(s, 1): if int(d): p = "" if l == i else f"*{10**(l-i)}" result.append(f"{d}{p}") return "+".join(result) # s = str(n) # return "+".join(f"{d}{f'*{10**(-i)}' if i else ''}" for i, d in enumerate(s, -len(s)+1) if int(d))
def simplify(n): s = str(n) l = len(s) result = [] for i, d in enumerate(s, 1): if int(d): p = "" if l == i else f"*{10**(l-i)}" result.append(f"{d}{p}") return "+".join(result) # s = str(n) # return "+".join(f"{d}{f'*{10**(-i)}' if i else ''}" for i, d in enumerate(s, -len(s)+1) if int(d))
train
APPS_structured
Given an integer num, find the closest two integers in absolute difference whose product equals num + 1 or num + 2. Return the two integers in any order. Example 1: Input: num = 8 Output: [3,3] Explanation: For num + 1 = 9, the closest divisors are 3 & 3, for num + 2 = 10, the closest divisors are 2 & 5, hence 3 & 3 is chosen. Example 2: Input: num = 123 Output: [5,25] Example 3: Input: num = 999 Output: [40,25] Constraints: 1 <= num <= 10^9
class Solution: def closestDivisors(self, num: int) -> List[int]: vals = [num + 1, num + 2] sqrt = int((num + 2) ** 0.5) for lo in itertools.count(sqrt, -1): for val in vals: if val % lo == 0: return lo, val // lo
class Solution: def closestDivisors(self, num: int) -> List[int]: vals = [num + 1, num + 2] sqrt = int((num + 2) ** 0.5) for lo in itertools.count(sqrt, -1): for val in vals: if val % lo == 0: return lo, val // lo
train
APPS_structured
=====Problem Statement===== You are given two sets, A and B. Your job is to find whether set A is a subset of set B. If set A is subset of set B, print True. If set A is not a subset of set B, print False. =====Input Format===== The first line will contain the number of test cases, T. The first line of each test case contains the number of elements in set A. The second line of each test case contains the space separated elements of set A. The third line of each test case contains the number of elements in set B. The fourth line of each test case contains the space separated elements of set B. =====Constraints===== 0<T<21 0<Number of elements in each set<1001 =====Output Format===== Output True or False for each test case on separate lines.
for i in range(int(input())): #More than 4 lines will result in 0 score. Blank lines won't be counted. a = int(input()); A = set(input().split()) b = int(input()); B = set(input().split()) print((len((A - B)) == 0))
for i in range(int(input())): #More than 4 lines will result in 0 score. Blank lines won't be counted. a = int(input()); A = set(input().split()) b = int(input()); B = set(input().split()) print((len((A - B)) == 0))
train
APPS_structured
Chef has provided with a sequence of integers of length $N$ arranged in an unsorted fashion. The elements of the sequence are ordered as ${A1,A2,A3.....A'N}$ The task of the chef is to identify the highest and lowest value among the given sequence. It is assured that the sequence given contains the highest and the lowest value always Please help chef in finding the desired value. -----Input:----- - First line will contain $N$, number of elements in the sequence. - Next line contains $N$ integers of the sequence . -----Output:----- Print the HIGHEST and LOWEST value of the sequence respectively. -----Constraints----- - $1 \leq N \leq 100$ - $2 \leq {A1,A2,A3.....A'N} \leq 10^4$ -----Sample Input:----- 5 3 2 7 9 4 -----Sample Output:----- 9 2 -----EXPLANATION:----- This list is : [3,2,7,9,4] so the highest value is 9 and lowest is 2 respectively.
# cook your dish here n=int(input()) arr=list(map(int,input().split()))[:n] print(max(arr),min(arr))
# cook your dish here n=int(input()) arr=list(map(int,input().split()))[:n] print(max(arr),min(arr))
train
APPS_structured
Given an array of positive integers nums, remove the smallest subarray (possibly empty) such that the sum of the remaining elements is divisible by p. It is not allowed to remove the whole array. Return the length of the smallest subarray that you need to remove, or -1 if it's impossible. A subarray is defined as a contiguous block of elements in the array. Example 1: Input: nums = [3,1,4,2], p = 6 Output: 1 Explanation: The sum of the elements in nums is 10, which is not divisible by 6. We can remove the subarray [4], and the sum of the remaining elements is 6, which is divisible by 6. Example 2: Input: nums = [6,3,5,2], p = 9 Output: 2 Explanation: We cannot remove a single element to get a sum divisible by 9. The best way is to remove the subarray [5,2], leaving us with [6,3] with sum 9. Example 3: Input: nums = [1,2,3], p = 3 Output: 0 Explanation: Here the sum is 6. which is already divisible by 3. Thus we do not need to remove anything. Example 4: Input: nums = [1,2,3], p = 7 Output: -1 Explanation: There is no way to remove a subarray in order to get a sum divisible by 7. Example 5: Input: nums = [1000000000,1000000000,1000000000], p = 3 Output: 0 Constraints: 1 <= nums.length <= 105 1 <= nums[i] <= 109 1 <= p <= 109
class Solution: def minSubarray(self, nums: List[int], p: int) -> int: if not nums: return 0 dic = {0:[-1]} if nums[0] % p not in dic: dic [nums[0] % p] = [] dic[nums[0] % p] = [0] nums[0] = nums[0] % p for i in range(1, len(nums)): nums[i] = (nums[i] + nums[i-1]) % p if nums[i] not in dic: dic[nums[i]] = [] dic[nums[i]].append(i) if nums[-1] == 0: return 0 output = len(nums) for i in range(len(nums)): res = (nums[i] - nums[-1]) % p try: output = min(output, min([i - j for j in dic[res] if j < i])) except: continue return output if output != len(nums) else -1
class Solution: def minSubarray(self, nums: List[int], p: int) -> int: if not nums: return 0 dic = {0:[-1]} if nums[0] % p not in dic: dic [nums[0] % p] = [] dic[nums[0] % p] = [0] nums[0] = nums[0] % p for i in range(1, len(nums)): nums[i] = (nums[i] + nums[i-1]) % p if nums[i] not in dic: dic[nums[i]] = [] dic[nums[i]].append(i) if nums[-1] == 0: return 0 output = len(nums) for i in range(len(nums)): res = (nums[i] - nums[-1]) % p try: output = min(output, min([i - j for j in dic[res] if j < i])) except: continue return output if output != len(nums) else -1
train
APPS_structured
Following from the previous kata and taking into account how cool psionic powers are compare to the Vance spell system (really, the idea of slots to dumb down the game sucks, not to mention that D&D became a smash hit among geeks, so...), your task in this kata is to create a function that returns how many power points you get as a psion [because psions are the coolest, they allow for a lot of indepth tactic playing and adjusting for psychic warriors or wilders or other non-core classes would be just an obnoxious core]. Consider both [the psion power points/days table](http://www.dandwiki.com/wiki/SRD:Psion#Making_a_Psion) and [bonus power points](http://www.d20pfsrd.com/psionics-unleashed/classes/#Table_Ability_Modifiers_and_Bonus_Power_Points) to figure out the correct reply, returned as an integer; the usual interpretation is that bonus power points stop increasing after level 20, but for the scope of this kata, we will pretend they keep increasing as they did before. To compute the total, you will be provided, both as non-negative integers: * class level (assume they are all psion levels and remember the base power points/day halts after level 20) * manifesting attribute score (Intelligence, to be more precise) to determine the total, provided the score is high enough for the character to manifest at least one power. Some examples: ```python psion_power_points(1,0) == 0 psion_power_points(1,10) == 0 psion_power_points(1,11) == 2 psion_power_points(1,20) == 4 psion_power_points(21,30) == 448 ``` *Note: I didn't explain things in detail and just pointed out to the table on purpose, as my goal is also to train the pattern recognition skills of whoever is going to take this challenges, so do not complain about a summary description. Thanks :)* In the same series: * [D&D Character generator #1: attribute modifiers and spells](https://www.codewars.com/kata/d-and-d-character-generator-number-1-attribute-modifiers-and-spells/) * [D&D Character generator #2: psion power points](https://www.codewars.com/kata/d-and-d-character-generator-number-2-psion-power-points/) * [D&D Character generator #3: carrying capacity](https://www.codewars.com/kata/d-and-d-character-generator-number-3-carrying-capacity/)
import math def psion_power_points(level,score): day = [ 0,2,6,11,17,25,35,46,58,72,88,106,126,147,170,195,221,250,280,311,343] return math.floor(level * (score//2-5) * 0.5) + ( day[level] if level <20 else 343) if score >10 else 0
import math def psion_power_points(level,score): day = [ 0,2,6,11,17,25,35,46,58,72,88,106,126,147,170,195,221,250,280,311,343] return math.floor(level * (score//2-5) * 0.5) + ( day[level] if level <20 else 343) if score >10 else 0
train
APPS_structured
A string of '0's and '1's is monotone increasing if it consists of some number of '0's (possibly 0), followed by some number of '1's (also possibly 0.) We are given a string S of '0's and '1's, and we may flip any '0' to a '1' or a '1' to a '0'. Return the minimum number of flips to make S monotone increasing. Example 1: Input: "00110" Output: 1 Explanation: We flip the last digit to get 00111. Example 2: Input: "010110" Output: 2 Explanation: We flip to get 011111, or alternatively 000111. Example 3: Input: "00011000" Output: 2 Explanation: We flip to get 00000000. Note: 1 <= S.length <= 20000 S only consists of '0' and '1' characters.
class Solution: def minFlipsMonoIncr(self, S: str) -> int: n, prefix, total, res = len(S), 0, S.count('1'), sys.maxsize for i in range(n + 1): res = min(res, prefix + len(S) - i - total + prefix) if i < n: prefix += 1 if S[i] == '1' else 0 return res
class Solution: def minFlipsMonoIncr(self, S: str) -> int: n, prefix, total, res = len(S), 0, S.count('1'), sys.maxsize for i in range(n + 1): res = min(res, prefix + len(S) - i - total + prefix) if i < n: prefix += 1 if S[i] == '1' else 0 return res
train
APPS_structured
# Task John loves encryption. He can encrypt any string by the following algorithm: ``` take the first and the last letters of the word; replace the letters between them with their number; replace this number with the sum of it digits until a single digit is obtained.``` Given two strings(`s1` and `s2`), return `true` if their encryption is the same, or `false` otherwise. # Example For `s1 = "EbnhGfjklmjhgz" and s2 = "Eabcz"`, the result should be `true`. ``` "EbnhGfjklmjhgz" --> "E12z" --> "E3z" "Eabcz" --> "E3z" Their encryption is the same.``` # Input/Output - `[input]` string `s1` The first string to be encrypted. `s1.length >= 3` - `[input]` string `s2` The second string to be encrypted. `s2.length >= 3` - `[output]` a boolean value `true` if encryption is the same, `false` otherwise.
from string import ascii_lowercase as alphabet def same_encryption(s1, s2): sum_s1 = len(s1[1:-1]) sum_s2 = len(s2[1:-1]) while len(str(sum_s1)) > 1: sum_s1 = sum(map(int, str(sum_s1))) while len(str(sum_s2)) > 1: sum_s2 = sum(map(int, str(sum_s2))) return '{}{}{}'.format(s1[0], sum_s1, s1[-1]) == '{}{}{}'.format(s2[0], sum_s2, s2[-1])
from string import ascii_lowercase as alphabet def same_encryption(s1, s2): sum_s1 = len(s1[1:-1]) sum_s2 = len(s2[1:-1]) while len(str(sum_s1)) > 1: sum_s1 = sum(map(int, str(sum_s1))) while len(str(sum_s2)) > 1: sum_s2 = sum(map(int, str(sum_s2))) return '{}{}{}'.format(s1[0], sum_s1, s1[-1]) == '{}{}{}'.format(s2[0], sum_s2, s2[-1])
train
APPS_structured
=====Function Descriptions===== collections.Counter() A counter is a container that stores elements as dictionary keys, and their counts are stored as dictionary values. Sample Code >>> from collections import Counter >>> >>> myList = [1,1,2,3,4,5,3,2,3,4,2,1,2,3] >>> print Counter(myList) Counter({2: 4, 3: 4, 1: 3, 4: 2, 5: 1}) >>> >>> print Counter(myList).items() [(1, 3), (2, 4), (3, 4), (4, 2), (5, 1)] >>> >>> print Counter(myList).keys() [1, 2, 3, 4, 5] >>> >>> print Counter(myList).values() [3, 4, 4, 2, 1] =====Problem Statement===== Raghu is a shoe shop owner. His shop has X number of shoes. He has a list containing the size of each shoe he has in his shop. There are N number of customers who are willing to pay x_i amount of money only if they get the shoe of their desired size. Your task is to compute how much money Raghu earned. =====Input Format===== The first line contains X, the number of shoes. The second line contains the space separated list of all the shoe sizes in the shop. The third line contains N, the number of customers. The next N lines contain the space separated values of the shoe size desired by the customer and x_i, the price of the shoe. =====Constraints===== 0<X<10^3 0<N≤10^3 0<x_i<100 2<shoe size<20 =====Output Format===== Print the amount of money earned by Raghu.
x = int(input()) shoe_size = list(map(int,input().split())) n = int(input()) sell = 0 for i in range(n): s, p = list(map(int,input().split())) if s in shoe_size: sell = sell + p shoe_size.remove(s) print(sell)
x = int(input()) shoe_size = list(map(int,input().split())) n = int(input()) sell = 0 for i in range(n): s, p = list(map(int,input().split())) if s in shoe_size: sell = sell + p shoe_size.remove(s) print(sell)
train
APPS_structured
KISS stands for Keep It Simple Stupid. It is a design principle for keeping things simple rather than complex. You are the boss of Joe. Joe is submitting words to you to publish to a blog. He likes to complicate things. Define a function that determines if Joe's work is simple or complex. Input will be non emtpy strings with no punctuation. It is simple if: ``` the length of each word does not exceed the amount of words in the string ``` (See example test cases) Otherwise it is complex. If complex: ```python return "Keep It Simple Stupid" ``` or if it was kept simple: ```python return "Good work Joe!" ``` Note: Random test are random and nonsensical. Here is a silly example of a random test: ```python "jump always mostly is touchy dancing choice is pineapples mostly" ```
def is_kiss(stg): words = stg.split() l = len(words) return "Good work Joe!" if all(len(word) <= l for word in words) else "Keep It Simple Stupid"
def is_kiss(stg): words = stg.split() l = len(words) return "Good work Joe!" if all(len(word) <= l for word in words) else "Keep It Simple Stupid"
train
APPS_structured
Poor Cade has got his number conversions mixed up again! Fix his ```convert_num()``` function so it correctly converts a base-10 ```int```eger, to the selected of ```bin```ary or ```hex```adecimal. ```#The output should be a string at all times``` ```python convert_num(number, base): if 'base' = hex: return int(number, 16) if 'base' = bin: return int(number, 2) return (Incorrect base input) ``` Please note, invalid ```number``` or ```base``` inputs will be tested. In the event of an invalid ```number/base``` you should return: ```python "Invalid number input" or "Invalid base input" ``` For each respectively. Good luck coding! :D
def convert_num(number, base): try: return {'hex': hex, 'bin': bin}[base](number) except KeyError: return 'Invalid base input' except TypeError: return 'Invalid {} input'.format( ('base', 'number')[isinstance(base, str)] )
def convert_num(number, base): try: return {'hex': hex, 'bin': bin}[base](number) except KeyError: return 'Invalid base input' except TypeError: return 'Invalid {} input'.format( ('base', 'number')[isinstance(base, str)] )
train
APPS_structured
You are given a permutation $p=[p_1, p_2, \ldots, p_n]$ of integers from $1$ to $n$. Let's call the number $m$ ($1 \le m \le n$) beautiful, if there exists two indices $l, r$ ($1 \le l \le r \le n$), such that the numbers $[p_l, p_{l+1}, \ldots, p_r]$ is a permutation of numbers $1, 2, \ldots, m$. For example, let $p = [4, 5, 1, 3, 2, 6]$. In this case, the numbers $1, 3, 5, 6$ are beautiful and $2, 4$ are not. It is because: if $l = 3$ and $r = 3$ we will have a permutation $[1]$ for $m = 1$; if $l = 3$ and $r = 5$ we will have a permutation $[1, 3, 2]$ for $m = 3$; if $l = 1$ and $r = 5$ we will have a permutation $[4, 5, 1, 3, 2]$ for $m = 5$; if $l = 1$ and $r = 6$ we will have a permutation $[4, 5, 1, 3, 2, 6]$ for $m = 6$; it is impossible to take some $l$ and $r$, such that $[p_l, p_{l+1}, \ldots, p_r]$ is a permutation of numbers $1, 2, \ldots, m$ for $m = 2$ and for $m = 4$. You are given a permutation $p=[p_1, p_2, \ldots, p_n]$. For all $m$ ($1 \le m \le n$) determine if it is a beautiful number or not. -----Input----- The first line contains the only integer $t$ ($1 \le t \le 1000$)  — the number of test cases in the input. The next lines contain the description of test cases. The first line of a test case contains a number $n$ ($1 \le n \le 2 \cdot 10^5$) — the length of the given permutation $p$. The next line contains $n$ integers $p_1, p_2, \ldots, p_n$ ($1 \le p_i \le n$, all $p_i$ are different) — the given permutation $p$. It is guaranteed, that the sum of $n$ from all test cases in the input doesn't exceed $2 \cdot 10^5$. -----Output----- Print $t$ lines — the answers to test cases in the order they are given in the input. The answer to a test case is the string of length $n$, there the $i$-th character is equal to $1$ if $i$ is a beautiful number and is equal to $0$ if $i$ is not a beautiful number. -----Example----- Input 3 6 4 5 1 3 2 6 5 5 3 1 2 4 4 1 4 3 2 Output 101011 11111 1001 -----Note----- The first test case is described in the problem statement. In the second test case all numbers from $1$ to $5$ are beautiful: if $l = 3$ and $r = 3$ we will have a permutation $[1]$ for $m = 1$; if $l = 3$ and $r = 4$ we will have a permutation $[1, 2]$ for $m = 2$; if $l = 2$ and $r = 4$ we will have a permutation $[3, 1, 2]$ for $m = 3$; if $l = 2$ and $r = 5$ we will have a permutation $[3, 1, 2, 4]$ for $m = 4$; if $l = 1$ and $r = 5$ we will have a permutation $[5, 3, 1, 2, 4]$ for $m = 5$.
for _ in range(int(input())): input() nums = [int(x) for x in input().split()] new_ar = list(zip(nums,[i for i in range(len(nums))])) new_ar.sort() maxx = new_ar[0][1] minn = new_ar[0][1] s="1" for j in range(1,len(new_ar)): if(new_ar[j][1]>maxx): maxx = new_ar[j][1] if(new_ar[j][1]<minn): minn = new_ar[j][1] if(maxx-minn<j+1): s+="1" else: s+="0" print(s)
for _ in range(int(input())): input() nums = [int(x) for x in input().split()] new_ar = list(zip(nums,[i for i in range(len(nums))])) new_ar.sort() maxx = new_ar[0][1] minn = new_ar[0][1] s="1" for j in range(1,len(new_ar)): if(new_ar[j][1]>maxx): maxx = new_ar[j][1] if(new_ar[j][1]<minn): minn = new_ar[j][1] if(maxx-minn<j+1): s+="1" else: s+="0" print(s)
train
APPS_structured
Chef and his girlfriend are going to have a promenade. They are walking along the straight road which consists of segments placed one by one. Before walking Chef and his girlfriend stay at the beginning of the first segment, they want to achieve the end of the last segment. There are few problems: - At the beginning Chef should choose constant integer - the velocity of mooving. It can't be changed inside one segment. - The velocity should be decreased by at least 1 after achieving the end of some segment. - There is exactly one shop on each segment. Each shop has an attractiveness. If it's attractiveness is W and Chef and his girlfriend move with velocity V then if V < W girlfriend will run away into the shop and the promenade will become ruined. Chef doesn't want to lose her girl in such a way, but he is an old one, so you should find the minimal possible velocity at the first segment to satisfy all conditions. -----Input----- - The first line of the input contains an 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 denoting the number of segments. The second line contains N space-separated integers W1, W2, ..., WN denoting the attractiveness of shops. -----Output----- - For each test case, output a single line containing the minimal possible velocity at the beginning. -----Constraints----- - 1 ≤ T ≤ 10 - 1 ≤ N ≤ 10^5 - 1 ≤ Wi ≤ 10^6 -----Example----- Input: 2 5 6 5 4 3 2 5 3 4 3 1 1 Output: 6 5 -----Explanation----- Example case 1. If we choose velocity 6, on the first step we have 6 >= 6 everything is OK, then we should decrease the velocity to 5 and on the 2nd segment we'll receive 5 >= 5, again OK, and so on. Example case 2. If we choose velocity 4, the promanade will be ruined on the 2nd step (we sould decrease our velocity, so the maximal possible will be 3 which is less than 4).
# cook your dish here for i in range(int(input())): n = int(input()) l = list(map(int,input().split())) l.reverse() c = 0 for i in range(n): if(c>=l[i]): pass else: c = l[i] c = c+1 print(c-1)
# cook your dish here for i in range(int(input())): n = int(input()) l = list(map(int,input().split())) l.reverse() c = 0 for i in range(n): if(c>=l[i]): pass else: c = l[i] c = c+1 print(c-1)
train
APPS_structured
So the Beautiful Regional Contest (BeRC) has come to an end! $n$ students took part in the contest. The final standings are already known: the participant in the $i$-th place solved $p_i$ problems. Since the participants are primarily sorted by the number of solved problems, then $p_1 \ge p_2 \ge \dots \ge p_n$. Help the jury distribute the gold, silver and bronze medals. Let their numbers be $g$, $s$ and $b$, respectively. Here is a list of requirements from the rules, which all must be satisfied: for each of the three types of medals, at least one medal must be awarded (that is, $g>0$, $s>0$ and $b>0$); the number of gold medals must be strictly less than the number of silver and the number of bronze (that is, $g<s$ and $g<b$, but there are no requirements between $s$ and $b$); each gold medalist must solve strictly more problems than any awarded with a silver medal; each silver medalist must solve strictly more problems than any awarded a bronze medal; each bronze medalist must solve strictly more problems than any participant not awarded a medal; the total number of medalists $g+s+b$ should not exceed half of all participants (for example, if $n=21$, then you can award a maximum of $10$ participants, and if $n=26$, then you can award a maximum of $13$ participants). The jury wants to reward with medals the total maximal number participants (i.e. to maximize $g+s+b$) so that all of the items listed above are fulfilled. Help the jury find such a way to award medals. -----Input----- The first line of the input contains an integer $t$ ($1 \le t \le 10000$) — the number of test cases in the input. Then $t$ test cases follow. The first line of a test case contains an integer $n$ ($1 \le n \le 4\cdot10^5$) — the number of BeRC participants. The second line of a test case contains integers $p_1, p_2, \dots, p_n$ ($0 \le p_i \le 10^6$), where $p_i$ is equal to the number of problems solved by the $i$-th participant from the final standings. The values $p_i$ are sorted in non-increasing order, i.e. $p_1 \ge p_2 \ge \dots \ge p_n$. The sum of $n$ over all test cases in the input does not exceed $4\cdot10^5$. -----Output----- Print $t$ lines, the $j$-th line should contain the answer to the $j$-th test case. The answer consists of three non-negative integers $g, s, b$. Print $g=s=b=0$ if there is no way to reward participants with medals so that all requirements from the statement are satisfied at the same time. Otherwise, print three positive numbers $g, s, b$ — the possible number of gold, silver and bronze medals, respectively. The sum of $g+s+b$ should be the maximum possible. If there are several answers, print any of them. -----Example----- Input 5 12 5 4 4 3 2 2 1 1 1 1 1 1 4 4 3 2 1 1 1000000 20 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 32 64 64 63 58 58 58 58 58 37 37 37 37 34 34 28 28 28 28 28 28 24 24 19 17 17 17 17 16 16 16 16 11 Output 1 2 3 0 0 0 0 0 0 2 5 3 2 6 6 -----Note----- In the first test case, it is possible to reward $1$ gold, $2$ silver and $3$ bronze medals. In this case, the participant solved $5$ tasks will be rewarded with the gold medal, participants solved $4$ tasks will be rewarded with silver medals, participants solved $2$ or $3$ tasks will be rewarded with bronze medals. Participants solved exactly $1$ task won't be rewarded. It's easy to see, that in this case, all conditions are satisfied and it is possible to reward participants in this way. It is impossible to give more than $6$ medals because the number of medals should not exceed half of the number of participants. The answer $1$, $3$, $2$ is also correct in this test case. In the second and third test cases, it is impossible to reward medals, because at least one medal of each type should be given, but the number of medals should not exceed half of the number of participants.
import sys input = sys.stdin.readline from collections import Counter t=int(input()) for testcases in range(t): n=int(input()) P=list(map(int,input().split())) C=Counter(P) PLIST=sorted(set(P),reverse=True) g=C[PLIST[0]] s=0 b=0 sflag=1 for i in PLIST[1:]: if sflag: if s<=g: s+=C[i] else: sflag=0 bflag=1 b+=C[i] elif bflag: if b<=g: b+=C[i] elif g+s+b+C[i]<=n//2: b+=C[i] else: break #print(i,g,s,b) if g+s+b<=n//2: print(g,s,b) else: print(0,0,0)
import sys input = sys.stdin.readline from collections import Counter t=int(input()) for testcases in range(t): n=int(input()) P=list(map(int,input().split())) C=Counter(P) PLIST=sorted(set(P),reverse=True) g=C[PLIST[0]] s=0 b=0 sflag=1 for i in PLIST[1:]: if sflag: if s<=g: s+=C[i] else: sflag=0 bflag=1 b+=C[i] elif bflag: if b<=g: b+=C[i] elif g+s+b+C[i]<=n//2: b+=C[i] else: break #print(i,g,s,b) if g+s+b<=n//2: print(g,s,b) else: print(0,0,0)
train
APPS_structured
A zero-indexed array A of length N contains all integers from 0 to N-1. Find and return the longest length of set S, where S[i] = {A[i], A[A[i]], A[A[A[i]]], ... } subjected to the rule below. Suppose the first element in S starts with the selection of element A[i] of index = i, the next element in S should be A[A[i]], and then A[A[A[i]]]… By that analogy, we stop adding right before a duplicate element occurs in S. Example 1: Input: A = [5,4,0,3,1,6,2] Output: 4 Explanation: A[0] = 5, A[1] = 4, A[2] = 0, A[3] = 3, A[4] = 1, A[5] = 6, A[6] = 2. One of the longest S[K]: S[0] = {A[0], A[5], A[6], A[2]} = {5, 6, 2, 0} Note: N is an integer within the range [1, 20,000]. The elements of A are all distinct. Each element of A is an integer within the range [0, N-1].
class Solution: def arrayNesting(self, nums): """ :type nums: List[int] :rtype: int """ maxLength = 0 for i in range(len(nums)): length = 0 j = i while nums[j] >= 0: length += 1 tmp = nums[j] nums[j] = -1 j = tmp maxLength = max(maxLength, length) return maxLength
class Solution: def arrayNesting(self, nums): """ :type nums: List[int] :rtype: int """ maxLength = 0 for i in range(len(nums)): length = 0 j = i while nums[j] >= 0: length += 1 tmp = nums[j] nums[j] = -1 j = tmp maxLength = max(maxLength, length) return maxLength
train
APPS_structured
From wikipedia In number theory and combinatorics, a partition of a positive integer n, also called an integer partition, is a way of writing n as a sum of positive integers. Two sums that differ only in the order of their summands are considered the **same** partition. For example, 4 can be partitioned in five distinct ways: `4, 3 + 1, 2 + 2, 2 + 1 + 1, 1 + 1 + 1 + 1`. We can write: `enum(4) -> [[4],[3,1],[2,2],[2,1,1],[1,1,1,1]]` and `enum(5) -> [[5],[4,1],[3,2],[3,1,1],[2,2,1],[2,1,1,1],[1,1,1,1,1]]`. The number of parts in a partition grows very fast. For n = 50 number of parts is `204226`, for 80 it is `15,796,476` It would be too long to tests answers with arrays of such size. So our task is the following: 1 - n being given (n integer, 1 <= n <= 50) calculate enum(n) ie the partition of n. We will obtain something like that: `enum(n) -> [[n],[n-1,1],[n-2,2],...,[1,1,...,1]]` (order of array and sub-arrays doesn't matter). This part is not tested. 2 - For each sub-array of enum(n) calculate its product. If n = 5 we'll obtain **after removing duplicates and sorting**: `prod(5) -> [1,2,3,4,5,6]` `prod(8) -> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 15, 16, 18]` If n = 40 prod(n) has a length of `2699` hence the tests will not verify such arrays. Instead our task number 3 is: 3 - return the range, the average and the median of prod(n) in the following form (example for n = 5): `"Range: 5 Average: 3.50 Median: 3.50"` Range is an integer, Average and Median are float numbers rounded to two decimal places (".2f" in some languages). #Notes: `Range` : difference between the highest and lowest values. `Mean or Average` : To calculate mean, add together all of the numbers in a set and then divide the sum by the total count of numbers. `Median` : The median is the number separating the higher half of a data sample from the lower half. (https://en.wikipedia.org/wiki/Median) #Hints: Try to optimize your program to avoid timing out. Memoization can be helpful but it is not mandatory for being successful.
from functools import reduce from statistics import median def partition(n, I=1): yield (n,) for i in range(I, n//2 + 1): for p in partition(n-i, i): yield (i,) + p def part(n): prod = set() all = partition(n) for i in all: prod.add(reduce(lambda a, b: a*b, i)) return("Range: {0} Average: {1:.2f} Median: {2:.2f}".format(max(prod) - min(prod), sum(prod)/len(prod), median(prod)))
from functools import reduce from statistics import median def partition(n, I=1): yield (n,) for i in range(I, n//2 + 1): for p in partition(n-i, i): yield (i,) + p def part(n): prod = set() all = partition(n) for i in all: prod.add(reduce(lambda a, b: a*b, i)) return("Range: {0} Average: {1:.2f} Median: {2:.2f}".format(max(prod) - min(prod), sum(prod)/len(prod), median(prod)))
train
APPS_structured
Shubham recently learned the lexicographical order in strings. Now, he has two strings s1 and s2 of the equal size and Shubham wants to compare those two strings lexicographically. Help Shubham with the strings comparison. Note: Letters are case insensitive. -----Input----- First line contains a integer T denoting the number of test cases. Each test case contains two strings of equal size in two separate lines. -----Output----- For each test case, If s1 < s2, print "first". If s1 > s2, print "second". If s1=s2, print "equal". in separate lines. -----Constraints----- - 1 ≤ T ≤ 10^2 - 1 ≤ Length of the string ≤ 500 -----Example----- Input: 2 abc acb AB ba Output: first first
import sys for __ in range(eval(input())) : a , b = input().lower() , input().lower() if a>b : print("second") elif a < b : print("first") else : print("equal")
import sys for __ in range(eval(input())) : a , b = input().lower() , input().lower() if a>b : print("second") elif a < b : print("first") else : print("equal")
train
APPS_structured
Create a function ```python has_two_cube_sums(n) ``` which checks if a given number `n` can be written as the sum of two cubes in two different ways: `n = a³+b³ = c³+d³`. All the numbers `a`, `b`, `c` and `d` should be different and greater than `0`. E.g. 1729 = 9³+10³ = 1³+12³. ```python has_two_cube_sums(1729); // true has_two_cube_sums(42); // false ```
def has_two_cube_sums(n): if n == 1: return False high = int((n)**(1/3.0)) low = int((n/2)**(1/3.0)) return sum( abs(y-round(y)) < 1e-8 for y in [((n-x**3))**(1/3.0) for x in range(low,high+1)]) >= 2
def has_two_cube_sums(n): if n == 1: return False high = int((n)**(1/3.0)) low = int((n/2)**(1/3.0)) return sum( abs(y-round(y)) < 1e-8 for y in [((n-x**3))**(1/3.0) for x in range(low,high+1)]) >= 2
train
APPS_structured
Sherlock has a new girlfriend (so unlike him!). Valentine's day is coming and he wants to gift her some jewelry. He bought n pieces of jewelry. The i-th piece has price equal to i + 1, that is, the prices of the jewelry are 2, 3, 4, ... n + 1. Watson gave Sherlock a challenge to color these jewelry pieces such that two pieces don't have the same color if the price of one piece is a prime divisor of the price of the other piece. Also, Watson asked him to minimize the number of different colors used. Help Sherlock complete this trivial task. -----Input----- The only line contains single integer n (1 ≤ n ≤ 100000) — the number of jewelry pieces. -----Output----- The first line of output should contain a single integer k, the minimum number of colors that can be used to color the pieces of jewelry with the given constraints. The next line should consist of n space-separated integers (between 1 and k) that specify the color of each piece in the order of increasing price. If there are multiple ways to color the pieces using k colors, you can output any of them. -----Examples----- Input 3 Output 2 1 1 2 Input 4 Output 2 2 1 1 2 -----Note----- In the first input, the colors for first, second and third pieces of jewelry having respective prices 2, 3 and 4 are 1, 1 and 2 respectively. In this case, as 2 is a prime divisor of 4, colors of jewelry having prices 2 and 4 must be distinct.
import sys def debug(x, table): for name, val in table.items(): if x is val: print('DEBUG:{} -> {}'.format(name, val), file=sys.stderr) return None def solve(): n = int(input()) if n <= 2: k = 1 ans = [1]*n print(k) print(*ans) else: k = 2 ans = color(n) print(k) print(*ans) def color(n): res = [1] * (n + 2) # 0, 1, 2, 3, ..., n + 1 for p in range(2, n + 2): if res[p] != 1: continue for q in range(p*p, n + 2, p): res[q] = 2 # debug(res, locals()) return res[2:] def __starting_point(): solve() __starting_point()
import sys def debug(x, table): for name, val in table.items(): if x is val: print('DEBUG:{} -> {}'.format(name, val), file=sys.stderr) return None def solve(): n = int(input()) if n <= 2: k = 1 ans = [1]*n print(k) print(*ans) else: k = 2 ans = color(n) print(k) print(*ans) def color(n): res = [1] * (n + 2) # 0, 1, 2, 3, ..., n + 1 for p in range(2, n + 2): if res[p] != 1: continue for q in range(p*p, n + 2, p): res[q] = 2 # debug(res, locals()) return res[2:] def __starting_point(): solve() __starting_point()
train
APPS_structured
# It's too hot, and they can't even… One hot summer day Pete and his friend Billy decided to buy watermelons. They chose the biggest crate. They rushed home, dying of thirst, and decided to divide their loot, however they faced a hard problem. Pete and Billy are great fans of even numbers, that's why they want to divide the number of watermelons in such a way that each of the two parts consists of an even number of watermelons. However, it is not obligatory that the parts are equal. Example: the boys can divide a stack of 8 watermelons into 2+6 melons, or 4+4 melons. The boys are extremely tired and want to start their meal as soon as possible, that's why you should help them and find out, whether they can divide the fruits in the way they want. For sure, each of them should get a part of positive weight. # Task Given an integral number of watermelons `w` (`1 ≤ w ≤ 100`; `1 ≤ w` in Haskell), check whether Pete and Billy can divide the melons so that each of them gets an even amount. ## Examples
def divide(weight): return len([i for i in range(1, weight + 1) if i % 2 == 0]) >= 2 and weight % 2 == 0
def divide(weight): return len([i for i in range(1, weight + 1) if i % 2 == 0]) >= 2 and weight % 2 == 0
train
APPS_structured
Chef loves triangles. But the chef is poor at maths. Given three random lengths Chef wants to find if the three sides form a right-angled triangle or not. Can you help Chef in this endeavour? -----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, three Integers $A,B and C$ -----Output:----- For each test case, output in a single line "YES" if it is possible to form a triangle using the given numbers or "NO" if it is not possible to form a triangle. -----Constraints----- - $1 \leq T \leq 1000000$ - $0 \leq A,B,C \leq 100$ -----Sample Input:----- 2 3 4 5 1 3 4 -----Sample Output:----- YES NO -----EXPLANATION:----- 3,4,5 forms a right-angled triangle. 1, 3 and 4 does not form a right-angled triangle.
#!/usr/bin/env python3 # coding: utf-8 #Last Modified: 23/Feb/20 12:23:37 PM import sys def main(): def checkValidity(a, b, c): if (a + b <= c) or (a + c <= b) or (b + c <= a) : return False else: return True def checkrt(a, b, c): if a**2 + b**2 == c**2 or a**2+c**2==b**2 or b**2+c**2==a**2: return True return False for tc in range(int(input())): a, b, c=get_ints() if checkValidity(a, b, c): if checkrt(a, b, c): print('YES') else: print('NO') else: print('NO') get_array = lambda: list(map(int, sys.stdin.readline().split())) get_ints = lambda: list(map(int, sys.stdin.readline().split())) input = lambda: sys.stdin.readline().strip() main()
#!/usr/bin/env python3 # coding: utf-8 #Last Modified: 23/Feb/20 12:23:37 PM import sys def main(): def checkValidity(a, b, c): if (a + b <= c) or (a + c <= b) or (b + c <= a) : return False else: return True def checkrt(a, b, c): if a**2 + b**2 == c**2 or a**2+c**2==b**2 or b**2+c**2==a**2: return True return False for tc in range(int(input())): a, b, c=get_ints() if checkValidity(a, b, c): if checkrt(a, b, c): print('YES') else: print('NO') else: print('NO') get_array = lambda: list(map(int, sys.stdin.readline().split())) get_ints = lambda: list(map(int, sys.stdin.readline().split())) input = lambda: sys.stdin.readline().strip() main()
train
APPS_structured
No description!!! Input :: [10,20,25,0] Output :: ["+0", "+10", "+15", "-10"] `Show some love, rank and upvote!`
def equalize(xs): return [f'{x-xs[0]:+d}' for x in xs]
def equalize(xs): return [f'{x-xs[0]:+d}' for x in xs]
train
APPS_structured
Return the largest possible k such that there exists a_1, a_2, ..., a_k such that: Each a_i is a non-empty string; Their concatenation a_1 + a_2 + ... + a_k is equal to text; For all 1 <= i <= k,  a_i = a_{k+1 - i}. Example 1: Input: text = "ghiabcdefhelloadamhelloabcdefghi" Output: 7 Explanation: We can split the string on "(ghi)(abcdef)(hello)(adam)(hello)(abcdef)(ghi)". Example 2: Input: text = "merchant" Output: 1 Explanation: We can split the string on "(merchant)". Example 3: Input: text = "antaprezatepzapreanta" Output: 11 Explanation: We can split the string on "(a)(nt)(a)(pre)(za)(tpe)(za)(pre)(a)(nt)(a)". Example 4: Input: text = "aaa" Output: 3 Explanation: We can split the string on "(a)(a)(a)". Constraints: text consists only of lowercase English characters. 1 <= text.length <= 1000
class Solution: def longestDecomposition(self, text: str) -> int: n = len(text) @lru_cache(None) def dp(left, right): if left > right: return 0 if left == right: return 1 maxk = 1 length = 1 #print(left, right) while(left + length <= right - length+1 ): #print(text[left:left+length],text[right-length+1:right+1]) if text[left:left+length] == text[right-length+1:right+1]: maxk = max(maxk, dp(left+length, right-length) + 2) length += 1 return maxk x = dp(0, n-1) return x
class Solution: def longestDecomposition(self, text: str) -> int: n = len(text) @lru_cache(None) def dp(left, right): if left > right: return 0 if left == right: return 1 maxk = 1 length = 1 #print(left, right) while(left + length <= right - length+1 ): #print(text[left:left+length],text[right-length+1:right+1]) if text[left:left+length] == text[right-length+1:right+1]: maxk = max(maxk, dp(left+length, right-length) + 2) length += 1 return maxk x = dp(0, n-1) return x
train
APPS_structured
Create a function that takes a string and returns that string with the first half lowercased and the last half uppercased. eg: foobar == fooBAR If it is an odd number then 'round' it up to find which letters to uppercase. See example below. sillycase("brian") // --^-- midpoint // bri first half (lower-cased) // AN second half (upper-cased)
import math def sillycase(silly): if len(silly) % 2 == 0: even_half = len(silly) // 2 return silly[:even_half].lower() + silly[even_half:].upper() else: odd_half = math.ceil(len(silly) / 2) return silly[:odd_half].lower() + silly[odd_half:].upper()
import math def sillycase(silly): if len(silly) % 2 == 0: even_half = len(silly) // 2 return silly[:even_half].lower() + silly[even_half:].upper() else: odd_half = math.ceil(len(silly) / 2) return silly[:odd_half].lower() + silly[odd_half:].upper()
train
APPS_structured
# Task Your task is to create a `Funnel` data structure. It consists of three basic methods: `fill()`, `drip()` and `toString()/to_s/__str__`. Its maximum capacity is 15 data. Data should be arranged in an inverted triangle, like this: ``` \1 2 3 4 5/ \7 8 9 0/ \4 5 6/ \2 3/ \1/ ``` The string method should return a multi-line string to display current funnel data arrangement: ```python funnel = Funnel() print(funnel) \ / \ / \ / \ / \ / ``` The method `fill()` should accept one or more arguments to fill in the funnel: ```python funnel = Funnel() funnel.fill(1) print (funnel) \ / \ / \ / \ / \1/ funnel.fill(2) print (funnel) \ / \ / \ / \2 / \1/ funnel.fill(3) print (funnel) \ / \ / \ / \2 3/ \1/ funnel.fill(4,5) print (funnel) \ / \ / \4 5 / \2 3/ \1/ funnel.fill(6,7,8,9) print(funnel) \ / \7 8 9 / \4 5 6/ \2 3/ \1/ ``` In each row, `fill()` always fill data from left to right. The method `drip()` should drip the bottom value out of funnel and returns this value: ```python (continue the example above) v = funnel.drip() print(v) 1 print(funnel) \ / \ 8 9 / \7 5 6/ \4 3/ \2/ ``` As you can see, the bottom 1 was dripping out. The number above it will fill it's place. The rules to fill are: Select one of the two numbers above it, which bear the "weight" of relatively large. In other words, there are more numbers on this number. Is this a bit hard to understand? Please see the following: ``` In the example above, before the execution of drip(), funnel is: \ / \7 8 9 / \4 5 6/ \2 3/ \1/ ``` * After drip(), 1 will be dripped out. * We should choose a number between 2 and 3 to fill the place of 1. * 2 has 5 numbers on it(4,5,7,8,9). 3 has 4 numbers on it(5,6,8,9) * So we choose 2 to fill the place of 1 * And now, the place of 2 is empty. * We also need choose a number between 4 and 5 to fill the place of 2. * 4 has 2 numbers on it(7,8). 5 has 2 numbers on it too(8,9) * There are same "weight" on 4 and 5, * In this case, we choose the number on the left * So we choose 4 to fill the place of 2 * And then choose 7 to fill the place of 4 Let us continue to `drip()`: ```python funnel.drip() print(funnel) \ / \ 9 / \7 8 6/ \5 3/ \4/ funnel.drip() print(funnel) \ / \ / \7 9 6/ \8 3/ \5/ funnel.drip() print(funnel) \ / \ / \ 9 6/ \7 3/ \8/ funnel.drip() print(funnel) \ / \ / \ 6/ \7 9/ \3/ funnel.drip() print(funnel) \ / \ / \ / \7 6/ \9/ funnel.drip() print(funnel) \ / \ / \ / \ 6/ \7/ funnel.drip() print(funnel) \ / \ / \ / \ / \6/ funnel.drip() print(funnel) \ / \ / \ / \ / \ / ``` When the funnel is empty, drip() will return `null/nil/None` Another edge case is: When funnel is full, fill() will not change the funnel. A bit complex...
class Funnel(): def __init__(self): self.funnel = [[" " for j in range(i+1)] for i in range(5)] self.data = 0 def fill(self, *args): for arg in args: if self.data<15: for indexi, i in enumerate(self.funnel): if " " in i: self.funnel[indexi][i.index(" ")] = str(arg) self.data += 1 break def count_weight_left(self,row, index): if self.funnel[row][index] != " ": if row <4: return 1 + self.count_weight_left(row+1, index) else: return 1 return 0 def count_weight_both(self, row, index): if self.funnel[row][index] != " ": if row < 4: return 1 + self.count_weight_left(row+1, index) + self.count_weight_both(row+1, index+1) else: return 1 return 0 def drip(self): if not self.data: return None self.data-= 1 value = int(self.funnel[0][0]) index = 0 for row in range(1,5): if self.count_weight_both(row ,index)>= self.count_weight_both(row, index + 1): self.funnel[row-1][index] = self.funnel[row][index] self.funnel[row][index] = " " else: self.funnel[row-1][index] = self.funnel[row][index+1] index += 1 self.funnel[row][index] = " " return value def __str__(self): string="" for index, i in enumerate(reversed(self.funnel)): string+= " "*index + "\\" + " ".join(i) + "/\n" return string[:-1]
class Funnel(): def __init__(self): self.funnel = [[" " for j in range(i+1)] for i in range(5)] self.data = 0 def fill(self, *args): for arg in args: if self.data<15: for indexi, i in enumerate(self.funnel): if " " in i: self.funnel[indexi][i.index(" ")] = str(arg) self.data += 1 break def count_weight_left(self,row, index): if self.funnel[row][index] != " ": if row <4: return 1 + self.count_weight_left(row+1, index) else: return 1 return 0 def count_weight_both(self, row, index): if self.funnel[row][index] != " ": if row < 4: return 1 + self.count_weight_left(row+1, index) + self.count_weight_both(row+1, index+1) else: return 1 return 0 def drip(self): if not self.data: return None self.data-= 1 value = int(self.funnel[0][0]) index = 0 for row in range(1,5): if self.count_weight_both(row ,index)>= self.count_weight_both(row, index + 1): self.funnel[row-1][index] = self.funnel[row][index] self.funnel[row][index] = " " else: self.funnel[row-1][index] = self.funnel[row][index+1] index += 1 self.funnel[row][index] = " " return value def __str__(self): string="" for index, i in enumerate(reversed(self.funnel)): string+= " "*index + "\\" + " ".join(i) + "/\n" return string[:-1]
train
APPS_structured
# Task Dudka has `n` details. He must keep exactly 3 of them. To do this, he performs the following operations until he has only 3 details left: ``` He numbers them. He keeps those with either odd or even numbers and throws the others away.``` Dudka wants to know how many ways there are to get exactly 3 details. Your task is to help him calculate it. # Example For `n = 6`, the output should be `2`. ``` Dudka has 6 details, numbered 1 2 3 4 5 6. He can keep either details with numbers 1, 3, 5, or with numbers 2, 4, 6. Both options leave him with 3 details, so the answer is 2.``` For `n = 7`, the output should be `1`. ``` Dudka has 7 details, numbered 1 2 3 4 5 6 7. He can keep either details 1 3 5 7, or details 2 4 6. If he keeps details 1 3 5 7 , he won't be able to get 3 details in the future, because at the next step he will number them 1 2 3 4 and will have to keep either details 1 3, or 2 4, only two details anyway. That's why he must keep details 2 4 6 at the first step, so the answer is 1.``` # Input/Output - `[input]` integer `n` `3 ≤ n ≤ 10^9` - `[output]` an integer The number of ways to get exactly 3 details.
ready = [0,0,0,1] def f(x): if x<len(ready): return ready[x] else: return f(x//2) + f(x//2 + x%2) for i in range(4,100001): ready.append(f(i)) def three_details(n): if n < 100000: return ready[n] else: return three_details(n//2) + three_details(n//2 +n%2)
ready = [0,0,0,1] def f(x): if x<len(ready): return ready[x] else: return f(x//2) + f(x//2 + x%2) for i in range(4,100001): ready.append(f(i)) def three_details(n): if n < 100000: return ready[n] else: return three_details(n//2) + three_details(n//2 +n%2)
train
APPS_structured
# Task "AL-AHLY" and "Zamalek" are the best teams in Egypt, but "AL-AHLY" always wins the matches between them. "Zamalek" managers want to know what is the best match they've played so far. The best match is the match they lost with the minimum goal difference. If there is more than one match with the same difference, choose the one "Zamalek" scored more goals in. Given the information about all matches they played, return the `index` of the best match (`0-based`). If more than one valid result, return the smallest index. # Example For `ALAHLYGoals = [6,4] and zamalekGoals = [1,2]`, the output should be 1. Because `4 - 2` is less than `6 - 1` For `ALAHLYGoals = [1,2,3,4,5] and zamalekGoals = [0,1,2,3,4]`, the output should be 4. The goal difference of all matches are 1, but at 4th match "Zamalek" scored more goals in. So the result is `4`. # Input/Output - `[input]` integer array `ALAHLYGoals` The number of goals "AL-AHLY" scored in each match. - `[input]` integer array `zamalekGoals` The number of goals "Zamalek" scored in each match. It is guaranteed that zamalekGoals[i] < ALAHLYGoals[i] for each element. - `[output]` an integer Index of the best match.
def best_match(goals1 : list, goals2 : list): # Set the current "best" values as the first match lowest_difference = goals1[0] - goals2[0] amount_of_goals = goals2[0] best_match_index = 0 # Loop through the length of the lists, to see if theres a better match for i in range(1, len(goals1)): # The current difference in goals. current_difference = goals1[i] - goals2[i] if (current_difference) < lowest_difference: # If the game was closer, this is the best match lowest_difference = current_difference amount_of_goals = goals2[i] best_match_index = i elif (current_difference == lowest_difference) and (amount_of_goals < goals2[i]): # If the difference is the same, but Zamalek scored more goals, it should change the best match. amount_of_goals = goals2[i] best_match_index = i return best_match_index
def best_match(goals1 : list, goals2 : list): # Set the current "best" values as the first match lowest_difference = goals1[0] - goals2[0] amount_of_goals = goals2[0] best_match_index = 0 # Loop through the length of the lists, to see if theres a better match for i in range(1, len(goals1)): # The current difference in goals. current_difference = goals1[i] - goals2[i] if (current_difference) < lowest_difference: # If the game was closer, this is the best match lowest_difference = current_difference amount_of_goals = goals2[i] best_match_index = i elif (current_difference == lowest_difference) and (amount_of_goals < goals2[i]): # If the difference is the same, but Zamalek scored more goals, it should change the best match. amount_of_goals = goals2[i] best_match_index = i return best_match_index
train
APPS_structured
Bohan loves milk tea so much and he drinks one cup of milk tea every day. The local shop sells milk tea in two sizes: a Medium cup for $3 and a Large cup for $4. For every cup of milk tea purchased Bohan receives a promotional stamp. Bohan may redeem 6 stamps for a free drink of milk tea regardless of the size. No stamp will be given for a free drink. Determine the amount of money Bohan have spent on milk tea, given a sequence of milk tea sizes he got in the past a few days. Assume Bohan had no stamps in the beginning and he always redeemed the stamps for the next drink once he had collected 6 stamps. -----Input----- The input begins with the number of test cases T. Each test case has a single line of letters. The i-th letter is either 'M' or 'L' denoting a Medium cup or a Large cup of milk tea Bohan got on the i-th day. -----Output----- For each case, output the amount of money in dollars Bohan have spent on milk tea. -----Constraints----- - T ≤ 100 - 1 ≤ length of each sequence ≤ 100 -----Example----- Input: 3 MLM MMLLMMLL MMMMMMML Output: 10 24 22 -----Explanation----- Example 1: Bohan didn't redeem any stamps. Example 2: Bohan redeemed 6 stamps for the Large cup of milk tea on the 7th day. Example 3: Bohan redeemed 6 stamps for the Medium cup of milk tea on the 7th day.
t=int(input()) while t>0: t-=1 s=input() val=0 ctr=0 for i in s: if ctr==6: ctr=0 else: if i=='M': val+=3 ctr+=1 else: val+=4 ctr+=1 print(val)
t=int(input()) while t>0: t-=1 s=input() val=0 ctr=0 for i in s: if ctr==6: ctr=0 else: if i=='M': val+=3 ctr+=1 else: val+=4 ctr+=1 print(val)
train
APPS_structured
Consider an array that has no prime numbers, and none of its elements has any prime digit. It would start with: `[1,4,6,8,9,10,14,16,18,..]`. `12` and `15` are not in the list because `2` and `5` are primes. You will be given an integer `n` and your task will be return the number at that index in the array. For example: ``` solve(0) = 1 solve(2) = 6 ``` More examples in the test cases. Good luck! If you like Prime Katas, you will enjoy this Kata: [Simple Prime Streaming](https://www.codewars.com/kata/5a908da30025e995880000e3)
from itertools import compress def sieve(n): n += 1 r = [False,True] * (n//2) + [True] r[1] = False r[2] = True for i in range(3,int(n**.5)+1,2): if r[i]: r[i*i::2*i] = [False] * ((n+2*i-1-i*i)//(2*i)) r = list(compress(range(len(r)),r)) if r[-1] %2 == 0: return r[:-1] return r primes = set(sieve(10**6)) res = [] factors = {'2','3','5','7'} for i in range(1,10**6): if i not in primes and set(str(i)).isdisjoint(factors): res.append(i) def solve(n): return res[n]
from itertools import compress def sieve(n): n += 1 r = [False,True] * (n//2) + [True] r[1] = False r[2] = True for i in range(3,int(n**.5)+1,2): if r[i]: r[i*i::2*i] = [False] * ((n+2*i-1-i*i)//(2*i)) r = list(compress(range(len(r)),r)) if r[-1] %2 == 0: return r[:-1] return r primes = set(sieve(10**6)) res = [] factors = {'2','3','5','7'} for i in range(1,10**6): if i not in primes and set(str(i)).isdisjoint(factors): res.append(i) def solve(n): return res[n]
train
APPS_structured
=====Function Descriptions===== Polar coordinates are an alternative way of representing Cartesian coordinates or Complex Numbers. A complex number z z = x + yj is completely determined by its real part y. Here, j is the imaginary unit. A polar coordinate (r, φ) is completely determined by modulus r and phase angle φ. If we convert complex number z to its polar coordinate, we find: r: Distance from z to origin, i.e., sqrt(x^2 + y^2) φ: Counter clockwise angle measured from the positive -axis to the line segment that joins z to the origin. Python's cmath module provides access to the mathematical functions for complex numbers. cmath.phase This tool returns the phase of complex number z (also known as the argument of z). >>> phase(complex(-1.0, 0.0)) 3.1415926535897931 abs This tool returns the modulus (absolute value) of complex number z. >>> abs(complex(-1.0, 0.0)) 1.0 =====Problem Statement===== You are given a complex z. Your task is to convert it to polar coordinates. =====Input Format===== A single line containing the complex number z. Note: complex() function can be used in python to convert the input as a complex number. =====Constraints===== Given number is a valid complex number =====Output Format===== Output two lines: The first line should contain the value of r. The second line should contain the value of φ.
#!/usr/bin/env python3 import cmath def __starting_point(): cnum = complex(input().strip()) print(abs(cnum)) print(cmath.phase(cnum)) __starting_point()
#!/usr/bin/env python3 import cmath def __starting_point(): cnum = complex(input().strip()) print(abs(cnum)) print(cmath.phase(cnum)) __starting_point()
train
APPS_structured
Write a function name `nextPerfectSquare` that returns the first perfect square that is greater than its integer argument. A `perfect square` is a integer that is equal to some integer squared. For example 16 is a perfect square because `16=4*4`. ``` example n next perfect sqare 6 9 36 49 0 1 -5 0 ``` ```if-not:csharp caution! the largest number tested is closer to `Number.MAX_SAFE_INTEGER` ``` ```if:csharp Caution! The largest number test is close to `Int64.MaxValue` ```
def next_perfect_square(n, i=0): while True: if i*i > n: return i*i i += 1
def next_perfect_square(n, i=0): while True: if i*i > n: return i*i i += 1
train
APPS_structured
In programming you know the use of the logical negation operator (**!**), it reverses the meaning of a condition. Your task is to complete the function 'negationValue()' that takes a string of negations with a value and returns what the value would be if those negations were applied to it. ```python negation_value("!", False) #=> True negation_value("!!!!!", True) #=> False negation_value("!!", []) #=> False ``` Do not use the `eval()` function or the `Function()` constructor in JavaScript. Note: Always return a boolean value, even if there're no negations.
def negation_value(s, val): if( len(s) % 2 ): return not val else: return not not val
def negation_value(s, val): if( len(s) % 2 ): return not val else: return not not val
train
APPS_structured
Ravi is very good student in mathematics and he also like Even numbers very much . On the other hand his friend Jhon like Odd numbers . Both of them are preparing for IIT JEE Advance .One day they are solving a question together the question was Find the sum of first $n$ terms of the given series $1^2+2.2^2+3^2+2.4^2+5^2+2.6^2+...........$ If the sum is odd then Jhon will be happy and will solve 2 more questions,and Ravi will not attempt more questions. If sum is even Ravi will be happy and will solve 2 more questions and Jhon will not attempt more questions. So Your task is to decide who will solve more questions. -----Input:----- - First line will contain $n$, number of terms in the given series. -----Output:----- Output single line "Ravi" if he solve more questions or "Jhon" if he solve more questions. -----Constraints----- - $1 \leq n \leq 100$ -----Sample Input:----- 2 3 -----Sample Output:----- Jhon Ravi -----EXPLANATION:----- In the first test cases sum of 2 terms is 9 (according to the given series) which is an odd number so Jhon will solve 2 more questions and Ravi will not attempt more questions. In second test case sum of 3 terms is 18 (according to the given series) which is an even number according to the given series so Ravi will solve 3 more questions and Jhon will not attempt more questions.
# cook your dish here while True: try: m=int(input()) n=int(m/2) a=m-n sum_even= int(2*(2*n*(n+1)*(2*n+1))/3) sum_odd= int(((4*a*a*a)-a)/3) result=sum_odd+sum_even if result%2==0: print('Ravi') else: print('Jhon') except: break;
# cook your dish here while True: try: m=int(input()) n=int(m/2) a=m-n sum_even= int(2*(2*n*(n+1)*(2*n+1))/3) sum_odd= int(((4*a*a*a)-a)/3) result=sum_odd+sum_even if result%2==0: print('Ravi') else: print('Jhon') except: break;
train
APPS_structured
Create the function ```consecutive(arr)``` that takes an array of integers and return the minimum number of integers needed to make the contents of ```arr``` consecutive from the lowest number to the highest number. For example: If ```arr``` contains [4, 8, 6] then the output should be 2 because two numbers need to be added to the array (5 and 7) to make it a consecutive array of numbers from 4 to 8. Numbers in ```arr``` will be unique.
def consecutive(arr): if len(arr) <= 1: return 0 return (max(arr) - min(arr) + 1) - len(arr)
def consecutive(arr): if len(arr) <= 1: return 0 return (max(arr) - min(arr) + 1) - len(arr)
train
APPS_structured
At the start of each season, every player in a football team is assigned their own unique squad number. Due to superstition or their history certain numbers are more desirable than others. Write a function generateNumber() that takes two arguments, an array of the current squad numbers (squad) and the new player's desired number (n). If the new player's desired number is not already taken, return n, else if the desired number can be formed by adding two digits between 1 and 9, return the number formed by joining these two digits together. E.g. If 2 is taken, return 11 because 1 + 1 = 2. Otherwise return null. Note: Often there will be several different ways to form a replacement number. In these cases the number with lowest first digit should be given priority. E.g. If n = 15, but squad already contains 15, return 69, not 78.
import itertools def twodigcombs(n): ls = [] digits = [1,2,3,4,5,6,7,8,9] for x, y in itertools.combinations_with_replacement(digits, 2): if x + y == n: ls.append([x,y]) return sorted(ls) def generate_number(squad, n): print((squad, n)) if n not in squad: return n for [a,b] in twodigcombs(n): x = a*10 + b if x not in squad: return x
import itertools def twodigcombs(n): ls = [] digits = [1,2,3,4,5,6,7,8,9] for x, y in itertools.combinations_with_replacement(digits, 2): if x + y == n: ls.append([x,y]) return sorted(ls) def generate_number(squad, n): print((squad, n)) if n not in squad: return n for [a,b] in twodigcombs(n): x = a*10 + b if x not in squad: return x
train
APPS_structured
You are given $n$ arrays that can have different sizes. You also have a table with $w$ columns and $n$ rows. The $i$-th array is placed horizontally in the $i$-th row. You can slide each array within its row as long as it occupies several consecutive cells and lies completely inside the table. You need to find the maximum sum of the integers in the $j$-th column for each $j$ from $1$ to $w$ independently. [Image] Optimal placements for columns $1$, $2$ and $3$ are shown on the pictures from left to right. Note that you can exclude any array out of a column provided it remains in the window. In this case its value is considered to be zero. -----Input----- The first line contains two integers $n$ ($1 \le n \le 10^{6}$) and $w$ ($1 \le w \le 10^{6}$) — the number of arrays and the width of the table. Each of the next $n$ lines consists of an integer $l_{i}$ ($1 \le l_{i} \le w$), the length of the $i$-th array, followed by $l_{i}$ integers $a_{i1}, a_{i2}, \ldots, a_{il_i}$ ($-10^{9} \le a_{ij} \le 10^{9}$) — the elements of the array. The total length of the arrays does no exceed $10^{6}$. -----Output----- Print $w$ integers, the $i$-th of them should be the maximum sum for column $i$. -----Examples----- Input 3 3 3 2 4 8 2 2 5 2 6 3 Output 10 15 16 Input 2 2 2 7 8 1 -8 Output 7 8 -----Note----- Illustration for the first example is in the statement.
import sys input = sys.stdin.readline from collections import deque def slidemax(X, k): q = deque([]) ret = [] for i in range(len(X)): while q and q[-1][1] <= X[i]: q.pop() deque.append(q, (i+k, X[i])) if q[0][0] == i: deque.popleft(q) if i >= k-1: ret.append(q[0][1]) return ret N, W = list(map(int, input().split())) A = [0] * W s = 0 for _ in range(N): l, *B = list(map(int, input().split())) if l*2 < W: C = slidemax([0]*(l-1)+B+[0]*(l-1), l) m = max(B + [0]) s += m for i in range(l-1): A[i] += C[i] - m A[-i-1] += C[-i-1] - m else: C = slidemax([0]*(W-l)+B+[0]*(W-l), W - l + 1) A = [a+c for a, c in zip(A, C)] print(*[a+s for a in A])
import sys input = sys.stdin.readline from collections import deque def slidemax(X, k): q = deque([]) ret = [] for i in range(len(X)): while q and q[-1][1] <= X[i]: q.pop() deque.append(q, (i+k, X[i])) if q[0][0] == i: deque.popleft(q) if i >= k-1: ret.append(q[0][1]) return ret N, W = list(map(int, input().split())) A = [0] * W s = 0 for _ in range(N): l, *B = list(map(int, input().split())) if l*2 < W: C = slidemax([0]*(l-1)+B+[0]*(l-1), l) m = max(B + [0]) s += m for i in range(l-1): A[i] += C[i] - m A[-i-1] += C[-i-1] - m else: C = slidemax([0]*(W-l)+B+[0]*(W-l), W - l + 1) A = [a+c for a, c in zip(A, C)] print(*[a+s for a in A])
train
APPS_structured
You are given an array A of size N. Let us list down all the subarrays of the given array. There will be a total of N * (N + 1) / 2 subarrays of the given array. Let us sort each of the subarrays in descending order of the numbers in it. Now you want to sort these subarrays in descending order. You can compare two subarrays B, C, as follows. compare(B, C): Append N - |B| zeros at the end of the array B. Append N - |C| zeros at the end of the array C. for i = 1 to N: if B[i] < C[i]: return B is less than C if B[i] > C[i]: return B is greater than C return B and C are equal. You are given M queries asking for the maximum element in the pth subarray (1-based indexing). -----Input----- The first line of input contains T, the number of test cases. The first line of each test case contains two space separated integers N and M, denoting the array size and the number of queries respectively. The next line contains N space-separated integers denoting the array elements. Each of the next M lines contains a single integer - p. -----Output----- Output a single integer corresponding to the maximum element in the pth subarray. -----Constraints----- - 1 ≤ Ai ≤ 109 - 1 ≤ p ≤ N+1C2 -----Subtasks-----Subtask #1 (20 points): - 1 ≤ T ≤ 20 - 1 ≤ N ≤ 200 - 1 ≤ M ≤ 104 Subtask #2 (30 points): - 1 ≤ T ≤ 20 - 1 ≤ N ≤ 3000 - 1 ≤ M ≤ 104 Subtask #3 (50 points): - 1 ≤ T ≤ 5 - 1 ≤ N ≤ 105 - 1 ≤ M ≤ 105 -----Example----- Input:1 4 2 3 1 2 4 1 5 Output:4 3
for _ in range(int(input())): N, M = map(int, input().split()) arr = list(map(int, input().split())) arr1 = sorted(arr, reverse=True) lst = [] for i in range(N): for j in range(i, N): x = arr[i:j+1] x.sort(reverse=True) x.extend([0]*(N-len(x))) lst.append(x) lst.sort(reverse=True) for j in range(M): p = int(input())-1 print(lst[p][0])
for _ in range(int(input())): N, M = map(int, input().split()) arr = list(map(int, input().split())) arr1 = sorted(arr, reverse=True) lst = [] for i in range(N): for j in range(i, N): x = arr[i:j+1] x.sort(reverse=True) x.extend([0]*(N-len(x))) lst.append(x) lst.sort(reverse=True) for j in range(M): p = int(input())-1 print(lst[p][0])
train
APPS_structured
There are N piles of stones arranged in a row.  The i-th pile has stones[i] stones. A move consists of merging exactly K consecutive piles into one pile, and the cost of this move is equal to the total number of stones in these K piles. Find the minimum cost to merge all piles of stones into one pile.  If it is impossible, return -1. Example 1: Input: stones = [3,2,4,1], K = 2 Output: 20 Explanation: We start with [3, 2, 4, 1]. We merge [3, 2] for a cost of 5, and we are left with [5, 4, 1]. We merge [4, 1] for a cost of 5, and we are left with [5, 5]. We merge [5, 5] for a cost of 10, and we are left with [10]. The total cost was 20, and this is the minimum possible. Example 2: Input: stones = [3,2,4,1], K = 3 Output: -1 Explanation: After any merge operation, there are 2 piles left, and we can't merge anymore. So the task is impossible. Example 3: Input: stones = [3,5,1,2,6], K = 3 Output: 25 Explanation: We start with [3, 5, 1, 2, 6]. We merge [5, 1, 2] for a cost of 8, and we are left with [3, 8, 6]. We merge [3, 8, 6] for a cost of 17, and we are left with [17]. The total cost was 25, and this is the minimum possible. Note: 1 <= stones.length <= 30 2 <= K <= 30 1 <= stones[i] <= 100
from functools import lru_cache import itertools class Solution: def mergeStones(self, stones: List[int], K: int) -> int: # dp[i][j] means the minimum cost needed to merge stones[i] ~ stones[j]. # Time complexity: O(N^3 / K) # Space complexity: O(KN^2) n = len(stones) if (n - 1) % (K - 1): return -1 prefix = [0] * (n + 1) for i in range(n): prefix[i + 1] = prefix[i] + stones[i] @lru_cache(None) def dp(i, j): if j - i + 1 < K: return 0 res = min(dp(i, mid) + dp(mid + 1, j) for mid in range(i, j, K - 1)) if (j - i) % (K - 1) == 0: res += prefix[j + 1] - prefix[i] return res return dp(0, n - 1)
from functools import lru_cache import itertools class Solution: def mergeStones(self, stones: List[int], K: int) -> int: # dp[i][j] means the minimum cost needed to merge stones[i] ~ stones[j]. # Time complexity: O(N^3 / K) # Space complexity: O(KN^2) n = len(stones) if (n - 1) % (K - 1): return -1 prefix = [0] * (n + 1) for i in range(n): prefix[i + 1] = prefix[i] + stones[i] @lru_cache(None) def dp(i, j): if j - i + 1 < K: return 0 res = min(dp(i, mid) + dp(mid + 1, j) for mid in range(i, j, K - 1)) if (j - i) % (K - 1) == 0: res += prefix[j + 1] - prefix[i] return res return dp(0, n - 1)
train
APPS_structured
You have an infinite number of stacks arranged in a row and numbered (left to right) from 0, each of the stacks has the same maximum capacity. Implement the DinnerPlates class: DinnerPlates(int capacity) Initializes the object with the maximum capacity of the stacks. void push(int val) Pushes the given positive integer val into the leftmost stack with size less than capacity. int pop() Returns the value at the top of the rightmost non-empty stack and removes it from that stack, and returns -1 if all stacks are empty. int popAtStack(int index) Returns the value at the top of the stack with the given index and removes it from that stack, and returns -1 if the stack with that given index is empty. Example: Input: ["DinnerPlates","push","push","push","push","push","popAtStack","push","push","popAtStack","popAtStack","pop","pop","pop","pop","pop"] [[2],[1],[2],[3],[4],[5],[0],[20],[21],[0],[2],[],[],[],[],[]] Output: [null,null,null,null,null,null,2,null,null,20,21,5,4,3,1,-1] Explanation: DinnerPlates D = DinnerPlates(2); // Initialize with capacity = 2 D.push(1); D.push(2); D.push(3); D.push(4); D.push(5); // The stacks are now: 2  4   1  3  5 ﹈ ﹈ ﹈ D.popAtStack(0); // Returns 2. The stacks are now:  4   1  3  5 ﹈ ﹈ ﹈ D.push(20); // The stacks are now: 20 4   1  3  5 ﹈ ﹈ ﹈ D.push(21); // The stacks are now: 20 4 21   1  3  5 ﹈ ﹈ ﹈ D.popAtStack(0); // Returns 20. The stacks are now: 4 21   1  3  5 ﹈ ﹈ ﹈ D.popAtStack(2); // Returns 21. The stacks are now: 4   1  3  5 ﹈ ﹈ ﹈ D.pop() // Returns 5. The stacks are now: 4   1  3 ﹈ ﹈ D.pop() // Returns 4. The stacks are now: 1  3 ﹈ ﹈ D.pop() // Returns 3. The stacks are now: 1 ﹈ D.pop() // Returns 1. There are no stacks. D.pop() // Returns -1. There are still no stacks. Constraints: 1 <= capacity <= 20000 1 <= val <= 20000 0 <= index <= 100000 At most 200000 calls will be made to push, pop, and popAtStack.
class DinnerPlates: def __init__(self, capacity: int): self.c = capacity self.s = [] self.q = [] def push(self, val: int) -> None: while self.q and (self.q[0] >= len(self.s) or len(self.s[self.q[0]]) == self.c): heapq.heappop(self.q) # print(self.q, self.s) if self.q: idx = self.q[0] self.s[idx].append(val) if len(self.s[idx]) == self.c: heapq.heappop(self.q) else: idx = len(self.s)-1 if not self.s or len(self.s[-1]) == self.c: idx += 1 self.s.append([]) self.s[idx].append(val) def pop(self) -> int: while self.s and not self.s[-1]: self.s.pop() return self.popAtStack(len(self.s) - 1) def popAtStack(self, index: int) -> int: # print(self.s) if 0 <= index < len(self.s) and self.s[index]: heapq.heappush(self.q, index) return self.s[index].pop() return -1 # Your DinnerPlates object will be instantiated and called as such: # obj = DinnerPlates(capacity) # obj.push(val) # param_2 = obj.pop() # param_3 = obj.popAtStack(index)
class DinnerPlates: def __init__(self, capacity: int): self.c = capacity self.s = [] self.q = [] def push(self, val: int) -> None: while self.q and (self.q[0] >= len(self.s) or len(self.s[self.q[0]]) == self.c): heapq.heappop(self.q) # print(self.q, self.s) if self.q: idx = self.q[0] self.s[idx].append(val) if len(self.s[idx]) == self.c: heapq.heappop(self.q) else: idx = len(self.s)-1 if not self.s or len(self.s[-1]) == self.c: idx += 1 self.s.append([]) self.s[idx].append(val) def pop(self) -> int: while self.s and not self.s[-1]: self.s.pop() return self.popAtStack(len(self.s) - 1) def popAtStack(self, index: int) -> int: # print(self.s) if 0 <= index < len(self.s) and self.s[index]: heapq.heappush(self.q, index) return self.s[index].pop() return -1 # Your DinnerPlates object will be instantiated and called as such: # obj = DinnerPlates(capacity) # obj.push(val) # param_2 = obj.pop() # param_3 = obj.popAtStack(index)
train
APPS_structured
# altERnaTIng cAsE <=> ALTerNAtiNG CaSe Define `String.prototype.toAlternatingCase` (or a similar function/method *such as* `to_alternating_case`/`toAlternatingCase`/`ToAlternatingCase` in your selected language; **see the initial solution for details**) such that each lowercase letter becomes uppercase and each uppercase letter becomes lowercase. For example: ``` haskell toAlternatingCase "hello world" `shouldBe` "HELLO WORLD" toAlternatingCase "HELLO WORLD" `shouldBe` "hello world" toAlternatingCase "hello WORLD" `shouldBe` "HELLO world" toAlternatingCase "HeLLo WoRLD" `shouldBe` "hEllO wOrld" toAlternatingCase "12345" `shouldBe` "12345" toAlternatingCase "1a2b3c4d5e" `shouldBe` "1A2B3C4D5E" ``` ```C++ string source = "HeLLo WoRLD"; string upperCase = to_alternating_case(source); cout << upperCase << endl; // outputs: hEllO wOrld ``` As usual, your function/method should be pure, i.e. it should **not** mutate the original string.
def to_alternating_case(string): for char in string: '''if char.isupper(): str_ += char.lower() elif char.islower(): str_ += char.upper() elif char == " ": str_ += " " elif string.isdigit(): return str(string) ''' a = string.swapcase() return a print(to_alternating_case("cIao"))
def to_alternating_case(string): for char in string: '''if char.isupper(): str_ += char.lower() elif char.islower(): str_ += char.upper() elif char == " ": str_ += " " elif string.isdigit(): return str(string) ''' a = string.swapcase() return a print(to_alternating_case("cIao"))
train
APPS_structured
Magic The Gathering is a collectible card game that features wizards battling against each other with spells and creature summons. The game itself can be quite complicated to learn. In this series of katas, we'll be solving some of the situations that arise during gameplay. You won't need any prior knowledge of the game to solve these contrived problems, as I will provide you with enough information. ## Creatures Each creature has a power and toughness. We will represent this in an array. [2, 3] means this creature has a power of 2 and a toughness of 3. When two creatures square off, they each deal damage equal to their power to each other at the same time. If a creature takes on damage greater than or equal to their toughness, they die. Examples: - Creature 1 - [2, 3] - Creature 2 - [3, 3] - Creature 3 - [1, 4] - Creature 4 - [4, 1] If creature 1 battles creature 2, creature 1 dies, while 2 survives. If creature 3 battles creature 4, they both die, as 3 deals 1 damage to 4, but creature 4 only has a toughness of 1. Write a function `battle(player1, player2)` that takes in 2 arrays of creatures. Each players' creatures battle each other in order (player1[0] battles the creature in player2[0]) and so on. If one list of creatures is longer than the other, those creatures are considered unblocked, and do not battle. Your function should return an object (a hash in Ruby) with the keys player1 and player2 that contain the power and toughness of the surviving creatures. Example: ``` Good luck with your battles! Check out my other Magic The Gathering katas: Magic The Gathering #1: Creatures Magic The Gathering #2: Mana
from itertools import zip_longest def battle(player1, player2): rem = {'player1': [], 'player2': []} for c1,c2 in zip_longest(player1, player2, fillvalue=[0,0]): if c1[1] > c2[0]: rem['player1'].append(c1) if c2[1] > c1[0]: rem['player2'].append(c2) return rem
from itertools import zip_longest def battle(player1, player2): rem = {'player1': [], 'player2': []} for c1,c2 in zip_longest(player1, player2, fillvalue=[0,0]): if c1[1] > c2[0]: rem['player1'].append(c1) if c2[1] > c1[0]: rem['player2'].append(c2) return rem
train
APPS_structured
Write a function which takes one parameter representing the dimensions of a checkered board. The board will always be square, so 5 means you will need a 5x5 board. The dark squares will be represented by a unicode white square, while the light squares will be represented by a unicode black square (the opposite colours ensure the board doesn't look reversed on code wars' dark background). It should return a string of the board with a space in between each square and taking into account new lines. An even number should return a board that begins with a dark square. An odd number should return a board that begins with a light square. The input is expected to be a whole number that's at least two, and returns false otherwise (Nothing in Haskell). Examples: ```python checkered_board(5) ``` returns the string ``` ■ □ ■ □ ■ □ ■ □ ■ □ ■ □ ■ □ ■ □ ■ □ ■ □ ■ □ ■ □ ■ ``` **There should be no trailing white space at the end of each line, or new line characters at the end of the string.** **Note** Do not use HTML entities for the squares (e.g. `□` for white square) as the code doesn't consider it a valid square. A good way to check is if your solution prints a correct checker board on your local terminal. **Ruby note:** CodeWars has encoding issues with rendered unicode in Ruby. You'll need to use unicode source code (e.g. "\u25A0") instead of rendered unicode (e.g "■").
def checkered_board(n): if type(n) is not int or n <2: return False return '\n'.join(map(lambda i: ' '.join(map(lambda j: '□' if ((n-j) + i) % 2 == 0 else '■', range(n))), range(n)))
def checkered_board(n): if type(n) is not int or n <2: return False return '\n'.join(map(lambda i: ' '.join(map(lambda j: '□' if ((n-j) + i) % 2 == 0 else '■', range(n))), range(n)))
train
APPS_structured
Chef wants to host some Division-3 contests. Chef has $N$ setters who are busy creating new problems for him. The $i^{th}$ setter has made $A_i$ problems where $1 \leq i \leq N$. A Division-3 contest should have exactly $K$ problems. Chef wants to plan for the next $D$ days using the problems that they have currently. But Chef cannot host more than one Division-3 contest in a day. Given these constraints, can you help Chef find the maximum number of Division-3 contests that can be hosted in these $D$ days? -----Input:----- - The first line of 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 three space-separated integers - $N$, $K$ and $D$ respectively. - The second line of each test case contains $N$ space-separated integers $A_1, A_2, \ldots, A_N$ respectively. -----Output:----- For each test case, print a single line containing one integer ― the maximum number of Division-3 contests Chef can host in these $D$ days. -----Constraints----- - $1 \leq T \leq 10^3$ - $1 \leq N \leq 10^2$ - $1 \le K \le 10^9$ - $1 \le D \le 10^9$ - $1 \le A_i \le 10^7$ for each valid $i$ -----Subtasks----- Subtask #1 (40 points): - $N = 1$ - $1 \le A_1 \le 10^5$ Subtask #2 (60 points): Original constraints -----Sample Input:----- 5 1 5 31 4 1 10 3 23 2 5 7 20 36 2 5 10 19 2 3 3 300 1 1 1 -----Sample Output:----- 0 2 7 4 1 -----Explanation:----- - Example case 1: Chef only has $A_1 = 4$ problems and he needs $K = 5$ problems for a Division-3 contest. So Chef won't be able to host any Division-3 contest in these 31 days. Hence the first output is $0$. - Example case 2: Chef has $A_1 = 23$ problems and he needs $K = 10$ problems for a Division-3 contest. Chef can choose any $10+10 = 20$ problems and host $2$ Division-3 contests in these 3 days. Hence the second output is $2$. - Example case 3: Chef has $A_1 = 20$ problems from setter-1 and $A_2 = 36$ problems from setter-2, and so has a total of $56$ problems. Chef needs $K = 5$ problems for each Division-3 contest. Hence Chef can prepare $11$ Division-3 contests. But since we are planning only for the next $D = 7$ days and Chef cannot host more than $1$ contest in a day, Chef cannot host more than $7$ contests. Hence the third output is $7$.
# cook your dish here test=int(input()) while(test!=0): n,k,d=list(map(int,input().split())) li=list(map(int,input().split())) days=sum(li)//k print(min(days,d)) test=test-1
# cook your dish here test=int(input()) while(test!=0): n,k,d=list(map(int,input().split())) li=list(map(int,input().split())) days=sum(li)//k print(min(days,d)) test=test-1
train
APPS_structured
Write a function called "filterEvenLengthWords". Given an array of strings, "filterEvenLengthWords" returns an array containing only the elements of the given array whose length is an even number. var output = filterEvenLengthWords(['word', 'words', 'word', 'words']); console.log(output); // --> ['word', 'word']
def filter_even_length_words(words): return [word for word in words if len(word) % 2 == 0]
def filter_even_length_words(words): return [word for word in words if len(word) % 2 == 0]
train
APPS_structured
You are given an integer sequence $A_1, A_2, \ldots, A_N$. For any pair of integers $(l, r)$ such that $1 \le l \le r \le N$, let's define $\mathrm{OR}(l, r)$ as $A_l \lor A_{l+1} \lor \ldots \lor A_r$. Here, $\lor$ is the bitwise OR operator. In total, there are $\frac{N(N+1)}{2}$ possible pairs $(l, r)$, i.e. $\frac{N(N+1)}{2}$ possible values of $\mathrm{OR}(l, r)$. Determine if all these values are pairwise distinct. -----Input----- - The first line of the input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows. - The first line of each test case contains a single integer $N$. - The second line contains $N$ space-separated integers $A_1, A_2, \ldots, A_N$. -----Output----- For each test case, print a single line containing the string "YES" if all values of $\mathrm{OR}(l, r)$ are pairwise distinct or "NO" otherwise (without quotes). -----Constraints----- - $1 \le T \le 300$ - $1 \le N \le 10^5$ - $0 \le A_i \le 10^{18}$ for each valid $i$ - the sum of $N$ over all test cases does not exceed $3 \cdot 10^5$ -----Example Input----- 4 3 1 2 7 2 1 2 3 6 5 8 5 12 32 45 23 47 -----Example Output----- NO YES YES NO -----Explanation----- Example case 1: The values of $\mathrm{OR}(l, r)$ are $1, 2, 7, 3, 7, 7$ (corresponding to the contiguous subsequences $[1], [2], [7], [1,2], [2,7], [1,2,7]$ respectively). We can see that these values are not pairwise distinct. Example case 2: The values of $\mathrm{OR}(l, r)$ are $1, 2, 3$ (corresponding to the contiguous subsequences $[1], [2], [1, 2]$ respectively) and they are pairwise distinct.
def answer(): if(n <= 60): all_=set() for i in range(n): value=0 for j in range(i,n): value|=a[j] all_.add(value) if(len(all_)==n*(n+1)//2):return 'YES' return 'NO' for T in range(int(input())): n=int(input()) a=list(map(int,input().split())) print(answer())
def answer(): if(n <= 60): all_=set() for i in range(n): value=0 for j in range(i,n): value|=a[j] all_.add(value) if(len(all_)==n*(n+1)//2):return 'YES' return 'NO' for T in range(int(input())): n=int(input()) a=list(map(int,input().split())) print(answer())
train
APPS_structured
Time to build a crontab parser... https://en.wikipedia.org/wiki/Cron A crontab command is made up of 5 fields in a space separated string: ``` minute: 0-59 hour: 0-23 day of month: 1-31 month: 1-12 day of week: 0-6 (0 == Sunday) ``` Each field can be a combination of the following values: * a wildcard `*` which equates to all valid values. * a range `1-10` which equates to all valid values between start-end inclusive. * a step `*/2` which equates to every second value starting at 0, or 1 for day of month and month. * a single value `2` which would be 2. * a combination of the above separated by a `,` Note: In the case of multiple values in a single field, the resulting values should be sorted. Note: Steps and ranges can also be combined `1-10/2` would be every second value in the `1-10` range `1 3 5 7 9`. For an added challenge day of week and month will both support shortened iso formats: ``` SUN MON TUE ... JAN FEB MAR ... ``` Examples ======== `*` should output every valid value `0 1 2 3 4 5 6 ...` `1` should output the value `1`. `1,20,31` should output the values `1 20 31`. `1-10` should output the values `1 2 3 4 5 6 7 8 9 10`. `*/2` should output every second value `0 2 4 6 8 10 ...`. `*/2` should output `1 3 5 7 9 ...` in the cases, day of month and month. `1-10/2` should output `1 3 5 7 9`. `*/15,3-5` should output the values `0 3 4 5 15 30 45` when applied to the minute field. Output ====== The purpose of this kata is to take in a crontab command, and render it in a nice human readable format. The output format should be in the format `field_name values`. The field name should be left justified and padded to 15 characters. The values should be a space separated string of the returned values. For example the crontab `*/15 0 1,15 * 1-5` would have the following output: ``` minute 0 15 30 45 hour 0 day of month 1 15 month 1 2 3 4 5 6 7 8 9 10 11 12 day of week 1 2 3 4 5 ``` All test cases will receive a valid crontab, there is no need to handle an incorrect number of values. Super handy resource for playing with different values to find their outputs: https://crontab.guru/
def parse(crontab): crontab = crontab.replace('FEB', '2').replace('JUL', '7').replace('SUN', '0').replace('THU', '4').split() output = [[], [], [], [], []] valid = {0: [0, 59], 1: [0, 23], 2: [1, 31], 3: [1, 12], 4: [0, 6]} def parser(s): nums = '1234567890' out = [] dig1 = dig2 = dig3 = '' state = 0 for c in s: if c == ',': if not(dig3): dig3 = '1' out.append([dig1, dig2, dig3]) dig1 = dig2 = dig3 = '' state = 0 elif not(state): dig1 += c state = 1 elif state == 1: if c in nums: dig1 += c elif c == '-': state = 2 else: state = 3 elif state == 2: if c in nums: dig2 += c else: state = 3 elif state == 3: dig3 += c if not(dig3): dig3 = '1' out.append([dig1, dig2, dig3]) return out for i in range(len(crontab)): for p in parser(crontab[i]): if p[0] == '*': output[i].extend([x for x in range(valid[i][0], valid[i][1] + 1, int(p[2]))]) elif p[1]: output[i].extend([x for x in range(int(p[0]), int(p[1]) + 1, int(p[2])) if valid[i][0] <= x <= valid[i][1]]) else: output[i].append(int(p[0])) output[i].sort() output[i] = ' '.join([str(x) for x in output[i]]) return 'minute ' + output[0] + '\nhour ' + output[1] + '\nday of month ' + output[2] + '\nmonth ' + output[3] + '\nday of week ' + output[4]
def parse(crontab): crontab = crontab.replace('FEB', '2').replace('JUL', '7').replace('SUN', '0').replace('THU', '4').split() output = [[], [], [], [], []] valid = {0: [0, 59], 1: [0, 23], 2: [1, 31], 3: [1, 12], 4: [0, 6]} def parser(s): nums = '1234567890' out = [] dig1 = dig2 = dig3 = '' state = 0 for c in s: if c == ',': if not(dig3): dig3 = '1' out.append([dig1, dig2, dig3]) dig1 = dig2 = dig3 = '' state = 0 elif not(state): dig1 += c state = 1 elif state == 1: if c in nums: dig1 += c elif c == '-': state = 2 else: state = 3 elif state == 2: if c in nums: dig2 += c else: state = 3 elif state == 3: dig3 += c if not(dig3): dig3 = '1' out.append([dig1, dig2, dig3]) return out for i in range(len(crontab)): for p in parser(crontab[i]): if p[0] == '*': output[i].extend([x for x in range(valid[i][0], valid[i][1] + 1, int(p[2]))]) elif p[1]: output[i].extend([x for x in range(int(p[0]), int(p[1]) + 1, int(p[2])) if valid[i][0] <= x <= valid[i][1]]) else: output[i].append(int(p[0])) output[i].sort() output[i] = ' '.join([str(x) for x in output[i]]) return 'minute ' + output[0] + '\nhour ' + output[1] + '\nday of month ' + output[2] + '\nmonth ' + output[3] + '\nday of week ' + output[4]
train
APPS_structured
A frog is crossing a river. The river is divided into x units and at each unit there may or may not exist a stone. The frog can jump on a stone, but it must not jump into the water. Given a list of stones' positions (in units) in sorted ascending order, determine if the frog is able to cross the river by landing on the last stone. Initially, the frog is on the first stone and assume the first jump must be 1 unit. If the frog's last jump was k units, then its next jump must be either k - 1, k, or k + 1 units. Note that the frog can only jump in the forward direction. Note: The number of stones is ≥ 2 and is < 1,100. Each stone's position will be a non-negative integer < 231. The first stone's position is always 0. Example 1: [0,1,3,5,6,8,12,17] There are a total of 8 stones. The first stone at the 0th unit, second stone at the 1st unit, third stone at the 3rd unit, and so on... The last stone at the 17th unit. Return true. The frog can jump to the last stone by jumping 1 unit to the 2nd stone, then 2 units to the 3rd stone, then 2 units to the 4th stone, then 3 units to the 6th stone, 4 units to the 7th stone, and 5 units to the 8th stone. Example 2: [0,1,2,3,4,8,9,11] Return false. There is no way to jump to the last stone as the gap between the 5th and 6th stone is too large.
class Solution: def canCross(self, stones): """ :type stones: List[int] :rtype: bool """ stone_set, fail = set(stones), set() stack = [(0, 0)] while stack: stone, jump = stack.pop() for j in (jump-1, jump, jump+1): s = stone + j if j > 0 and s in stone_set and (s, j) not in fail: if s == stones[-1]: return True stack.append((s, j)) fail.add((stone, jump)) return False # queue, invalid, stones = [(0, 0)], [], sorted(list(set(stones))) # while queue: # pos, jump = queue.pop() # for n in [jump-1, jump, jump+1]: # if n > 0 and pos + n in stones and pos + n not in invalid: # if pos + n == stones[-1]: # return True # else: # queue += [(pos+n, n)] # elif n > 0 and pos + n not in invalid: # invalid += [pos + n] # return False
class Solution: def canCross(self, stones): """ :type stones: List[int] :rtype: bool """ stone_set, fail = set(stones), set() stack = [(0, 0)] while stack: stone, jump = stack.pop() for j in (jump-1, jump, jump+1): s = stone + j if j > 0 and s in stone_set and (s, j) not in fail: if s == stones[-1]: return True stack.append((s, j)) fail.add((stone, jump)) return False # queue, invalid, stones = [(0, 0)], [], sorted(list(set(stones))) # while queue: # pos, jump = queue.pop() # for n in [jump-1, jump, jump+1]: # if n > 0 and pos + n in stones and pos + n not in invalid: # if pos + n == stones[-1]: # return True # else: # queue += [(pos+n, n)] # elif n > 0 and pos + n not in invalid: # invalid += [pos + n] # return False
train
APPS_structured
-----Problem Statement----- You all must have played the game candy crush. So here is a bomb which works much the fruit bomb in candy crush. A designer, Anton, designed a very powerful bomb. The bomb, when placed on a location $(x, y)$ in a $R \times C$ grid, wipes out the row $x$ and column $y$ completely. You are given a $R\times C$ grid with $N$ targets. You have only one bomb. Your aim is to maximize the damage and hence destroy most number of targets. Given the location of targets on the grid, find out the number of targets that can destroyed. The grid system uses index starting with $0$. -----Input----- - First line contains three space separated integers, $R$, $C$ and $N$. Then, $N$ lines follow. - Each line contains space separated integers $r$ and $c$ mentioning the location of the target. -----Output----- A single integer giving the number of targets that can be destroyed. -----Constraints----- - $1 \leq R, C \leq 3 \times 10^5$ - $1 \leq N \leq min(R \times C, 3 \times 10^5)$ - $0 \leq r < R$ - $0 \leq c < C$ - Any input pair $(r, c)$ is not repeated. -----Subtasks----- The total marks will be divided into: - 20% : $R, C \leq 10^3$ - 80% : Original Constraints -----Sample Input----- 2 3 3 1 1 0 0 0 2 -----Sample Output----- 3 -----EXPLANATION----- It is possible to destroy all the targets if we place the bomb at $(0, 1)$. Hence, total number of targets destroyed is $3$, which is our answer.
r,c,n=list(map(int,input().split())) ro=[0]*n co=[0]*n for i in range(n): a,b=list(map(int,input().split())) ro[a]+=1 co[b]+=1 ma=0 ma+=max(ro) ma+=max(co) print(ma)
r,c,n=list(map(int,input().split())) ro=[0]*n co=[0]*n for i in range(n): a,b=list(map(int,input().split())) ro[a]+=1 co[b]+=1 ma=0 ma+=max(ro) ma+=max(co) print(ma)
train
APPS_structured
You are in charge of controlling a dam. The dam can store at most L liters of water. Initially, the dam is empty. Some amount of water flows into the dam every morning, and any amount of water may be discharged every night, but this amount needs to be set so that no water overflows the dam the next morning. It is known that v_i liters of water at t_i degrees Celsius will flow into the dam on the morning of the i-th day. You are wondering about the maximum possible temperature of water in the dam at noon of each day, under the condition that there needs to be exactly L liters of water in the dam at that time. For each i, find the maximum possible temperature of water in the dam at noon of the i-th day. Here, consider each maximization separately, that is, the amount of water discharged for the maximization of the temperature on the i-th day, may be different from the amount of water discharged for the maximization of the temperature on the j-th day (j≠i). Also, assume that the temperature of water is not affected by anything but new water that flows into the dam. That is, when V_1 liters of water at T_1 degrees Celsius and V_2 liters of water at T_2 degrees Celsius are mixed together, they will become V_1+V_2 liters of water at \frac{T_1*V_1+T_2*V_2}{V_1+V_2} degrees Celsius, and the volume and temperature of water are not affected by any other factors. -----Constraints----- - 1≤ N ≤ 5*10^5 - 1≤ L ≤ 10^9 - 0≤ t_i ≤ 10^9(1≤i≤N) - 1≤ v_i ≤ L(1≤i≤N) - v_1 = L - L, each t_i and v_i are integers. -----Input----- Input is given from Standard Input in the following format: N L t_1 v_1 t_2 v_2 : t_N v_N -----Output----- Print N lines. The i-th line should contain the maximum temperature such that it is possible to store L liters of water at that temperature in the dam at noon of the i-th day. Each of these values is accepted if the absolute or relative error is at most 10^{-6}. -----Sample Input----- 3 10 10 10 20 5 4 3 -----Sample Output----- 10.0000000 15.0000000 13.2000000 - On the first day, the temperature of water in the dam is always 10 degrees: the temperature of the only water that flows into the dam on the first day. - 10 liters of water at 15 degrees of Celsius can be stored on the second day, by discharging 5 liters of water on the night of the first day, and mix the remaining water with the water that flows into the dam on the second day. - 10 liters of water at 13.2 degrees of Celsius can be stored on the third day, by discharging 8 liters of water on the night of the first day, and mix the remaining water with the water that flows into the dam on the second and third days.
# F from collections import deque TT_list = [] # input N, L = list(map(int, input().split())) T = 0.0 vt_now = 0.0 v_now = 0 que = deque() for i in range(N): ti, v = list(map(int, input().split())) t = float(ti) v_now += v vt_now += v*t # add if v == L: que.append([t, v]) else: while v < L and len(que) > 0: t_, v_ = que[-1] if t_ <= t: que.append([t, v]) break elif v + v_ >= L: v_ = v + v_ - L t = ((L - v) * t_ + v * t) / L v = L que = deque([[t, v]]) v_now = L vt_now = t*L # break else: t = (t*v + t_*v_) / (v + v_) v = v + v_ que.pop() # minus while v_now > L: if que[0][1] <= v_now - L: v_now -= que[0][1] vt_now -= que[0][1]*que[0][0] que.popleft() else: que[0][1] -= v_now - L vt_now -= (v_now - L)*que[0][0] v_now = L TT_list.append(vt_now / L) for i in range(N): print((TT_list[i]))
# F from collections import deque TT_list = [] # input N, L = list(map(int, input().split())) T = 0.0 vt_now = 0.0 v_now = 0 que = deque() for i in range(N): ti, v = list(map(int, input().split())) t = float(ti) v_now += v vt_now += v*t # add if v == L: que.append([t, v]) else: while v < L and len(que) > 0: t_, v_ = que[-1] if t_ <= t: que.append([t, v]) break elif v + v_ >= L: v_ = v + v_ - L t = ((L - v) * t_ + v * t) / L v = L que = deque([[t, v]]) v_now = L vt_now = t*L # break else: t = (t*v + t_*v_) / (v + v_) v = v + v_ que.pop() # minus while v_now > L: if que[0][1] <= v_now - L: v_now -= que[0][1] vt_now -= que[0][1]*que[0][0] que.popleft() else: que[0][1] -= v_now - L vt_now -= (v_now - L)*que[0][0] v_now = L TT_list.append(vt_now / L) for i in range(N): print((TT_list[i]))
train
APPS_structured
There are n student groups at the university. During the study day, each group can take no more than 7 classes. Seven time slots numbered from 1 to 7 are allocated for the classes. The schedule on Monday is known for each group, i. e. time slots when group will have classes are known. Your task is to determine the minimum number of rooms needed to hold classes for all groups on Monday. Note that one room can hold at most one group class in a single time slot. -----Input----- The first line contains a single integer n (1 ≤ n ≤ 1000) — the number of groups. Each of the following n lines contains a sequence consisting of 7 zeroes and ones — the schedule of classes on Monday for a group. If the symbol in a position equals to 1 then the group has class in the corresponding time slot. In the other case, the group has no class in the corresponding time slot. -----Output----- Print minimum number of rooms needed to hold all groups classes on Monday. -----Examples----- Input 2 0101010 1010101 Output 1 Input 3 0101011 0011001 0110111 Output 3 -----Note----- In the first example one room is enough. It will be occupied in each of the seven time slot by the first group or by the second group. In the second example three rooms is enough, because in the seventh time slot all three groups have classes.
n=int(input()) w=[0,0,0,0,0,0,0] for i in range(n): j=0 for i in input(): if i=='1': w[j]+=1 j+=1 print(max(w))
n=int(input()) w=[0,0,0,0,0,0,0] for i in range(n): j=0 for i in input(): if i=='1': w[j]+=1 j+=1 print(max(w))
train
APPS_structured
This year $p$ footballers and $q$ cricketers have been invited to participate in IPL (Indian Programming League) as guests. You have to accommodate them in $r$ rooms such that- - No room may remain empty. - A room may contain either only footballers or only cricketers, not both. - No cricketers are allowed to stay alone in a room. Find the number of ways to place the players. Note though, that all the rooms are identical. But each of the cricketers and footballers are unique. Since the number of ways can be very large, print the answer modulo $998,244,353$. -----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 three space-separated integers $p$, $q$ and $r$ denoting the number of footballers, cricketers and rooms. -----Output----- For each test case, output the number of ways to place the players modulo $998,244,353$. -----Constraints----- - $1 \le T \le 100$ - $1 \le p, q, r \le 100$ -----Example Input----- 4 2 1 4 2 4 4 2 5 4 2 8 4 -----Example Output----- 0 3 10 609 -----Explanation----- Example case 2: Three possible ways are: - {Footballer 1}, {Footballer 2}, {Cricketer 1, Cricketer 2}, {Cricketer 3, Cricketer 4} - {Footballer 1}, {Footballer 2}, {Cricketer 1, Cricketer 3}, {Cricketer 2, Cricketer 4} - {Footballer 1}, {Footballer 2}, {Cricketer 1, Cricketer 4}, {Cricketer 2, Cricketer 3} Please note that the rooms are identical.
# -*- coding: utf-8 -*- """ Created on Thu Jan 23 18:46:38 2020 @author: 736473 """ MOD = 998244353 fball = [ [0]*101 for _ in range(101) ] cric = [ [0]*101 for _ in range(101) ] def calSNum(n, r): if n == r or r == 1: fball[r][n] = 1 return if n > 0 and r > 0 and n > r: fball[r][n] = (fball[r-1][n-1]%MOD + (r*fball[r][n-1])%MOD )%MOD return fball[r][n] = 0 def calASNum(n, r): if n == 0 and r == 0 : cric[r][n] = 0 return if n >= 2 and r == 1: cric[r][n] = 1 return if r > 0 and n > 0 and n >= 2*r: cric[r][n] = ((r*cric[r][n-1])%MOD + ((n-1)*cric[r-1][n-2])%MOD )%MOD return cric[r][n] = 0 def preCompute(): for r in range(1,101): for n in range(1, 101): calSNum(n, r) calASNum(n, r) def main(): preCompute() t = int(input()) while True: try: f, c, r = list(map(int, input().split())) except EOFError: break ans = 0 if f + (c//2) >= r: minv = min(f, r) for i in range(1, minv+1): if r-i <= c//2: ans = (ans + (fball[i][f] * cric[r-i][c])%MOD )%MOD print(ans) def __starting_point(): main() __starting_point()
# -*- coding: utf-8 -*- """ Created on Thu Jan 23 18:46:38 2020 @author: 736473 """ MOD = 998244353 fball = [ [0]*101 for _ in range(101) ] cric = [ [0]*101 for _ in range(101) ] def calSNum(n, r): if n == r or r == 1: fball[r][n] = 1 return if n > 0 and r > 0 and n > r: fball[r][n] = (fball[r-1][n-1]%MOD + (r*fball[r][n-1])%MOD )%MOD return fball[r][n] = 0 def calASNum(n, r): if n == 0 and r == 0 : cric[r][n] = 0 return if n >= 2 and r == 1: cric[r][n] = 1 return if r > 0 and n > 0 and n >= 2*r: cric[r][n] = ((r*cric[r][n-1])%MOD + ((n-1)*cric[r-1][n-2])%MOD )%MOD return cric[r][n] = 0 def preCompute(): for r in range(1,101): for n in range(1, 101): calSNum(n, r) calASNum(n, r) def main(): preCompute() t = int(input()) while True: try: f, c, r = list(map(int, input().split())) except EOFError: break ans = 0 if f + (c//2) >= r: minv = min(f, r) for i in range(1, minv+1): if r-i <= c//2: ans = (ans + (fball[i][f] * cric[r-i][c])%MOD )%MOD print(ans) def __starting_point(): main() __starting_point()
train
APPS_structured
Don't Drink the Water Given a two-dimensional array representation of a glass of mixed liquids, sort the array such that the liquids appear in the glass based on their density. (Lower density floats to the top) The width of the glass will not change from top to bottom. ``` ====================== | Density Chart | ====================== | Honey | H | 1.36 | | Water | W | 1.00 | | Alcohol | A | 0.87 | | Oil | O | 0.80 | ---------------------- [ [ ['H', 'H', 'W', 'O'], ['O','O','O','O'] ['W', 'W', 'O', 'W'], => ['W','W','W','W'] ['H', 'H', 'O', 'O'] ['H','H','H','H'] ] ] ``` The glass representation may be larger or smaller. If a liquid doesn't fill a row, it floats to the top and to the left.
def separate_liquids(glass): liquids = []; comparing = { 'H' : 1.36, 'W' : 1.00, 'A' : 0.87, 'O' : 0.80 } for row in glass: liquids.extend(row) liquids.sort(key=lambda k: comparing[k], reverse=True) for i in range(len(glass)): for j in range(len(glass[0])): glass[i][j] = liquids.pop() return glass
def separate_liquids(glass): liquids = []; comparing = { 'H' : 1.36, 'W' : 1.00, 'A' : 0.87, 'O' : 0.80 } for row in glass: liquids.extend(row) liquids.sort(key=lambda k: comparing[k], reverse=True) for i in range(len(glass)): for j in range(len(glass[0])): glass[i][j] = liquids.pop() return glass
train
APPS_structured
=====Function Descriptions===== itertools.product() This tool computes the cartesian product of input iterables. It is equivalent to nested for-loops. For example, product(A, B) returns the same as ((x,y) for x in A for y in B). Sample Code >>> from itertools import product >>> >>> print list(product([1,2,3],repeat = 2)) [(1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3), (3, 1), (3, 2), (3, 3)] >>> >>> print list(product([1,2,3],[3,4])) [(1, 3), (1, 4), (2, 3), (2, 4), (3, 3), (3, 4)] >>> >>> A = [[1,2,3],[3,4,5]] >>> print list(product(*A)) [(1, 3), (1, 4), (1, 5), (2, 3), (2, 4), (2, 5), (3, 3), (3, 4), (3, 5)] >>> >>> B = [[1,2,3],[3,4,5],[7,8]] >>> print list(product(*B)) [(1, 3, 7), (1, 3, 8), (1, 4, 7), (1, 4, 8), (1, 5, 7), (1, 5, 8), (2, 3, 7), (2, 3, 8), (2, 4, 7), (2, 4, 8), (2, 5, 7), (2, 5, 8), (3, 3, 7), (3, 3, 8), (3, 4, 7), (3, 4, 8), (3, 5, 7), (3, 5, 8)] =====Problem Statement===== You are given a two lists A and B. Your task is to compute their cartesian product AXB. Example A = [1, 2] B = [3, 4] AxB = [(1, 3), (1, 4), (2, 3), (2, 4)] Note: A and B are sorted lists, and the cartesian product's tuples should be output in sorted order. =====Input Format===== The first line contains the space separated elements of list A. The second line contains the space separated elements of list B. Both lists have no duplicate integer elements. =====Constraints===== 0<A<30 0<B<30 =====Output Format===== Output the space separated tuples of the cartesian product.
import itertools ar1 = list(map(int,input().split())) ar2 = list(map(int,input().split())) cross = list(itertools.product(ar1,ar2)) for i in cross: print(i,end=' ')
import itertools ar1 = list(map(int,input().split())) ar2 = list(map(int,input().split())) cross = list(itertools.product(ar1,ar2)) for i in cross: print(i,end=' ')
train
APPS_structured
Given an integer k, return the minimum number of Fibonacci numbers whose sum is equal to k. The same Fibonacci number can be used multiple times. The Fibonacci numbers are defined as: F1 = 1 F2 = 1 Fn = Fn-1 + Fn-2 for n > 2. It is guaranteed that for the given constraints we can always find such Fibonacci numbers that sum up to k. Example 1: Input: k = 7 Output: 2 Explanation: The Fibonacci numbers are: 1, 1, 2, 3, 5, 8, 13, ... For k = 7 we can use 2 + 5 = 7. Example 2: Input: k = 10 Output: 2 Explanation: For k = 10 we can use 2 + 8 = 10. Example 3: Input: k = 19 Output: 3 Explanation: For k = 19 we can use 1 + 5 + 13 = 19. Constraints: 1 <= k <= 10^9
class Solution: def findMinFibonacciNumbers(self, k: int) -> int: a,b = 1,1 while b<=k: a,b = b, a+b res = 0 while a > 0: if k >= a: k -= a res += 1 a,b = b-a, a return res # if k == 0: # return 0 # a,b = 1, 1 # while b <= k: # O( (logk)^2 ) # a,b = b, a+b # return self.findMinFibonacciNumbers(k-a)+1 # First recursion, logk. Second resursion logK - 1, third entry logK - 2. # arr = [1, 1] # while arr[-1] <= k: # arr.append( arr[-1]+arr[-2] ) # O(n) space # d = k-arr[-2] # cnt = 1 # while d > 0: # ind = bisect.bisect_right(arr, d) # O(n log n) # d -= arr[ind-1] # cnt += 1 # return cnt
class Solution: def findMinFibonacciNumbers(self, k: int) -> int: a,b = 1,1 while b<=k: a,b = b, a+b res = 0 while a > 0: if k >= a: k -= a res += 1 a,b = b-a, a return res # if k == 0: # return 0 # a,b = 1, 1 # while b <= k: # O( (logk)^2 ) # a,b = b, a+b # return self.findMinFibonacciNumbers(k-a)+1 # First recursion, logk. Second resursion logK - 1, third entry logK - 2. # arr = [1, 1] # while arr[-1] <= k: # arr.append( arr[-1]+arr[-2] ) # O(n) space # d = k-arr[-2] # cnt = 1 # while d > 0: # ind = bisect.bisect_right(arr, d) # O(n log n) # d -= arr[ind-1] # cnt += 1 # return cnt
train
APPS_structured
Lately, Mr. Chanek frequently plays the game Arena of Greed. As the name implies, the game's goal is to find the greediest of them all, who will then be crowned king of Compfestnesia. The game is played by two people taking turns, where Mr. Chanek takes the first turn. Initially, there is a treasure chest containing $N$ gold coins. The game ends if there are no more gold coins in the chest. In each turn, the players can make one of the following moves: Take one gold coin from the chest. Take half of the gold coins on the chest. This move is only available if the number of coins in the chest is even. Both players will try to maximize the number of coins they have. Mr. Chanek asks your help to find the maximum number of coins he can get at the end of the game if both he and the opponent plays optimally. -----Input----- The first line contains a single integer $T$ $(1 \le T \le 10^5)$ denotes the number of test cases. The next $T$ lines each contain a single integer $N$ $(1 \le N \le 10^{18})$. -----Output----- $T$ lines, each line is the answer requested by Mr. Chanek. -----Example----- Input 2 5 6 Output 2 4 -----Note----- For the first case, the game is as follows: Mr. Chanek takes one coin. The opponent takes two coins. Mr. Chanek takes one coin. The opponent takes one coin. For the second case, the game is as follows: Mr. Chanek takes three coins. The opponent takes one coin. Mr. Chanek takes one coin. The opponent takes one coin.
from sys import stdin, stdout from collections import defaultdict input = stdin.readline for _ in range(int(input())): n = int(input()) chanek = 0 flag = 1 while n>0: if n%4==0 and n!=4: if flag: chanek += 1 n-=1 flag = 0 else: n-=1 flag = 1 elif n%2: if flag: chanek += 1 n-=1 flag = 0 else: n-=1 flag = 1 else: if flag: chanek += n//2 n//=2 flag = 0 else: n//=2 flag = 1 print(chanek)
from sys import stdin, stdout from collections import defaultdict input = stdin.readline for _ in range(int(input())): n = int(input()) chanek = 0 flag = 1 while n>0: if n%4==0 and n!=4: if flag: chanek += 1 n-=1 flag = 0 else: n-=1 flag = 1 elif n%2: if flag: chanek += 1 n-=1 flag = 0 else: n-=1 flag = 1 else: if flag: chanek += n//2 n//=2 flag = 0 else: n//=2 flag = 1 print(chanek)
train
APPS_structured
You're looking through different hex codes, and having trouble telling the difference between #000001 and #100000 We need a way to tell which is red, and which is blue! That's where you create ```hex_color()```! It should read an RGB input, and return whichever value (red, blue, or green) is of greatest concentration! But, if multiple colors are of equal concentration, you should return their mix! ```python red + blue = magenta green + red = yellow blue + green = cyan red + blue + green = white ``` One last thing, if the string given is empty, or has all 0's, return black! Examples: ```python hex_color('087 255 054') == 'green' hex_color('181 181 170') == 'yellow' hex_color('000 000 000') == 'black' hex_color('001 001 001') == 'white' ```
def hex_color(codes): if codes == '': return 'black' r,g,b = map(int,codes.split(' ')) if 0 == r == g == b: return 'black' if r == g == b: return 'white' if r > g and r > b: return 'red' if g > r and g > b: return 'green' if b > g and b > r: return 'blue' if r > g and r == b: return 'magenta' if r > b and r == g: return 'yellow' if b > r and b == g: return 'cyan'
def hex_color(codes): if codes == '': return 'black' r,g,b = map(int,codes.split(' ')) if 0 == r == g == b: return 'black' if r == g == b: return 'white' if r > g and r > b: return 'red' if g > r and g > b: return 'green' if b > g and b > r: return 'blue' if r > g and r == b: return 'magenta' if r > b and r == g: return 'yellow' if b > r and b == g: return 'cyan'
train
APPS_structured
Cascading Style Sheets (CSS) is a style sheet language used for describing the look and formatting of a document written in a markup language. A style sheet consists of a list of rules. Each rule or rule-set consists of one or more selectors, and a declaration block. Selector describes which element it matches. Sometimes element is matched to multiple selectors. In this case, element inherits multiple styles, from each rule it matches. Rules can override each other. To solve this problem, each selector has it's own 'specificity' - e.g. weight. The selector with greater specificity overrides the other selector. Your task is to calculate the weights of two selectors and determine which of them will beat the other one. ```python compare("body p", "div") # returns "body p" compare(".class", "#id") # returns "#id" compare("div.big", ".small") # returns "div.big" compare(".big", ".small") # returns ".small" (because it appears later) ``` For simplicity, all selectors in test cases are CSS1-compatible, test cases don't include pseudoclasses, pseudoelements, attribute selectors, etc. Below is an explanation on how to weight two selectors. You can read more about specificity here. The simplest selector type is ``tagname`` selector. It writes as a simple alphanumeric identifier: eg ``body``, ``div``, ``h1``, etc. It has the least weight. If selectors have multiple elements - the selector with more elements win. For example, ``body p`` beats ``div``, because it refers to 2 (nested) elements rather than 1. Another simple selector is ``.class`` selector. It begins with dot and refer to element with specific ``class`` attribute. Class selectors can also be applied to tagname selectors, so ``div.red`` refer to ```` element. They can be grouped, for example, ``.red.striped``. Class selector beats tagname selector. The most weighted selector type in stylesheet is ``#id`` selector. It begins with hash sign and refer to element with specific ``id`` attribute. It can also be standalone, or applied to an element. Id selector beats both selector types. And the least weighted selector is ``*``, which has no specificity and can be beat by any other selector. Selectors can be combined, for example, ``body #menu ul li.active`` refers to ``li`` element with ``class="active"``, placed inside ``ul`` element, placed inside element width ``id="menu"``, placed inside ``body``. Specificity calculation is simple. Selector with more #id selectors wins If both are same, the winner is selector with more .class selectors If both are same, selector with more elements wins If all of above values are same, the winner is selector that appear last For example, let's represent the number of ``#id`` , ``.class``, ``tagname`` selectors as array (in order from worst to best): SelectorSpecificity (#id,.class,tagname) *0, 0, 0 span0, 0, 1 body p0, 0, 2 .green0, 1, 0 apple.yellow0, 1, 1 div.menu li0, 1, 2 .red .orange0, 2, 0 div.big .first0, 2, 1 #john1, 0, 0 div#john1, 0, 1 body #john span1, 0, 2 menu .item #checkout.active1, 2, 1 #foo div#bar.red .none2, 2, 1
import re def key(t): i,s = t return (s.count('#'), s.count('.'), len(re.split(r'(?!<^)[ .#]+', s)), s!='*', i) def compare(*args): return max(enumerate(args), key=key)[1]
import re def key(t): i,s = t return (s.count('#'), s.count('.'), len(re.split(r'(?!<^)[ .#]+', s)), s!='*', i) def compare(*args): return max(enumerate(args), key=key)[1]
train
APPS_structured
# MOD 256 without the MOD operator The MOD-operator % (aka mod/modulus/remainder): ``` Returns the remainder of a division operation. The sign of the result is the same as the sign of the first operand. (Different behavior in Python!) ``` The short unbelievable mad story for this kata: I wrote a program and needed the remainder of the division by 256. And then it happened: The "5"/"%"-Key did not react. It must be broken! So I needed a way to: ``` Calculate the remainder of the division by 256 without the %-operator. ``` Also here some examples: ``` Input 254 -> Result 254 Input 256 -> Result 0 Input 258 -> Result 2 Input -258 -> Result -2 (in Python: Result: 254!) ``` It is always expected the behavior of the MOD-Operator of the language! The input number will always between -10000 and 10000. For some languages the %-operator will be blocked. If it is not blocked and you know how to block it, tell me and I will include it. For all, who say, this would be a duplicate: No, this is no duplicate! There are two katas, in that you have to write a general method for MOD without %. But this kata is only for MOD 256. And so you can create also other specialized solutions. ;-) Of course you can use the digit "5" in your solution. :-) I'm very curious for your solutions and the way you solve it. I found several interesting "funny" ways. Have fun coding it and please don't forget to vote and rank this kata! :-) I have also created other katas. Take a look if you enjoyed this kata!
def mod256_without_mod(number): return number & 255
def mod256_without_mod(number): return number & 255
train
APPS_structured
There are $N$ cars (numbered $1$ through $N$) on a circular track with length $N$. For each $i$ ($2 \le i \le N$), the $i$-th of them is at a distance $i-1$ clockwise from car $1$, i.e. car $1$ needs to travel a distance $i-1$ clockwise to reach car $i$. Also, for each valid $i$, the $i$-th car has $f_i$ litres of gasoline in it initially. You are driving car $1$ in the clockwise direction. To move one unit of distance in this direction, you need to spend $1$ litre of gasoline. When you pass another car (even if you'd run out of gasoline exactly at that point), you steal all its gasoline. Once you do not have any gasoline left, you stop. What is the total clockwise distance travelled by your car? -----Input----- - The first line of the input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows. - The first line of each test case contains a single integer $N$. - The second line contains $N$ space-separated integers $f_1, f_2, \ldots, f_N$. -----Output----- For each test case, print a single line containing one integer ― the total clockwise distance travelled. -----Constraints----- - $1 \le T \le 100$ - $1 \le N \le 100$ - $0 \le f_i \le 100$ for each valid $i$ -----Subtasks----- Subtask #1 (100 points): original constraints -----Example Input----- 3 5 3 0 0 0 0 5 1 1 1 1 1 5 5 4 3 2 1 -----Example Output----- 3 5 15
# cook your dish here for t in range(int(input())): N = int(input()) f = list(map(int, input().split())) gas = f[0] distance = 0 for _ in range(1, N): if gas == 0: break gas = gas - 1 + f[_] distance += 1 print(distance + gas)
# cook your dish here for t in range(int(input())): N = int(input()) f = list(map(int, input().split())) gas = f[0] distance = 0 for _ in range(1, N): if gas == 0: break gas = gas - 1 + f[_] distance += 1 print(distance + gas)
train
APPS_structured
You have recently discovered that horses travel in a unique pattern - they're either running (at top speed) or resting (standing still). Here's an example of how one particular horse might travel: ``` The horse Blaze can run at 14 metres/second for 60 seconds, but must then rest for 45 seconds. After 500 seconds Blaze will have traveled 4200 metres. ``` Your job is to write a function that returns how long a horse will have traveled after a given time. ####Input: * totalTime - How long the horse will be traveling (in seconds) * runTime - How long the horse can run for before having to rest (in seconds) * restTime - How long the horse have to rest for after running (in seconds) * speed - The max speed of the horse (in metres/second)
def travel(total_time, run_time, rest_time, speed): return speed*(run_time*((total_time)//(run_time+rest_time))+min(run_time,total_time%(run_time+rest_time)))
def travel(total_time, run_time, rest_time, speed): return speed*(run_time*((total_time)//(run_time+rest_time))+min(run_time,total_time%(run_time+rest_time)))
train
APPS_structured
Chefu is Chef's little brother, he is 12 years old and he is new to competitive programming. Chefu is practicing very hard to become a very skilled competitive programmer and win gold medal in IOI. Now Chefu is participating in a contest and the problem that he is trying to solve states: Given an array A of N integers, find any i, j such that i < j and Ai + Aj is maximum possible unfortunately, there's no much time left before the end of the contest, so Chefu doesn't have time to think of correct solution, so instead, he wrote a solution that selects a random pair (i, j) (i < j) and output Ai + Aj. each pair is equiprobable to be selected. Now Chefu wants your help to calculate the probability that his solution will pass a particular input. -----Input----- First line contains an integer T denoting the number of test-cases. First line of each test-case contains a single integer N Second line of each test-case contains N space-separated integers A1 A2 ... AN -----Output----- For each test-case output a single line containing a single number denoting the probability that Chefu's solution to output a correct answer. your answer will be accepted if the absolute difference between it and correct answer is less than 1e-6 -----Constraints----- - 1 ≤ T ≤ 100 - 2 ≤ N ≤ 100 - 1 ≤ Ai ≤ 1,000 -----Example----- Input: 3 4 3 3 3 3 6 1 1 1 2 2 2 4 1 2 2 3 Output: 1.00000000 0.20000000 0.33333333
# cook your dish here try: T=int(input()) for _ in range(T): N=int(input()) A=list(map(int,input().split())) c=0 d=[] for i in range(N): for j in range(i+1,N): d.append(A[i]+A[j]) ans=d.count(max(d))/len(d) print('%0.8f'%ans) except: pass
# cook your dish here try: T=int(input()) for _ in range(T): N=int(input()) A=list(map(int,input().split())) c=0 d=[] for i in range(N): for j in range(i+1,N): d.append(A[i]+A[j]) ans=d.count(max(d))/len(d) print('%0.8f'%ans) except: pass
train
APPS_structured
Given a nested list of integers represented as a string, implement a parser to deserialize it. Each element is either an integer, or a list -- whose elements may also be integers or other lists. Note: You may assume that the string is well-formed: String is non-empty. String does not contain white spaces. String contains only digits 0-9, [, - ,, ]. Example 1: Given s = "324", You should return a NestedInteger object which contains a single integer 324. Example 2: Given s = "[123,[456,[789]]]", Return a NestedInteger object containing a nested list with 2 elements: 1. An integer containing value 123. 2. A nested list containing two elements: i. An integer containing value 456. ii. A nested list with one element: a. An integer containing value 789.
# """ # This is the interface that allows for creating nested lists. # You should not implement it, or speculate about its implementation # """ #class NestedInteger: # def __init__(self, value=None): # """ # If value is not specified, initializes an empty list. # Otherwise initializes a single integer equal to value. # """ # # def isInteger(self): # """ # @return True if this NestedInteger holds a single integer, rather than a nested list. # :rtype bool # """ # # def add(self, elem): # """ # Set this NestedInteger to hold a nested list and adds a nested integer elem to it. # :rtype void # """ # # def setInteger(self, value): # """ # Set this NestedInteger to hold a single integer equal to value. # :rtype void # """ # # def getInteger(self): # """ # @return the single integer that this NestedInteger holds, if it holds a single integer # Return None if this NestedInteger holds a nested list # :rtype int # """ # # def getList(self): # """ # @return the nested list that this NestedInteger holds, if it holds a nested list # Return None if this NestedInteger holds a single integer # :rtype List[NestedInteger] # """ class Solution: def deserialize(self, s): """ :type s: str :rtype: NestedInteger """ return eval(s) # def deserialize(self, s): # def nestedInteger(x): # if isinstance(x, int): # return NestedInteger(x) # lst = NestedInteger() # for y in x: # lst.add(nestedInteger(y)) # return lst # return nestedInteger(eval(s))
# """ # This is the interface that allows for creating nested lists. # You should not implement it, or speculate about its implementation # """ #class NestedInteger: # def __init__(self, value=None): # """ # If value is not specified, initializes an empty list. # Otherwise initializes a single integer equal to value. # """ # # def isInteger(self): # """ # @return True if this NestedInteger holds a single integer, rather than a nested list. # :rtype bool # """ # # def add(self, elem): # """ # Set this NestedInteger to hold a nested list and adds a nested integer elem to it. # :rtype void # """ # # def setInteger(self, value): # """ # Set this NestedInteger to hold a single integer equal to value. # :rtype void # """ # # def getInteger(self): # """ # @return the single integer that this NestedInteger holds, if it holds a single integer # Return None if this NestedInteger holds a nested list # :rtype int # """ # # def getList(self): # """ # @return the nested list that this NestedInteger holds, if it holds a nested list # Return None if this NestedInteger holds a single integer # :rtype List[NestedInteger] # """ class Solution: def deserialize(self, s): """ :type s: str :rtype: NestedInteger """ return eval(s) # def deserialize(self, s): # def nestedInteger(x): # if isinstance(x, int): # return NestedInteger(x) # lst = NestedInteger() # for y in x: # lst.add(nestedInteger(y)) # return lst # return nestedInteger(eval(s))
train
APPS_structured
# Task **Your task** is to implement function `printNumber` (`print_number` in C/C++ and Python `Kata.printNumber` in Java) that returns string that represents given number in text format (see examples below). Arguments: - `number` — Number that we need to print (`num` in C/C++/Java) - `char` — Character for building number (`ch` in C/C++/Java) # Examples ```c,python print_number(99, '$') //Should return //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$\n //$ $\n //$ $$$$ $$$$ $$$$ $$$$ $$$$ $\n //$ $$ $$ $$ $$ $$ $$ $$ $$ $$ $$ $\n //$ $$ $$ $$ $$ $$ $$ $$ $$ $$ $$ $\n //$ $$ $$ $$ $$ $$ $$ $$$$ $$$$ $\n //$ $$ $$ $$ $$ $$ $$ $$ $$ $\n //$ $$$$ $$$$ $$$$ $$ $$ $\n //$ $\n //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ print_number(12345, '*') //Should return //****************************************\n //* *\n //* ** **** **** ** ** ****** *\n //* *** ** ** ** ** ** ** ** *\n //* * ** ** ** ** ** ***** *\n //* ** ** ** ***** ** *\n //* ** ** ** ** ** ** *\n //* ****** ****** **** ** ***** *\n //* *\n //**************************************** print_number(67890, '@') //Should return //@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@\n //@ @\n //@ @@ @@@@@@ @@@@ @@@@ @@@@ @\n //@ @@ @@ @@ @@ @@ @@ @@ @@ @@ @\n //@ @@@@ @@ @@@@ @@ @@ @@ @@ @\n //@ @@ @@ @@ @@@@ @@@@ @@ @@ @\n //@ @@ @@ @@ @@ @@ @@ @@ @@ @\n //@ @@@@ @@ @@@@ @@ @@@@ @\n //@ @\n //@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ ``` >***Note, that***: - Number should be `0 <= number <= 99999` and have `5 digits` (should have zeros at the start if needed) - Test cases contains only valid values (integers that are 0 <= number <= 99999) and characters - Numbers should have the same shape as in the examples (6x6 by the way) - Returned string should be joined by `\n` character (except of the end) - Returned string should have 1 character *(height)* border (use the same character as for number) + padding (1 character in height vertical and 2 horizontal with ` `) around borders and 1 character margin between "digits" *Suggestions and translations are welcome.*
# Build digit templates from the given examples in the instructions example_text = r""" //* ** **** **** ** ** ****** *\n //* *** ** ** ** ** ** ** ** *\n //* * ** ** ** ** ** ***** *\n //* ** ** ** ***** ** *\n //* ** ** ** ** ** ** *\n //* ****** ****** **** ** ***** *\n //@ @@ @@@@@@ @@@@ @@@@ @@@@ @\n //@ @@ @@ @@ @@ @@ @@ @@ @@ @@ @\n //@ @@@@ @@ @@@@ @@ @@ @@ @@ @\n //@ @@ @@ @@ @@@@ @@@@ @@ @@ @\n //@ @@ @@ @@ @@ @@ @@ @@ @@ @\n //@ @@@@ @@ @@@@ @@ @@@@ @\n """ # Clean/standardise the source text example_text = [ l[5:-4] for l in example_text.replace('@', '*').split('\n') if l.strip() ] # Extract the 7x6 super digits SUPER_DIGITS = [] for super_line in [example_text[:6], example_text[6:]]: for i in range(5): SUPER_DIGITS.append([line[i * 7:(i + 1) * 7] for line in super_line]) # Move the 0 from the end to start SUPER_DIGITS.insert(0, SUPER_DIGITS.pop(-1)) def print_number(number, char): # Pad to 5 digits digits = str(number).rjust(5, '0') # Add the digits (each one has a trailing space) lines = ['' for _ in range(6)] for d in digits: for i in range(6): lines[i] += SUPER_DIGITS[int(d)][i] # Justify lines = [f' {l} ' for l in lines] width = len(lines[0]) # Add header lines.insert(0, '*' * width) lines.insert(1, ' ' * width) # Add footer lines.append(' ' * width) lines.append('*' * width) # Add border lines = [f'*{l}*' for l in lines] # Concatenate and substitute return '\n'.join(lines).replace('*', char)
# Build digit templates from the given examples in the instructions example_text = r""" //* ** **** **** ** ** ****** *\n //* *** ** ** ** ** ** ** ** *\n //* * ** ** ** ** ** ***** *\n //* ** ** ** ***** ** *\n //* ** ** ** ** ** ** *\n //* ****** ****** **** ** ***** *\n //@ @@ @@@@@@ @@@@ @@@@ @@@@ @\n //@ @@ @@ @@ @@ @@ @@ @@ @@ @@ @\n //@ @@@@ @@ @@@@ @@ @@ @@ @@ @\n //@ @@ @@ @@ @@@@ @@@@ @@ @@ @\n //@ @@ @@ @@ @@ @@ @@ @@ @@ @\n //@ @@@@ @@ @@@@ @@ @@@@ @\n """ # Clean/standardise the source text example_text = [ l[5:-4] for l in example_text.replace('@', '*').split('\n') if l.strip() ] # Extract the 7x6 super digits SUPER_DIGITS = [] for super_line in [example_text[:6], example_text[6:]]: for i in range(5): SUPER_DIGITS.append([line[i * 7:(i + 1) * 7] for line in super_line]) # Move the 0 from the end to start SUPER_DIGITS.insert(0, SUPER_DIGITS.pop(-1)) def print_number(number, char): # Pad to 5 digits digits = str(number).rjust(5, '0') # Add the digits (each one has a trailing space) lines = ['' for _ in range(6)] for d in digits: for i in range(6): lines[i] += SUPER_DIGITS[int(d)][i] # Justify lines = [f' {l} ' for l in lines] width = len(lines[0]) # Add header lines.insert(0, '*' * width) lines.insert(1, ' ' * width) # Add footer lines.append(' ' * width) lines.append('*' * width) # Add border lines = [f'*{l}*' for l in lines] # Concatenate and substitute return '\n'.join(lines).replace('*', char)
train
APPS_structured
Bob has a server farm crunching numbers. He has `nodes` servers in his farm. His company has a lot of work to do. The work comes as a number `workload` which indicates how many jobs there are. Bob wants his servers to get an equal number of jobs each. If that is impossible, he wants the first servers to receive more jobs. He also wants the jobs sorted, so that the first server receives the first jobs. The way this works, Bob wants an array indicating which jobs are going to which servers. Can you help him distribute all this work as evenly as possible onto his servers? Example ------- Bob has `2` servers and `4` jobs. The first server should receive job 0 and 1 while the second should receive 2 and 3. ``` distribute(2, 4) # => [[0, 1], [2, 3]] ``` On a different occasion Bob has `3` servers and `3` jobs. Each should get just one. ``` distribute(3, 3) # => [[0], [1], [2]] ``` A couple of days go by and Bob sees a spike in jobs. Now there are `10`, but he hasn't got more than `4` servers available. He boots all of them. This time the first and second should get a job more than the third and fourth. ``` distribute(4, 10) # => [[0, 1, 2], [3, 4, 5], [6, 7], [8, 9]] ``` Input ----- Don't worry about invalid inputs. That is, `nodes > 0` and `workload > 0` and both will always be integers.
import numpy def distribute(nodes, workload): return [list(i) for i in numpy.array_split(numpy.array(range(0, workload)),nodes)]
import numpy def distribute(nodes, workload): return [list(i) for i in numpy.array_split(numpy.array(range(0, workload)),nodes)]
train
APPS_structured
Trigrams are a special case of the n-gram, where n is 3. One trigram is a continious sequence of 3 chars in phrase. [Wikipedia](https://en.wikipedia.org/wiki/Trigram) - return all trigrams for the given phrase - replace spaces with \_ - return an empty string for phrases shorter than 3 Example: trigrams('the quick red') == the he\_ e\_q \_qu qui uic ick ck\_ k\_r \_re red
def trigrams(phrase): phrase = phrase.replace(' ', '_') return ' '.join(''.join(xs) for xs in zip(phrase, phrase[1:], phrase[2:]))
def trigrams(phrase): phrase = phrase.replace(' ', '_') return ' '.join(''.join(xs) for xs in zip(phrase, phrase[1:], phrase[2:]))
train
APPS_structured
The chef is placing the laddus on the large square plat. The plat has the side of length N. Each laddu takes unit sq.unit area. Cheffina comes and asks the chef one puzzle to the chef as, how many squares can be formed in this pattern with all sides of new square are parallel to the original edges of the plate. -----Input:----- - First-line will contain $T$, the number of test cases. Then the test cases follow. - Each test case contains a single line of input, one integer $N$. -----Output:----- For each test case, output in a single line answer as maximum squares on plate satisfying the condition. -----Constraints----- - $1 \leq T \leq 1000$ - $1 \leq N \leq 10^5$ -----Sample Input:----- 2 1 2 -----Sample Output:----- 1 5 -----EXPLANATION:----- For 1) Only 1 Square For 2) 4 squares with area 1 sq.unit 1 square with area 4 sq.unit
for _ in range(int(input())): n = int(input()) a = (n*(n+1)*(2*n+1))//6 print(a)
for _ in range(int(input())): n = int(input()) a = (n*(n+1)*(2*n+1))//6 print(a)
train
APPS_structured
Roma is programmer and he likes memes about IT, Maxim is chemist and he likes memes about chemistry, Danik is designer and he likes memes about design, and Vlad likes all other memes. ___ You will be given a meme (string), and your task is to identify its category, and send it to the right receiver: `IT - 'Roma'`, `chemistry - 'Maxim'`, `design - 'Danik'`, or `other - 'Vlad'`. IT meme has letters `b, u, g`. Chemistry meme has letters `b, o, o, m`. Design meme has letters `e, d, i, t, s`. If there is more than 1 possible answer, the earliest match should be chosen. **Note:** letters are case-insensetive and should come in the order specified above. ___ ## Examples: (Matching letters are surrounded by curly braces for readability.) ``` this is programmer meme {b}ecause it has b{ug} this is also program{bu}r meme {g}ecause it has needed key word this is {ed}s{i}gner meme cause i{t} ha{s} key word this could {b}e chemistry meme b{u}t our{g}Gey word 'boom' is too late instead of this could {b}e chemistry meme but {o}ur gey w{o}rd 'boo{m}' is too late ```
def memesorting(s): order_p,p,ini_p,order_c,c,int_c, order_d,d,int_d = {0: 'b', 1: 'u', 2: 'g'},"",0,{0: 'b', 1: 'o', 2: 'o', 3: 'm'},"",0,{0: 'e', 1: 'd', 2: 'i', 3: 't', 4: 's'},"",0 for i in s.lower(): if i == order_p[ini_p] : p += i ; ini_p += 1 if i == order_c[int_c] : c += i ; int_c += 1 if i == order_d[int_d] : d += i ; int_d += 1 for k in range(3): if ["bug", "boom", "edits"][k] == [p, c, d][k] : return ["Roma", "Maxim", "Danik"][k] return "Vlad"
def memesorting(s): order_p,p,ini_p,order_c,c,int_c, order_d,d,int_d = {0: 'b', 1: 'u', 2: 'g'},"",0,{0: 'b', 1: 'o', 2: 'o', 3: 'm'},"",0,{0: 'e', 1: 'd', 2: 'i', 3: 't', 4: 's'},"",0 for i in s.lower(): if i == order_p[ini_p] : p += i ; ini_p += 1 if i == order_c[int_c] : c += i ; int_c += 1 if i == order_d[int_d] : d += i ; int_d += 1 for k in range(3): if ["bug", "boom", "edits"][k] == [p, c, d][k] : return ["Roma", "Maxim", "Danik"][k] return "Vlad"
train
APPS_structured
### Task Yes, your eyes are no problem, this is toLoverCase (), not toLowerCase (), we want to make the world full of love. ### What do we need to do? You need to add a prototype function to the String, the name is toLoverCase. Function can convert the letters in the string, converted to "L", "O", "V", "E", if not the letter, don't change it. ### How to convert? : ``` "love!".toLoverCase()="EVOL!" ``` more example see the testcases. ### Series: - [Bug in Apple](http://www.codewars.com/kata/56fe97b3cc08ca00e4000dc9) - [Father and Son](http://www.codewars.com/kata/56fe9a0c11086cd842000008) - [Jumping Dutch act](http://www.codewars.com/kata/570bcd9715944a2c8e000009) - [Planting Trees](http://www.codewars.com/kata/5710443187a36a9cee0005a1) - [Give me the equation](http://www.codewars.com/kata/56fe9b65cc08cafbc5000de3) - [Find the murderer](http://www.codewars.com/kata/570f3fc5b29c702c5500043e) - [Reading a Book](http://www.codewars.com/kata/570ca6a520c69f39dd0016d4) - [Eat watermelon](http://www.codewars.com/kata/570df12ce6e9282a7d000947) - [Special factor](http://www.codewars.com/kata/570e5d0b93214b1a950015b1) - [Guess the Hat](http://www.codewars.com/kata/570ef7a834e61306da00035b) - [Symmetric Sort](http://www.codewars.com/kata/5705aeb041e5befba20010ba) - [Are they symmetrical?](http://www.codewars.com/kata/5705cc3161944b10fd0004ba) - [Max Value](http://www.codewars.com/kata/570771871df89cf59b000742) - [Trypophobia](http://www.codewars.com/kata/56fe9ffbc25bf33fff000f7c) - [Virus in Apple](http://www.codewars.com/kata/5700af83d1acef83fd000048) - [Balance Attraction](http://www.codewars.com/kata/57033601e55d30d3e0000633) - [Remove screws I](http://www.codewars.com/kata/5710a50d336aed828100055a) - [Remove screws II](http://www.codewars.com/kata/5710a8fd336aed00d9000594) - [Regular expression compression](http://www.codewars.com/kata/570bae4b0237999e940016e9) - [Collatz Array(Split or merge)](http://www.codewars.com/kata/56fe9d579b7bb6b027000001) - [Tidy up the room](http://www.codewars.com/kata/5703ace6e55d30d3e0001029) - [Waiting for a Bus](http://www.codewars.com/kata/57070eff924f343280000015)
import string alpha = {x: i for i, x in enumerate(string.ascii_lowercase)} def to_lover_case(s): return ''.join( ('LOVE'[alpha[c] % 4] if c.islower() else c) for c in s.lower() )
import string alpha = {x: i for i, x in enumerate(string.ascii_lowercase)} def to_lover_case(s): return ''.join( ('LOVE'[alpha[c] % 4] if c.islower() else c) for c in s.lower() )
train
APPS_structured
# The Invitation Most of us played with toy blocks growing up. It was fun and you learned stuff. So what else can you do but rise to the challenge when a 3-year old exclaims, "Look, I made a square!", then pointing to a pile of blocks, "Can _you_ do it?" # These Blocks Just to play along, of course we'll be viewing these blocks in two dimensions. Depth now being disregarded, it turns out the pile has four different sizes of block: `1x1`, `1x2`, `1x3`, and `1x4`. The smallest one represents the area of a square, the other three are rectangular, and all differ by their width. Integers matching these four widths are used to represent the blocks in the input. # This Square Well, the kid made a `4x4` square from this pile, so you'll have to match that. Noticing the way they fit together, you realize the structure must be built in fours rows, one row at a time, where the blocks must be placed horizontally. With the known types of block, there are five types of row you could build: * 1 four-unit block * 1 three-unit block plus 1 one-unit bock (in either order) * 2 two-unit blocks * 1 two-unit block plus 2 one-unit blocks (in any order) * 4 one-unit blocks Amounts for all four of the block sizes in the pile will each vary from `0` to `16`. The total size of the pile will also vary from `0` to `16`. The order of rows is irrelevant. A valid square doesn't have to use up all the given blocks. # Some Examples Given `1, 3, 2, 2, 4, 1, 1, 3, 1, 4, 2` there are many ways you could construct a square. Here are three possibilities, as described by their four rows: * 1 four-unit block * 2 two-unit blocks * 1 four-unit block * 4 one-unit blocks > * 1 three-unit block plus 1 one-unit block * 2 two-unit blocks * 1 four-unit block * 1 one-unit block plus 1 three-unit block > * 2 two-unit blocks * 1 three-unit block plus 1 one-unit block * 1 four-unit block * 2 one-unit blocks plus 1 two-unit block > Given `1, 3, 2, 4, 3, 3, 2` there is no way to complete the task, as you could only build three rows of the correct length. The kid will not be impressed. * 2 two-unit blocks * 1 three-unit block plus 1 one-unit block * 1 four-unit block * (here only sadness) > # Input ```python blocks ~ a random list of integers (1 <= x <= 4) ``` # Output ```python True or False ~ whether you can build a square ``` # Enjoy! If interested, I also have [this kata](https://www.codewars.com/kata/5cb7baa989b1c50014a53333) as well as [this other kata](https://www.codewars.com/kata/5cb5eb1f03c3ff4778402099) to consider solving.
def build_square(blocks): a = 4 b = blocks.count(1) c = blocks.count(2) d = blocks.count(3) e = blocks.count(4) a -= e if a <= 0: return True while b > 0 and d > 0: b-=1 d-=1 a-=1 while c > 0 and b > 1: b-=2 c-=1 a-=1 while b > 3: b-=4 a-=1 while c > 1: c-=2 a-=1 if a <= 0: return True else: return False
def build_square(blocks): a = 4 b = blocks.count(1) c = blocks.count(2) d = blocks.count(3) e = blocks.count(4) a -= e if a <= 0: return True while b > 0 and d > 0: b-=1 d-=1 a-=1 while c > 0 and b > 1: b-=2 c-=1 a-=1 while b > 3: b-=4 a-=1 while c > 1: c-=2 a-=1 if a <= 0: return True else: return False
train
APPS_structured
Given a credit card number we can determine who the issuer/vendor is with a few basic knowns. ```if:python Complete the function `get_issuer()` that will use the values shown below to determine the card issuer for a given card number. If the number cannot be matched then the function should return the string `Unknown`. ``` ```if-not:python Complete the function `getIssuer()` that will use the values shown below to determine the card issuer for a given card number. If the number cannot be matched then the function should return the string `Unknown`. ``` ```if:typescript Where `Issuer` is defined with the following enum type. ~~~typescript enum Issuer { VISA = 'VISA', AMEX = 'AMEX', Mastercard = 'Mastercard', Discover = 'Discover', Unknown = 'Unknown', } ~~~ ``` ```markdown | Card Type | Begins With | Number Length | |------------|----------------------|---------------| | AMEX | 34 or 37 | 15 | | Discover | 6011 | 16 | | Mastercard | 51, 52, 53, 54 or 55 | 16 | | VISA | 4 | 13 or 16 | ``` ```if:c,cpp **C/C++ note:** The return value in C is not freed. ``` ## Examples ```if-not:python ~~~js getIssuer(4111111111111111) == "VISA" getIssuer(4111111111111) == "VISA" getIssuer(4012888888881881) == "VISA" getIssuer(378282246310005) == "AMEX" getIssuer(6011111111111117) == "Discover" getIssuer(5105105105105100) == "Mastercard" getIssuer(5105105105105106) == "Mastercard" getIssuer(9111111111111111) == "Unknown" ~~~ ``` ```if:python ~~~py get_issuer(4111111111111111) == "VISA" get_issuer(4111111111111) == "VISA" get_issuer(4012888888881881) == "VISA" get_issuer(378282246310005) == "AMEX" get_issuer(6011111111111117) == "Discover" get_issuer(5105105105105100) == "Mastercard" get_issuer(5105105105105106) == "Mastercard" get_issuer(9111111111111111) == "Unknown" ~~~ ```
def get_issuer(number): s = str(number) if int(s[0:2]) in (34,37) and len(s) == 15: return 'AMEX' elif int(s[0:4]) == 6011 and len(s) == 16: return 'Discover' elif int(s[0:2]) in (51, 52, 53, 54, 55) and len(s) == 16: return 'Mastercard' elif int(s[0]) == 4 and len(s) in (13,16): return 'VISA' return 'Unknown'
def get_issuer(number): s = str(number) if int(s[0:2]) in (34,37) and len(s) == 15: return 'AMEX' elif int(s[0:4]) == 6011 and len(s) == 16: return 'Discover' elif int(s[0:2]) in (51, 52, 53, 54, 55) and len(s) == 16: return 'Mastercard' elif int(s[0]) == 4 and len(s) in (13,16): return 'VISA' return 'Unknown'
train
APPS_structured
You are a king and you are at war. If the enemy breaks through your frontline you lose. Enemy can break the line only if the sum of morale of any $K$ continuous soldiers is strictly less than $M$. So, you being a motivational orator decides to boost their morale by giving a speech. On hearing it morale of a soldier multiplies by $X$ which depends on you and your speech (i.e. $X$ can be any positive value) but atmost only $K$ continuous speakers can hear your speech. N soldiers are standing on the frontline with $A[i]$ morale. Determine the minimum number of speeches you need to give. -----Input:----- The first line contains three space seperated integers $N,K,M$. The next line contains $N$ space integers, ith of which denotes the morale of $ith$ soldier. -----Output:----- Output the minimum number of speeches required. In case if it is impossible to achieve, print $-1$. -----Constraints:----- $1 \leq N,M \leq 10^5$ $1 \leq k \leq N$ $0 \leq Ai \leq 10^5$ -----Sample Input:----- 6 2 5 1 1 1 1 1 1 -----Sample Output:----- 2 -----Explanation:----- We multiply 2nd ,3rd and 5th,6th by 5. Resulting array will be 1 5 5 1 5 5.
N,K,M=list(map(int,input().split())) A=list(map(int,input().split())) tt=0 i=0 while(i<N): k1=-1 j=0 c=0 while(j<K and i<N): if (A[i]!=0): k1=i c=c+A[i] i=i+1 j=j+1 while(c>=M and i<N): if (A[i]!=0): k1=i c=c+A[i]-A[i-K] i=i+1 if (k1<0): tt=-1 break elif (c<M and j==K): tt=tt+1 i=k1+K #print(i,c) print(tt)
N,K,M=list(map(int,input().split())) A=list(map(int,input().split())) tt=0 i=0 while(i<N): k1=-1 j=0 c=0 while(j<K and i<N): if (A[i]!=0): k1=i c=c+A[i] i=i+1 j=j+1 while(c>=M and i<N): if (A[i]!=0): k1=i c=c+A[i]-A[i-K] i=i+1 if (k1<0): tt=-1 break elif (c<M and j==K): tt=tt+1 i=k1+K #print(i,c) print(tt)
train
APPS_structured
Jon and Joe have received equal marks in the school examination. But, they won't reconcile in peace when equated with each other. To prove his might, Jon challenges Joe to write a program to find all possible number combos that sum to a given number. While unsure whether he would be able to accomplish this feat or not, Joe accpets the challenge. Being Joe's friend, your task is to help him out. # Task Create a function `combos`, that accepts a single positive integer `num` (30 > `num` > 0) and returns an array of arrays of positive integers that sum to `num`. # Notes 1. Sub-arrays may or may not have their elements sorted. 2. The order of sub-arrays inside the main array does not matter. 3. For an optimal solution, the following operation should complete within 6000ms. # Sample
def combos(n): def partition(residue, acc): if residue == 0: yield acc[1:] else: for part in range(acc[-1], residue + 1): for result in partition(residue - part, acc + [part]): yield result return list(partition(n, [1]))
def combos(n): def partition(residue, acc): if residue == 0: yield acc[1:] else: for part in range(acc[-1], residue + 1): for result in partition(residue - part, acc + [part]): yield result return list(partition(n, [1]))
train
APPS_structured
# Task Given a string `str`, reverse it omitting all non-alphabetic characters. # Example For `str = "krishan"`, the output should be `"nahsirk"`. For `str = "ultr53o?n"`, the output should be `"nortlu"`. # Input/Output - `[input]` string `str` A string consists of lowercase latin letters, digits and symbols. - `[output]` a string
def reverse_letter(string): array = list(filter(str.isalpha, string)) new_list = ''.join(array) return new_list[::-1]
def reverse_letter(string): array = list(filter(str.isalpha, string)) new_list = ''.join(array) return new_list[::-1]
train
APPS_structured
# Task Alireza and Ali have a `3×3 table` and playing on that. they have 4 table(2×2) A,B,C and D in this table. At beginning all of 9 numbers in 3×3 table is zero. Alireza in each move choose a 2×2 table from A, B, C and D and increase all of 4 numbers in that by one. He asks Ali, how much he increase table A, B, C and D. (if he cheats you should return `[-1]`) Your task is to help Ali. # Example For ``` table= [[1,2,1], [2,4,2], [1,2,1]]``` The result should be `[1,1,1,1]` For: ``` Table= [[3,7,4], [5,16,11], [2,9,7]]``` The result should be `[3,4,2,7]` # Input/Output - `[input]` 2D integer array `table` `3×3` table. - `[output]` an integer array
def table_game(t): return [t[0][0],t[0][2],t[2][0],t[2][2]] if (t[0][1]+t[2][1])==(t[1][0]+t[1][2])==t[1][1] else [-1]
def table_game(t): return [t[0][0],t[0][2],t[2][0],t[2][2]] if (t[0][1]+t[2][1])==(t[1][0]+t[1][2])==t[1][1] else [-1]
train
APPS_structured
Bear Limak has a sequence of N non-negative integers A1, A2, ..., AN. He defines the score of a segment (consecutive subsequence) as its sum of elements modulo P (not necessarily prime). Find the maximum score of a non-empty segment, and also find the number of segments with this maximum score. -----Input----- First line of the input contains an integer T denoting the number of test cases. The description of T test cases follows. For each test case, the first line of the input contains two space separated integers, N and P. The second line contains N space separated integers denoting the sequence. -----Output----- For each test case, output two space separated integers denoting the maximum score of a segment and the number of segments with the score, respectively. -----Constraints----- - 1 ≤ T ≤ 10 - 1 ≤ N ≤ 105 - 1 ≤ P ≤ 109 - 0 ≤ Ai ≤ 109 Subtask #1: (25 points) - 1 ≤ N ≤ 100 Subtask #2: (25 points) - 1 ≤ N ≤ 1000 Subtask #3: (50 points) - original constraints -----Example----- Input: 4 2 3 1 2 3 5 2 4 3 3 100 1 3 5 4 3 1 2 3 4 Output: 2 1 4 2 9 1 2 2 -----Explanation----- Example case 1. There are three segments - [1], [2] and [1, 2]. Sum of these segments are 1, 2 and 3 respectively. Sum of these segments modulo 3 will be 1, 2 and 0. Maximum score among these is 2. There is also only one segment with this score. Example case 2. There are six segments - [2], [4], [3], [2, 4], [4, 3] and [2, 4, 3]. Sum of these segments are 2, 4, 3, 6, 7, 9 respectively. Sum of these segments modulo 5 will be 2, 4, 3, 1, 2, 4. Maximum score among these is 4. And there are two segments with this score.
for _ in range(int(input())): n,m=input().split() n,m=int(n),int(m) x=y=c=0 l=list(map(int,input().split())) for i in range(n): for j in range(i,n): x=x+l[j] if (x%m)>y: y=x%m c=1 elif y==(x%m): c+=1 x = 0 print(y,c)
for _ in range(int(input())): n,m=input().split() n,m=int(n),int(m) x=y=c=0 l=list(map(int,input().split())) for i in range(n): for j in range(i,n): x=x+l[j] if (x%m)>y: y=x%m c=1 elif y==(x%m): c+=1 x = 0 print(y,c)
train
APPS_structured
=====Function Descriptions===== If we want to add a single element to an existing set, we can use the .add() operation. It adds the element to the set and returns 'None'. =====Example===== >>> s = set('HackerRank') >>> s.add('H') >>> print s set(['a', 'c', 'e', 'H', 'k', 'n', 'r', 'R']) >>> print s.add('HackerRank') None >>> print s set(['a', 'c', 'e', 'HackerRank', 'H', 'k', 'n', 'r', 'R']) =====Problem Statement===== Apply your knowledge of the .add() operation to help your friend Rupal. Rupal has a huge collection of country stamps. She decided to count the total number of distinct country stamps in her collection. She asked for your help. You pick the stamps one by one from a stack of N country stamps. Find the total number of distinct country stamps. =====Input Format===== The fist line contains an integer N, the total number of country stamps. The next N lines contains the name of the country where the stamp is from. =====Constraints===== 0<N<1000 =====Output Format===== Output the total number of distinct country stamps on a single line.
n = int(input()) country_set = set() for i in range(n): country_name = input() country_set.add(country_name) print((len(country_set)))
n = int(input()) country_set = set() for i in range(n): country_name = input() country_set.add(country_name) print((len(country_set)))
train
APPS_structured
As [breadcrumb menùs](https://en.wikipedia.org/wiki/Breadcrumb_%28navigation%29) are quite popular today, I won't digress much on explaining them, leaving the wiki link to do all the dirty work in my place. What might not be so trivial is instead to get a decent breadcrumb from your current url. For this kata, your purpose is to create a function that takes a url, strips the first part (labelling it always `HOME`) and then builds it making each element but the last a `` element linking to the relevant path; last has to be a `` element getting the `active` `class`. All elements need to be turned to uppercase and separated by a separator, given as the second parameter of the function; the last element can terminate in some common extension like `.html`, `.htm`, `.php` or `.asp`; if the name of the last element is `index`.something, you treat it as if it wasn't there, sending users automatically to the upper level folder. A few examples can be more helpful than thousands of words of explanation, so here you have them: ```python generate_bc("mysite.com/pictures/holidays.html", " : ") == 'HOME : PICTURES : HOLIDAYS' generate_bc("www.codewars.com/users/GiacomoSorbi", " / ") == 'HOME / USERS / GIACOMOSORBI' generate_bc("www.microsoft.com/docs/index.htm", " * ") == 'HOME * DOCS' ``` Seems easy enough? Well, probably not so much, but we have one last extra rule: if one element (other than the root/home) is longer than 30 characters, you have to shorten it, acronymizing it (i.e.: taking just the initials of every word); url will be always given in the format `this-is-an-element-of-the-url` and you should ignore words in this array while acronymizing: `["the","of","in","from","by","with","and", "or", "for", "to", "at", "a"]`; a url composed of more words separated by `-` and equal or less than 30 characters long needs to be just uppercased with hyphens replaced by spaces. Ignore anchors (`www.url.com#lameAnchorExample`) and parameters (`www.url.com?codewars=rocks&pippi=rocksToo`) when present. Examples: ```python generate_bc("mysite.com/very-long-url-to-make-a-silly-yet-meaningful-example/example.htm", " > ") == 'HOME > VLUMSYME > EXAMPLE' generate_bc("www.very-long-site_name-to-make-a-silly-yet-meaningful-example.com/users/giacomo-sorbi", " + ") == 'HOME + USERS + GIACOMO SORBI' ``` You will always be provided **valid url** to webpages **in common formats**, so you probably shouldn't bother validating them. If you like to test yourself with actual work/interview related kata, please also consider this one about building [a string filter for Angular.js](http://www.codewars.com/kata/number-shortening-filter). _Special thanks to [the colleague](http://www.codewars.com/users/jury89) that, seeing my code and commenting that I worked on that as if it was I was on CodeWars, made me realize that it could be indeed a good idea for a kata_ :)
from typing import List, Tuple from urllib.parse import urlparse import re def generate_bc(url: str, separator: str) -> str: # print(f'url = {repr(url)}') # print(f'separator = {repr(separator)}') home_url = '<a href="/">HOME</a>' # type: str (path_components, last_path) = split_url(url) if last_path.startswith("index."): last_path = '' last_path = re.sub(r"(.html|.htm|.php|.asp)$", "", last_path) if not path_components: # empty if not last_path: return '<span class="active">HOME</span>' elif not last_path: last_path = path_components.pop() return separator.join([ home_url, *generate_bc_middle(path_components), generate_bc_last(last_path) ]) def generate_bc_middle(path_components: List[str]) -> List[str]: # return ['<a href="/important/">IMPORTANT</a>', '<a href="/important/confidential/">CONFIDENTIAL</a>'] cumulative_path = '' result: List[str] = [] for path in path_components: cumulative_path = (cumulative_path + '/' + path) if cumulative_path else path bc = path.replace('-', ' ').upper() if len(path) <= 30 else acronymyze(path) result.append(f'<a href="/{cumulative_path}/">{bc}</a>') return result def acronymyze(long_word: str) -> str: """ Shorten it, acronymizing it (i.e.: taking just the initials of every word) """ ignore_words = [ "the", "of", "in", "from", "by", "with", "and", "or", "for", "to", "at", "a" ] return ''.join(word[0].upper() for word in long_word.split('-') if word not in ignore_words) def generate_bc_last(last_path: str) -> str: if len(last_path) > 30: bc = acronymyze(last_path) else: bc = last_path.replace('-', ' ').upper() return f'<span class="active">{bc}</span>' def split_url(url: str) -> Tuple[List[str], str]: """ Returns a tuple by splitting the given url url = 'mysite.com/years/pictures/holidays.html' returns a tuple ([years,pictures], 'holidays.html') """ # Example url = 'https://mysite.com/years/pictures/holidays.html' parse_result = urlparse(url) # ParseResult(scheme='https', netloc='mysite.com', path='/years/pictures/holidays.html', # params='', query='', fragment='') # urlparse recognizes a netloc only if it is properly introduced by ‘//’. # Otherwise the input is presumed to be a relative URL and thus to start # with a path component. # Redo urlparse to make sure that parse_result.path has only filepath and not hostpath part if not parse_result.scheme and not url.startswith('//'): parse_result = urlparse('//' + url) if not parse_result.path: # empty path path_components = [] last_path = '' elif parse_result.path.startswith('/'): path_components = [ component for component in parse_result.path.split("/") ] path_components.pop(0) # Remove '' # ['', 'years', 'pictures', 'holidays.html'] last_path = path_components.pop() # type: str else: raise Exception("Invalid url") # (['years', 'pictures'], 'holidays.html') return (path_components, last_path)
from typing import List, Tuple from urllib.parse import urlparse import re def generate_bc(url: str, separator: str) -> str: # print(f'url = {repr(url)}') # print(f'separator = {repr(separator)}') home_url = '<a href="/">HOME</a>' # type: str (path_components, last_path) = split_url(url) if last_path.startswith("index."): last_path = '' last_path = re.sub(r"(.html|.htm|.php|.asp)$", "", last_path) if not path_components: # empty if not last_path: return '<span class="active">HOME</span>' elif not last_path: last_path = path_components.pop() return separator.join([ home_url, *generate_bc_middle(path_components), generate_bc_last(last_path) ]) def generate_bc_middle(path_components: List[str]) -> List[str]: # return ['<a href="/important/">IMPORTANT</a>', '<a href="/important/confidential/">CONFIDENTIAL</a>'] cumulative_path = '' result: List[str] = [] for path in path_components: cumulative_path = (cumulative_path + '/' + path) if cumulative_path else path bc = path.replace('-', ' ').upper() if len(path) <= 30 else acronymyze(path) result.append(f'<a href="/{cumulative_path}/">{bc}</a>') return result def acronymyze(long_word: str) -> str: """ Shorten it, acronymizing it (i.e.: taking just the initials of every word) """ ignore_words = [ "the", "of", "in", "from", "by", "with", "and", "or", "for", "to", "at", "a" ] return ''.join(word[0].upper() for word in long_word.split('-') if word not in ignore_words) def generate_bc_last(last_path: str) -> str: if len(last_path) > 30: bc = acronymyze(last_path) else: bc = last_path.replace('-', ' ').upper() return f'<span class="active">{bc}</span>' def split_url(url: str) -> Tuple[List[str], str]: """ Returns a tuple by splitting the given url url = 'mysite.com/years/pictures/holidays.html' returns a tuple ([years,pictures], 'holidays.html') """ # Example url = 'https://mysite.com/years/pictures/holidays.html' parse_result = urlparse(url) # ParseResult(scheme='https', netloc='mysite.com', path='/years/pictures/holidays.html', # params='', query='', fragment='') # urlparse recognizes a netloc only if it is properly introduced by ‘//’. # Otherwise the input is presumed to be a relative URL and thus to start # with a path component. # Redo urlparse to make sure that parse_result.path has only filepath and not hostpath part if not parse_result.scheme and not url.startswith('//'): parse_result = urlparse('//' + url) if not parse_result.path: # empty path path_components = [] last_path = '' elif parse_result.path.startswith('/'): path_components = [ component for component in parse_result.path.split("/") ] path_components.pop(0) # Remove '' # ['', 'years', 'pictures', 'holidays.html'] last_path = path_components.pop() # type: str else: raise Exception("Invalid url") # (['years', 'pictures'], 'holidays.html') return (path_components, last_path)
train
APPS_structured
# Summation Write a program that finds the summation of every number from 1 to num. The number will always be a positive integer greater than 0. For example: ```if-not:racket ~~~ summation(2) -> 3 1 + 2 summation(8) -> 36 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 ~~~ ``` ```if:racket ~~~racket (summation 2) ; 3 (+ 1 2) (summation 8) ; 36 (+ 1 2 3 4 5 6 7 8) ~~~ ```
def summation(num, sums=0): if num == 0: return sums else: return summation(num-1, sums + num)
def summation(num, sums=0): if num == 0: return sums else: return summation(num-1, sums + num)
train
APPS_structured
You have n binary tree nodes numbered from 0 to n - 1 where node i has two children leftChild[i] and rightChild[i], return true if and only if all the given nodes form exactly one valid binary tree. If node i has no left child then leftChild[i] will equal -1, similarly for the right child. Note that the nodes have no values and that we only use the node numbers in this problem. Example 1: Input: n = 4, leftChild = [1,-1,3,-1], rightChild = [2,-1,-1,-1] Output: true Example 2: Input: n = 4, leftChild = [1,-1,3,-1], rightChild = [2,3,-1,-1] Output: false Example 3: Input: n = 2, leftChild = [1,0], rightChild = [-1,-1] Output: false Example 4: Input: n = 6, leftChild = [1,-1,-1,4,-1,-1], rightChild = [2,-1,-1,5,-1,-1] Output: false Constraints: 1 <= n <= 10^4 leftChild.length == rightChild.length == n -1 <= leftChild[i], rightChild[i] <= n - 1
class Solution: def validateBinaryTreeNodes(self, n: int, left_children: List[int], right_children: List[int]) -> bool: root = self.find_root(n, left_children, right_children) if root == -1: return False return self.helper(root, n, left_children, right_children) def find_root(self, n, left_children, right_children): left_counter = collections.Counter(left_children) right_counter = collections.Counter(right_children) for i in range(n): if i not in left_counter and i not in right_counter: return i return -1 def helper(self, root, n, left_children, right_children): visited = set() if not self.dfs(root, left_children, right_children, visited): return False #print(visited) return len(visited) == n def dfs(self, root, left_children, right_children, visited): if root == -1: return True if root in visited: return False visited.add(root) left = self.dfs(left_children[root], left_children, right_children, visited) right = self.dfs(right_children[root], left_children, right_children, visited) return left and right
class Solution: def validateBinaryTreeNodes(self, n: int, left_children: List[int], right_children: List[int]) -> bool: root = self.find_root(n, left_children, right_children) if root == -1: return False return self.helper(root, n, left_children, right_children) def find_root(self, n, left_children, right_children): left_counter = collections.Counter(left_children) right_counter = collections.Counter(right_children) for i in range(n): if i not in left_counter and i not in right_counter: return i return -1 def helper(self, root, n, left_children, right_children): visited = set() if not self.dfs(root, left_children, right_children, visited): return False #print(visited) return len(visited) == n def dfs(self, root, left_children, right_children, visited): if root == -1: return True if root in visited: return False visited.add(root) left = self.dfs(left_children[root], left_children, right_children, visited) right = self.dfs(right_children[root], left_children, right_children, visited) return left and right
train
APPS_structured