input
stringlengths
50
13.9k
output_program
stringlengths
5
655k
output_answer
stringlengths
5
655k
split
stringclasses
1 value
dataset
stringclasses
1 value
It is well-known that the elephants are afraid of mouses. The Little Elephant from the Zoo of Lviv is not an exception. The Little Elephant is on a board A of n rows and m columns (0-based numeration). At the beginning he is in cell with coordinates (0; 0) and he wants to go to cell with coordinates (n-1; m-1). From cell (x; y) Little Elephant can go either to (x+1; y) or (x; y+1). Each cell of the board contains either 1 or 0. If A[i][j] = 1, then there is a single mouse in cell (i; j). Mouse at cell (i; j) scared Little Elephants if and only if during the path there was at least one such cell (x; y) (which belongs to that path) and |i-x| + |j-y| <= 1. Little Elephant wants to find some correct path from (0; 0) to (n-1; m-1) such that the number of mouses that have scared the Little Elephant is minimal possible. Print that number. -----Input----- First line contains single integer T - the number of test cases. Then T test cases follow. First line of each test case contain pair of integers n and m - the size of the board. Next n lines contain n strings, each of size m and consisted of digits 0 and 1. -----Output----- In T lines print T integer - the answers for the corresponding test. -----Constraints----- 1 <= T <= 50 2 <= n, m <= 100 -----Example----- Input: 2 3 9 001000001 111111010 100100100 7 9 010101110 110110111 010011111 100100000 000010100 011011000 000100101 Output: 9 10 -----Explanation----- Example case 1: The optimized path is: (0, 0) -> (0, 1) -> (0, 2) -> (0, 3) -> (0, 4) -> (0, 5) -> (0, 6) -> (0, 7) -> (0, 8) -> (1, 8) -> (2, 8). The mouses that scared the Little Elephant are at the following cells: (1, 0), (1, 1), (1, 2), (1, 3), (1, 4), (1, 5), (1, 7), (0, 2), (0, 8). Example case 2: The optimized path is: (0, 0) -> (1, 0) -> (1, 1) -> (2, 1) -> (2, 2) -> (3, 2) -> (3, 3) -> (4, 3) -> (4, 4) -> (5, 4) -> (5, 5) -> (6, 5) -> (6, 6) -> (6, 7) -> (6, 8). The 10 mouses that scared the Little Elephant are at the following cells: (0, 1), (1, 0), (1, 1), (2, 1), (3, 3), (4, 4), (5, 4), (5, 5), (6, 6), (6, 8).
from collections import defaultdict from itertools import product def solve(mouse,n,m): # shadow matrix will contains the count of mice which affect (i,j) position # if there is a mice at position (i,j) then in shadow matrix it will affect         all four adjacent blocks shadow=[[0 for i in range(m)]for j in range(n)] for i,j in product(list(range(n)),list(range(m))): if mouse[i][j]==1: if i>0: shadow[i-1][j]+=1 if j>0: shadow[i][j-1]+=1 if i<n-1: shadow[i+1][j]+=1 if j<m-1: shadow[i][j+1]+=1 # dp is a dictionary which contains a tuple of 3 values (i,j,0)=>we are         coming at destination (i,j) from left side # (i,j,1)=> we are coming at destination (i,j) from top dp=defaultdict(int) # dp[(0,0,0)]=dp[(0,0,1)]=shadow[0][0]-mouse[0][0] # fill only first row # in first row we can only reach at (0,j) from (0,j-1,0) as we can't come         from top. # so here we will assign count of mices which will affect current cell        (shadow[0][i]) + previous result i.e,(0,j-1,0) and # if mouse is in the current cell than we have to subtract it bcoz we have         add it twice i.e, when we enter at this block # and when we leave this block for i in range(1,m): dp[(0,i,0)]=dp[(0,i,1)]=shadow[0][i]-mouse[0][i]+dp[(0,i-1,0)] # same goes for first column # we can only come at (i,0) from (i-1,0) i.e top for i in range(1,n): dp[(i,0,0)]=dp[(i,0,1)]=shadow[i][0]-mouse[i][0]+dp[(i-1,0,1)] # for rest of the blocks # for a block (i,j) we have to add shadow[i][j] and subtract mouse[i][j]         from it for double counting # now for each block we have two choices, either take its previous block         with same direction or take previous block with different # direction and subtract corner double counted mouse. We have to take min of         both to find optimal answer for i,j in product(list(range(1,n)),list(range(1,m))): a=shadow[i][j]-mouse[i][j] b=a a+=min(dp[(i,j-1,0)],dp[(i,j-1,1)]-mouse[i-1][j]) b+=min(dp[(i-1,j,1)],dp[(i-1,j,0)]-mouse[i][j-1]) dp[(i,j,0)]=a dp[(i,j,1)]=b # what if [0][0] and [n-1][m-1] have mice, so we have to add them as we         haven't counted them yet. return min(dp[(n-1,m-1,0)],dp[(n-1,m-1,1)])+mouse[0][0]+mouse[n-1][m-1] for _ in range(int(input())): n,m=list(map(int,input().split( ))) mouse=[] for i in range(n): x=input() mouse.append(list(map(int,x))) print(solve(mouse,n,m))
from collections import defaultdict from itertools import product def solve(mouse,n,m): # shadow matrix will contains the count of mice which affect (i,j) position # if there is a mice at position (i,j) then in shadow matrix it will affect         all four adjacent blocks shadow=[[0 for i in range(m)]for j in range(n)] for i,j in product(list(range(n)),list(range(m))): if mouse[i][j]==1: if i>0: shadow[i-1][j]+=1 if j>0: shadow[i][j-1]+=1 if i<n-1: shadow[i+1][j]+=1 if j<m-1: shadow[i][j+1]+=1 # dp is a dictionary which contains a tuple of 3 values (i,j,0)=>we are         coming at destination (i,j) from left side # (i,j,1)=> we are coming at destination (i,j) from top dp=defaultdict(int) # dp[(0,0,0)]=dp[(0,0,1)]=shadow[0][0]-mouse[0][0] # fill only first row # in first row we can only reach at (0,j) from (0,j-1,0) as we can't come         from top. # so here we will assign count of mices which will affect current cell        (shadow[0][i]) + previous result i.e,(0,j-1,0) and # if mouse is in the current cell than we have to subtract it bcoz we have         add it twice i.e, when we enter at this block # and when we leave this block for i in range(1,m): dp[(0,i,0)]=dp[(0,i,1)]=shadow[0][i]-mouse[0][i]+dp[(0,i-1,0)] # same goes for first column # we can only come at (i,0) from (i-1,0) i.e top for i in range(1,n): dp[(i,0,0)]=dp[(i,0,1)]=shadow[i][0]-mouse[i][0]+dp[(i-1,0,1)] # for rest of the blocks # for a block (i,j) we have to add shadow[i][j] and subtract mouse[i][j]         from it for double counting # now for each block we have two choices, either take its previous block         with same direction or take previous block with different # direction and subtract corner double counted mouse. We have to take min of         both to find optimal answer for i,j in product(list(range(1,n)),list(range(1,m))): a=shadow[i][j]-mouse[i][j] b=a a+=min(dp[(i,j-1,0)],dp[(i,j-1,1)]-mouse[i-1][j]) b+=min(dp[(i-1,j,1)],dp[(i-1,j,0)]-mouse[i][j-1]) dp[(i,j,0)]=a dp[(i,j,1)]=b # what if [0][0] and [n-1][m-1] have mice, so we have to add them as we         haven't counted them yet. return min(dp[(n-1,m-1,0)],dp[(n-1,m-1,1)])+mouse[0][0]+mouse[n-1][m-1] for _ in range(int(input())): n,m=list(map(int,input().split( ))) mouse=[] for i in range(n): x=input() mouse.append(list(map(int,x))) print(solve(mouse,n,m))
train
APPS_structured
Hi! Welcome to my first kata. In this kata the task is to take a list of integers (positive and negative) and split them according to a simple rule; those ints greater than or equal to the key, and those ints less than the key (the itself key will always be positive). However, in this kata the goal is to sort the numbers IN PLACE, so DON'T go messing around with the order in with the numbers appear. You are to return a nested list. If the list is empty, simply return an empty list. Confused? Okay, let me walk you through an example... The input is: [1, 1, 1, 0, 0, 6, 10, 5, 10], the key is: 6 Okay so the first five numbers are less than the key, 6, so we group them together. [1, 1, 1, 0, 0] The next two numbers, 6 & 10, are both >= 6 to they belong in a seperate group, which we will add to the first group. Like so: [[1, 1, 1, 0, 0], [6, 10]] The next two numbers are 5 & 10. Since the key is 6 these two numbers form seperate groups, which we will add to the previous result. like so: [[1, 1, 1, 0, 0], [6, 10], [5], [10]] And voila! We're done. Here are a few more basic examples: group_ints([1, 0], key= 0) --> [[1,0]] group_ints([1, 0, -1, 5], key= 0) --> [[1, 0], [-1], [5]] group_ints([1, 0, -1, 5], key= 5) --> [[1, 0, -1], [5]] Good luck guys/gals!
class Nest(): def __init__(self, key, list): self.key = key self.list = list self.chen = 0 self.temp_list = [] self.new_list = [] self.ACT = { 1:self.__ap_end__, 0:self.__swich__ } self.OPER = { 0:lambda a, b: a < b , 1:lambda a, b : a >= b } def __ap_end__(self, c_list, element ): c_list.append(element) def __swich__(self, c_list, element): if c_list: self.__ap_end__(self.new_list, c_list) self.temp_list = [element] self.chen = not self.chen def do_sort(self ): if not self.list: return [] for e in self.list: self.ACT[ self.OPER[self.chen]( e,self.key ) ]( self.temp_list, e ) return self.new_list + [self.temp_list] group_ints = lambda lst, key=0 : Nest( key, lst ).do_sort()
class Nest(): def __init__(self, key, list): self.key = key self.list = list self.chen = 0 self.temp_list = [] self.new_list = [] self.ACT = { 1:self.__ap_end__, 0:self.__swich__ } self.OPER = { 0:lambda a, b: a < b , 1:lambda a, b : a >= b } def __ap_end__(self, c_list, element ): c_list.append(element) def __swich__(self, c_list, element): if c_list: self.__ap_end__(self.new_list, c_list) self.temp_list = [element] self.chen = not self.chen def do_sort(self ): if not self.list: return [] for e in self.list: self.ACT[ self.OPER[self.chen]( e,self.key ) ]( self.temp_list, e ) return self.new_list + [self.temp_list] group_ints = lambda lst, key=0 : Nest( key, lst ).do_sort()
train
APPS_structured
You're laying out a rad pixel art mural to paint on your living room wall in homage to [Paul Robertson](http://68.media.tumblr.com/0f55f7f3789a354cfcda7c2a64f501d1/tumblr_o7eq3biK9s1qhccbco1_500.png), your favorite pixel artist. You want your work to be perfect down to the millimeter. You haven't decided on the dimensions of your piece, how large you want your pixels to be, or which wall you want to use. You just know that you want to fit an exact number of pixels. To help decide those things you've decided to write a function, `is_divisible()` that will tell you whether a wall of a certain length can exactly fit an integer number of pixels of a certain length. Your function should take two arguments: the size of the wall in millimeters and the size of a pixel in millimeters. It should return `True` if you can fit an exact number of pixels on the wall, otherwise it should return `False`. For example `is_divisible(4050, 27)` should return `True`, but `is_divisible(4066, 27)` should return `False`. Note: you don't need to use an `if` statement here. Remember that in Python an expression using the `==` comparison operator will evaluate to either `True` or `False`: ```python >>> def equals_three(num): >>> return num == 3 >>> equals_three(5) False >>> equals_three(3) True ``` ```if:csharp Documentation: Kata.IsDivisible Method (Int32, Int32) Returns a boolean representing if the first argument is perfectly divisible by the second argument. Syntax public static bool IsDivisible( int wallLength,   int pixelSize,   ) Parameters wallLength Type: System.Int32 The length of the wall in millimeters. pixelSize Type: System.Int32 The length of a pixel in millimeters. Return Value Type: System.Boolean A boolean value representing if the first argument is perfectly divisible by the second. ```
def is_divisible(wall_in_mils, pixel_in_mils): return (wall_in_mils % pixel_in_mils) == 0
def is_divisible(wall_in_mils, pixel_in_mils): return (wall_in_mils % pixel_in_mils) == 0
train
APPS_structured
A grid is a perfect starting point for many games (Chess, battleships, Candy Crush!). Making a digital chessboard I think is an interesting way of visualising how loops can work together. Your task is to write a function that takes two integers `rows` and `columns` and returns a chessboard pattern as a two dimensional array. So `chessBoard(6,4)` should return an array like this: [ ["O","X","O","X"], ["X","O","X","O"], ["O","X","O","X"], ["X","O","X","O"], ["O","X","O","X"], ["X","O","X","O"] ] And `chessBoard(3,7)` should return this: [ ["O","X","O","X","O","X","O"], ["X","O","X","O","X","O","X"], ["O","X","O","X","O","X","O"] ] The white spaces should be represented by an: `'O'` and the black an: `'X'` The first row should always start with a white space `'O'`
def chess_board(rows, columns): board = [] for row in range(rows): if row % 2: board.append(["X" if not column % 2 else "O" for column in range(columns)]) else: board.append(["O" if not column % 2 else "X" for column in range(columns)]) return board
def chess_board(rows, columns): board = [] for row in range(rows): if row % 2: board.append(["X" if not column % 2 else "O" for column in range(columns)]) else: board.append(["O" if not column % 2 else "X" for column in range(columns)]) return board
train
APPS_structured
In this Kata, you will be given a string that has lowercase letters and numbers. Your task is to compare the number groupings and return the largest number. Numbers will not have leading zeros. For example, `solve("gh12cdy695m1") = 695`, because this is the largest of all number groupings. Good luck! Please also try [Simple remove duplicates](https://www.codewars.com/kata/5ba38ba180824a86850000f7)
def solve(s): s += 'a' digits = list('0123456789') biggest = 0 current = '' list_of_numbers = [] for i in range(len(s)): if s[i] in digits: current += s[i] else: list_of_numbers.append(current) current = '' while '' in list_of_numbers: list_of_numbers.remove('') list_of_ints = [] for j in range(len(list_of_numbers)): list_of_numbers[j] = int(list_of_numbers[j]) list_of_ints.append(list_of_numbers[j]) biggest = max(list_of_ints) return biggest pass
def solve(s): s += 'a' digits = list('0123456789') biggest = 0 current = '' list_of_numbers = [] for i in range(len(s)): if s[i] in digits: current += s[i] else: list_of_numbers.append(current) current = '' while '' in list_of_numbers: list_of_numbers.remove('') list_of_ints = [] for j in range(len(list_of_numbers)): list_of_numbers[j] = int(list_of_numbers[j]) list_of_ints.append(list_of_numbers[j]) biggest = max(list_of_ints) return biggest pass
train
APPS_structured
A number K$K$ is said to be magical if it can be represented as a power of 2 only.That is K$K$=2x$2^{x}$ for some natural number x$x$. Given a string of digits S$S$ of length N$N$, Let P be a valid arrangement of S. By valid arrangement we mean that it should not have any leading zeroes. Find the sum of all such distinct Pi's, which, when treated as a number is magical. Two arrangements are said to be distinct, if there is atleast one index where they differ. As the sum can be very large, print the sum modulo 109+7$10^{9}+7$. -----Input:----- -The first line of the input contains a single integer T$T$ denoting the number of test cases. -Only line of each test case contains a string S$S$ of length N$N$, consisting only of digits between 0 to 9. -----Output:----- For each test case, print a single integer denoting the sum of all such magical Pi′s$Pi's$ modulo 109+7$10^{9}+7$. If no such Pi$Pi$ exists print "-1". -----Constraints----- - 1≤T≤1000$1 \leq T \leq 1000$ - 2≤N≤1000$2 \leq N \leq 1000$ - String only consists of digits between 0 to 9, both inclusive. -----Subtasks----- - 10 points : 1≤N≤5$1 \leq N \leq 5$ - 40 points : 1≤N≤100$1 \leq N \leq 100$ - 50 points : Original Constraints -----Sample Input:----- 2 35566 31 -----Sample Output:----- 65536 -1 -----EXPLANATION:----- Only arrangement is 65536. No arrangement of 31 gives us a power of two.
from math import log2, ceil MOD = int(1e9 + 7) srt = lambda s: ''.join(sorted(s)) for _ in range(int(input())): s = srt(input()) res = -1 for p in range(ceil(log2(int(s))), int(log2(int(s[::-1]))) + 1): if int(srt(str(pow(2, p)))) == int(s): if res == -1: res = 0 res = (res + pow(2, p, MOD)) % MOD print(res)
from math import log2, ceil MOD = int(1e9 + 7) srt = lambda s: ''.join(sorted(s)) for _ in range(int(input())): s = srt(input()) res = -1 for p in range(ceil(log2(int(s))), int(log2(int(s[::-1]))) + 1): if int(srt(str(pow(2, p)))) == int(s): if res == -1: res = 0 res = (res + pow(2, p, MOD)) % MOD print(res)
train
APPS_structured
In a warehouse, there is a row of barcodes, where the i-th barcode is barcodes[i]. Rearrange the barcodes so that no two adjacent barcodes are equal.  You may return any answer, and it is guaranteed an answer exists. Example 1: Input: [1,1,1,2,2,2] Output: [2,1,2,1,2,1] Example 2: Input: [1,1,1,1,2,2,3,3] Output: [1,3,1,3,2,1,2,1] Note: 1 <= barcodes.length <= 10000 1 <= barcodes[i] <= 10000
from collections import Counter, defaultdict class Solution: def rearrangeBarcodes(self, barcodes: List[int]) -> List[int]: counter = Counter(barcodes) memo = defaultdict(list) rest = 0 for e, c in counter.most_common(): memo[c].append(e) rest += c ret = [] while rest: rest -= 1 for c in sorted(memo.keys(), reverse=True): for idx, e in enumerate(memo[c]): if ret and ret[-1] == e: continue ret.append(e) del memo[c][idx] if not memo[c]: del memo[c] memo[c-1].append(e) break if rest == len(barcodes) - len(ret): break return ret
from collections import Counter, defaultdict class Solution: def rearrangeBarcodes(self, barcodes: List[int]) -> List[int]: counter = Counter(barcodes) memo = defaultdict(list) rest = 0 for e, c in counter.most_common(): memo[c].append(e) rest += c ret = [] while rest: rest -= 1 for c in sorted(memo.keys(), reverse=True): for idx, e in enumerate(memo[c]): if ret and ret[-1] == e: continue ret.append(e) del memo[c][idx] if not memo[c]: del memo[c] memo[c-1].append(e) break if rest == len(barcodes) - len(ret): break return ret
train
APPS_structured
You need count how many valleys you will pass. Start is always from zero level. Every time you go down below 0 level counts as an entry of a valley, and as you go up to 0 level from valley counts as an exit of a valley. One passed valley is equal one entry and one exit of a valley. ``` s='FUFFDDFDUDFUFUF' U=UP F=FORWARD D=DOWN ``` To represent string above ``` (level 1) __ (level 0)_/ \ _(exit we are again on level 0) (entry-1) \_ _/ (level-2) \/\_/ ``` So here we passed one valley
def counting_valleys(s): level = 0 in_valley = False count = 0 for c in s: if c =='U': level += 1 elif c=='D': level -= 1 if level >= 0 and in_valley: count += 1 in_valley = level < 0 return count
def counting_valleys(s): level = 0 in_valley = False count = 0 for c in s: if c =='U': level += 1 elif c=='D': level -= 1 if level >= 0 and in_valley: count += 1 in_valley = level < 0 return count
train
APPS_structured
The annual snake festival is upon us, and all the snakes of the kingdom have gathered to participate in the procession. Chef has been tasked with reporting on the procession, and for this he decides to first keep track of all the snakes. When he sees a snake first, it'll be its Head, and hence he will mark a 'H'. The snakes are long, and when he sees the snake finally slither away, he'll mark a 'T' to denote its tail. In the time in between, when the snake is moving past him, or the time between one snake and the next snake, he marks with '.'s. Because the snakes come in a procession, and one by one, a valid report would be something like "..H..T...HTH....T.", or "...", or "HT", whereas "T...H..H.T", "H..T..H", "H..H..T..T" would be invalid reports (See explanations at the bottom). Formally, a snake is represented by a 'H' followed by some (possibly zero) '.'s, and then a 'T'. A valid report is one such that it begins with a (possibly zero length) string of '.'s, and then some (possibly zero) snakes between which there can be some '.'s, and then finally ends with some (possibly zero) '.'s. Chef had binged on the festival food and had been very drowsy. So his report might be invalid. You need to help him find out if his report is valid or not. -----Input----- - The first line contains a single integer, R, which denotes the number of reports to be checked. The description of each report follows after this. - The first line of each report contains a single integer, L, the length of that report. - The second line of each report contains a string of length L. The string contains only the characters '.', 'H', and 'T'. -----Output----- - For each report, output the string "Valid" or "Invalid" in a new line, depending on whether it was a valid report or not. -----Constraints----- - 1 ≤ R ≤ 500 - 1 ≤ length of each report ≤ 500 -----Example----- Input: 6 18 ..H..T...HTH....T. 3 ... 10 H..H..T..T 2 HT 11 .T...H..H.T 7 H..T..H Output: Valid Valid Invalid Valid Invalid Invalid -----Explanation----- "H..H..T..T" is invalid because the second snake starts before the first snake ends, which is not allowed. ".T...H..H.T" is invalid because it has a 'T' before a 'H'. A tail can come only after its head. "H..T..H" is invalid because the last 'H' does not have a corresponding 'T'.
t=int(input()) for i in range(t): n=int(input()) s=input() c=0 for i in s: if i=='H': c=c+1 if i=='T': c=c-1 if c>1: break if c<0: break if c==0: print('Valid') else: print('Invalid')
t=int(input()) for i in range(t): n=int(input()) s=input() c=0 for i in s: if i=='H': c=c+1 if i=='T': c=c-1 if c>1: break if c<0: break if c==0: print('Valid') else: print('Invalid')
train
APPS_structured
Given an array A of integers, return the length of the longest arithmetic subsequence in A. Recall that a subsequence of A is a list A[i_1], A[i_2], ..., A[i_k] with 0 <= i_1 < i_2 < ... < i_k <= A.length - 1, and that a sequence B is arithmetic if B[i+1] - B[i] are all the same value (for 0 <= i < B.length - 1). Example 1: Input: A = [3,6,9,12] Output: 4 Explanation: The whole array is an arithmetic sequence with steps of length = 3. Example 2: Input: A = [9,4,7,2,10] Output: 3 Explanation: The longest arithmetic subsequence is [4,7,10]. Example 3: Input: A = [20,1,15,3,10,5,8] Output: 4 Explanation: The longest arithmetic subsequence is [20,15,10,5]. Constraints: 2 <= A.length <= 1000 0 <= A[i] <= 500
class Solution: def longestArithSeqLength(self, A: List[int]) -> int: dp = [collections.defaultdict(int) for _ in range(len(A))] res = 0 for i in range(1, len(A)): for j in range(i): dp[i][A[i]-A[j]] = max(dp[i][A[i]-A[j]], dp[j].get(A[i]-A[j], 1)+1) res = max(res, dp[i][A[i]-A[j]]) return res
class Solution: def longestArithSeqLength(self, A: List[int]) -> int: dp = [collections.defaultdict(int) for _ in range(len(A))] res = 0 for i in range(1, len(A)): for j in range(i): dp[i][A[i]-A[j]] = max(dp[i][A[i]-A[j]], dp[j].get(A[i]-A[j], 1)+1) res = max(res, dp[i][A[i]-A[j]]) return res
train
APPS_structured
# Task Imagine a standard chess board with only two white and two black knights placed in their standard starting positions: the white knights on b1 and g1; the black knights on b8 and g8. There are two players: one plays for `white`, the other for `black`. During each move, the player picks one of his knights and moves it to an unoccupied square according to standard chess rules. Thus, a knight on d5 can move to any of the following squares: b6, c7, e7, f6, f4, e3, c3, and b4, as long as it is not occupied by either a friendly or an enemy knight. The players take turns in making moves, starting with the white player. Given the configuration `positions` of the knights after an unspecified number of moves, determine whose turn it is. # Example For `positions = "b1;g1;b8;g8"`, the output should be `true`. The configuration corresponds to the initial state of the game. Thus, it's white's turn. # Input/Output - `[input]` string `positions` The positions of the four knights, starting with white knights, separated by a semicolon, in the chess notation. - `[output]` a boolean value `true` if white is to move, `false` otherwise.
def whose_turn(positions): positions = positions.split(";") on_white_squares = [is_white_square(pos) for pos in positions] # Player's knights on black-black or white-white => odd number of moves white_pieces_match = on_white_squares[0] == on_white_squares[1] black_pieces_match = on_white_squares[2] == on_white_squares[3] # Equal number of moves => white to move return white_pieces_match == black_pieces_match def is_white_square(pos): x, y = ord(pos[0]) - 97, int(pos[1]) return x % 2 == y % 2
def whose_turn(positions): positions = positions.split(";") on_white_squares = [is_white_square(pos) for pos in positions] # Player's knights on black-black or white-white => odd number of moves white_pieces_match = on_white_squares[0] == on_white_squares[1] black_pieces_match = on_white_squares[2] == on_white_squares[3] # Equal number of moves => white to move return white_pieces_match == black_pieces_match def is_white_square(pos): x, y = ord(pos[0]) - 97, int(pos[1]) return x % 2 == y % 2
train
APPS_structured
The legendary Farmer John is throwing a huge party, and animals from all over the world are hanging out at his house. His guests are hungry, so he instructs his cow Bessie to bring out the snacks! Moo! There are $n$ snacks flavors, numbered with integers $1, 2, \ldots, n$. Bessie has $n$ snacks, one snack of each flavor. Every guest has exactly two favorite flavors. The procedure for eating snacks will go as follows: First, Bessie will line up the guests in some way. Then in this order, guests will approach the snacks one by one. Each guest in their turn will eat all remaining snacks of their favorite flavor. In case no favorite flavors are present when a guest goes up, they become very sad. Help Bessie to minimize the number of sad guests by lining the guests in an optimal way. -----Input----- The first line contains integers $n$ and $k$ ($2 \le n \le 10^5$, $1 \le k \le 10^5$), the number of snacks and the number of guests. The $i$-th of the following $k$ lines contains two integers $x_i$ and $y_i$ ($1 \le x_i, y_i \le n$, $x_i \ne y_i$), favorite snack flavors of the $i$-th guest. -----Output----- Output one integer, the smallest possible number of sad guests. -----Examples----- Input 5 4 1 2 4 3 1 4 3 4 Output 1 Input 6 5 2 3 2 1 3 4 6 5 4 5 Output 0 -----Note----- In the first example, Bessie can order the guests like this: $3, 1, 2, 4$. Guest $3$ goes first and eats snacks $1$ and $4$. Then the guest $1$ goes and eats the snack $2$ only, because the snack $1$ has already been eaten. Similarly, the guest $2$ goes up and eats the snack $3$ only. All the snacks are gone, so the guest $4$ will be sad. In the second example, one optimal ordering is $2, 1, 3, 5, 4$. All the guests will be satisfied.
from sys import stdin n, k = tuple(int(x) for x in stdin.readline().split()) dic = {} ans = 0 for i in range(k): a, b = tuple(int(x) for x in stdin.readline().split()) a -= 1 b -= 1 if a not in dic: dic[a] = set((b,)) else: dic[a].add(b) if b not in dic: dic[b] = set((a,)) else: dic[b].add(a) for i in range(n): if i in dic: lst = [i] s = set((i,)) for src in lst: if src in dic: for dest in dic[src]: if dest in dic and dest not in s: lst.append(dest) s.add(dest) ans += 1 del dic[src] print(k-ans)
from sys import stdin n, k = tuple(int(x) for x in stdin.readline().split()) dic = {} ans = 0 for i in range(k): a, b = tuple(int(x) for x in stdin.readline().split()) a -= 1 b -= 1 if a not in dic: dic[a] = set((b,)) else: dic[a].add(b) if b not in dic: dic[b] = set((a,)) else: dic[b].add(a) for i in range(n): if i in dic: lst = [i] s = set((i,)) for src in lst: if src in dic: for dest in dic[src]: if dest in dic and dest not in s: lst.append(dest) s.add(dest) ans += 1 del dic[src] print(k-ans)
train
APPS_structured
One upon a time there were three best friends Abhinav, Harsh, and Akash decided to form a team and take part in ICPC from KIIT. Participants are usually offered several problems during the programming contest. Long before the start, the friends decided that they will implement a problem if at least two of them are sure about the solution. Otherwise, friends won't write the problem's solution. This contest offers $N$ problems to the participants. For each problem we know, which friend is sure about the solution. Help the KIITians find the number of problems for which they will write a solution. Then n lines contain three integers each, each integer is either 0 or 1. If the first number in the line equals 1, then Abhinav is sure about the problem's solution, otherwise, he isn't sure. The second number shows Harsh's view on the solution, the third number shows Akash's view. The numbers on the lines are -----Input:----- - A single integer will contain $N$, number of problems. -----Output:----- Print a single integer — the number of problems the friends will implement on the contest. -----Constraints----- - $1 \leq N \leq 1000$ -----Sample Input:----- 3 1 1 0 1 1 1 1 0 0 -----Sample Output:----- 2 -----EXPLANATION:----- In the first sample, Abhinav and Harsh are sure that they know how to solve the first problem and all three of them know how to solve the second problem. That means that they will write solutions for these problems. Only Abhinav is sure about the solution for the third problem, but that isn't enough, so the group won't take it.
# cook your dish here a=int(input()) z=0 for i in range(a): b=list(map(int,input().split())) y=0 for j in b: if j==1: y=y+1 if y>1: z=z+1 print(z)
# cook your dish here a=int(input()) z=0 for i in range(a): b=list(map(int,input().split())) y=0 for j in b: if j==1: y=y+1 if y>1: z=z+1 print(z)
train
APPS_structured
Implement function which will return sum of roots of a quadratic equation rounded to 2 decimal places, if there are any possible roots, else return **None/null/nil/nothing**. If you use discriminant,when discriminant = 0, x1 = x2 = root => return sum of both roots. There will always be valid arguments. Quadratic equation - https://en.wikipedia.org/wiki/Quadratic_equation
def roots(a,b,c): import math d = b ** 2 - 4 * a * c if d > 0: return round(-2 * b / (2 * a), 2) elif d == 0: x = -b / (2 * a) return x * 2 else: return None
def roots(a,b,c): import math d = b ** 2 - 4 * a * c if d > 0: return round(-2 * b / (2 * a), 2) elif d == 0: x = -b / (2 * a) return x * 2 else: return None
train
APPS_structured
# Task The `hamming distance` between a pair of numbers is the number of binary bits that differ in their binary notation. # Example For `a = 25, b= 87`, the result should be `4` ``` 25: 00011001 87: 01010111 ``` The `hamming distance` between these two would be 4 ( the `2nd, 5th, 6th, 7th` bit ). # Input/Output - `[input]` integer `a` First Number. `1 <= a <= 2^20` - `[input]` integer `b` Second Number. `1 <= b <= 2^20` - `[output]` an integer Hamming Distance
def hamming_distance(a, b): return sum(x != y for x, y in zip(format(a, "020b"), format(b, "020b")))
def hamming_distance(a, b): return sum(x != y for x, y in zip(format(a, "020b"), format(b, "020b")))
train
APPS_structured
You are participating in a contest which has $11$ problems (numbered $1$ through $11$). The first eight problems (i.e. problems $1, 2, \ldots, 8$) are scorable, while the last three problems ($9$, $10$ and $11$) are non-scorable ― this means that any submissions you make on any of these problems do not affect your total score. Your total score is the sum of your best scores for all scorable problems. That is, for each scorable problem, you look at the scores of all submissions you made on that problem and take the maximum of these scores (or $0$ if you didn't make any submissions on that problem); the total score is the sum of the maximum scores you took. You know the results of all submissions you made. Calculate your total score. -----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$ denoting the number of submissions you made. - $N$ lines follow. For each $i$ ($1 \le i \le N$), the $i$-th of these lines contains two space-separated integers $p_i$ and $s_i$, denoting that your $i$-th submission was on problem $p_i$ and it received a score $s_i$. -----Output----- For each test case, print a single line containing one integer ― your total score. -----Constraints----- - $1 \le T \le 10$ - $1 \le N \le 1,000$ - $1 \le p_i \le 11$ for each valid $i$ - $0 \le s_i \le 100$ for each valid $i$ -----Subtasks----- Subtask #1 (15 points): all submissions are on the same problem, i.e. $p_1 = p_2 = \ldots = p_N$ Subtask #2 (15 points): there is at most one submission made on each problem, i.e. $p_i \neq p_j$ for each valid $i, j$ ($i \neq j$) Subtask #3 (70 points): original constraints -----Example Input----- 2 5 2 45 9 100 8 0 2 15 8 90 1 11 1 -----Example Output----- 135 0 -----Explanation----- Example case 1: The scorable problems with at least one submission are problems $2$ and $8$. For problem $2$, there are two submissions and the maximum score among them is $45$. For problem $8$, there are also two submissions and the maximum score is $90$. Hence, the total score is $45 + 90 = 135$. Example case 2: No scorable problem is attempted, so the total score is $0$.
# cook your dish here for _ in range(int(input())): n=int(input()) arr=[] for i in range(11): arr.append(0) for i in range(n): p,s=list(map(int,input().split())) if p<=8: arr[p-1]=max(arr[p-1],s) print(sum(arr))
# cook your dish here for _ in range(int(input())): n=int(input()) arr=[] for i in range(11): arr.append(0) for i in range(n): p,s=list(map(int,input().split())) if p<=8: arr[p-1]=max(arr[p-1],s) print(sum(arr))
train
APPS_structured
You're in the casino, playing Roulette, going for the "1-18" bets only and desperate to beat the house and so you want to test how effective the [Martingale strategy](https://en.wikipedia.org/wiki/Martingale_(betting_system)) is. You will be given a starting cash balance and an array of binary digits to represent a win (`1`) or a loss (`0`). Return your balance after playing all rounds. *The Martingale strategy* You start with a stake of `100` dollars. If you lose a round, you lose the stake placed on that round and you double the stake for your next bet. When you win, you win 100% of the stake and revert back to staking 100 dollars on your next bet. ## Example ``` martingale(1000, [1, 1, 0, 0, 1]) === 1300 ``` Explanation: * you win your 1st round: gain $100, balance = 1100 * you win the 2nd round: gain $100, balance = 1200 * you lose the 3rd round: lose $100 dollars, balance = 1100 * double stake for 4th round and lose: staked $200, lose $200, balance = 900 * double stake for 5th round and win: staked $400, won $400, balance = 1300 **Note: Your balance is allowed to go below 0.**
def martingale(bank, outcomes): stake = 100 for i in outcomes: if i == 0: bank -= stake stake *= 2 else: bank += stake stake = 100 return bank
def martingale(bank, outcomes): stake = 100 for i in outcomes: if i == 0: bank -= stake stake *= 2 else: bank += stake stake = 100 return bank
train
APPS_structured
Your task is to create a function called ```sum_arrays()``` in Python or ```addArrays``` in Javascript, which takes two arrays consisting of integers, and returns the sum of those two arrays. The twist is that (for example) ```[3,2,9]``` does not equal ``` 3 + 2 + 9```, it would equal ```'3' + '2' + '9'``` converted to an integer for this kata, meaning it would equal ```329```. The output should be an array of the the sum in a similar fashion to the input (for example, if the sum is ```341```, you would return ```[3,4,1]```). Examples are given below of what two arrays should return. ```python [3,2,9],[1,2] --> [3,4,1] [4,7,3],[1,2,3] --> [5,9,6] [1],[5,7,6] --> [5,7,7] ``` If both arrays are empty, return an empty array. In some cases, there will be an array containing a negative number as the first index in the array. In this case treat the whole number as a negative number. See below: ```python [3,2,6,6],[-7,2,2,8] --> [-3,9,6,2] # 3266 + (-7228) = -3962 ```
def sum_arrays(array1,array2): number1 = 0 number2 = 0 b1 = False b2 = False if len(array1) == 0: return array2 if len(array2) == 0: return array1 if array1[0] < 0: array1[0] *= -1 b1 = True if array2[0] < 0: array2[0] *= -1 b2 = True for i in array1: number1 = number1 * 10 + i for i in array2: number2 = number2 * 10 + i if b1: number1 *= -1 if b2: number2 *= -1 number = number1 + number2 array = [] if number == 0: return [] if number < 0: b = True number *= -1 else: b = False number = str(number) for i in range(len(number)): array.append(int(number[i])) if b: array[0] *= -1 return array return array
def sum_arrays(array1,array2): number1 = 0 number2 = 0 b1 = False b2 = False if len(array1) == 0: return array2 if len(array2) == 0: return array1 if array1[0] < 0: array1[0] *= -1 b1 = True if array2[0] < 0: array2[0] *= -1 b2 = True for i in array1: number1 = number1 * 10 + i for i in array2: number2 = number2 * 10 + i if b1: number1 *= -1 if b2: number2 *= -1 number = number1 + number2 array = [] if number == 0: return [] if number < 0: b = True number *= -1 else: b = False number = str(number) for i in range(len(number)): array.append(int(number[i])) if b: array[0] *= -1 return array return array
train
APPS_structured
Given an array of integers nums, sort the array in ascending order. Example 1: Input: nums = [5,2,3,1] Output: [1,2,3,5] Example 2: Input: nums = [5,1,1,2,0,0] Output: [0,0,1,1,2,5] Constraints: 1 <= nums.length <= 50000 -50000 <= nums[i] <= 50000
class Solution: def left(self, i): return 2*i+1 def right(self, i): return 2*i+2 def parent(self, i): return (i//2)-1 if not i%2 else i//2 def maxheapify(self, a, heapsize,i): l = self.left(i) leftisgreater = False rightisgreater = False if l < heapsize: if a[i] < a[l]: leftisgreater = True r = self.right(i) if r < heapsize: if a[i] < a[r]: rightisgreater = True if leftisgreater or rightisgreater: if leftisgreater and not rightisgreater: a[i],a[l] = a[l],a[i] self.maxheapify(a, heapsize, l) elif not leftisgreater and rightisgreater: a[i],a[r] = a[r],a[i] self.maxheapify(a, heapsize, r) elif leftisgreater and rightisgreater: if a[l] <= a[r]: rightisgreater = True leftisgreater = False else: leftisgreater = True rightisgreater = False if rightisgreater: a[i],a[r] = a[r],a[i] self.maxheapify(a, heapsize, r) else: a[i],a[l] = a[l],a[i] self.maxheapify(a, heapsize, l) def buildmaxheap(self, nums, heapsize): for i in reversed(range(len(nums)//2)): self.maxheapify(nums, heapsize,i) def heapsort(self, nums): heapsize = len(nums) self.buildmaxheap(nums, heapsize) for i in range(len(nums)): nums[0],nums[heapsize-1]=nums[heapsize-1],nums[0] heapsize-=1 self.maxheapify(nums, heapsize, 0) def sortArray(self, nums: List[int]) -> List[int]: self.heapsort(nums) return nums
class Solution: def left(self, i): return 2*i+1 def right(self, i): return 2*i+2 def parent(self, i): return (i//2)-1 if not i%2 else i//2 def maxheapify(self, a, heapsize,i): l = self.left(i) leftisgreater = False rightisgreater = False if l < heapsize: if a[i] < a[l]: leftisgreater = True r = self.right(i) if r < heapsize: if a[i] < a[r]: rightisgreater = True if leftisgreater or rightisgreater: if leftisgreater and not rightisgreater: a[i],a[l] = a[l],a[i] self.maxheapify(a, heapsize, l) elif not leftisgreater and rightisgreater: a[i],a[r] = a[r],a[i] self.maxheapify(a, heapsize, r) elif leftisgreater and rightisgreater: if a[l] <= a[r]: rightisgreater = True leftisgreater = False else: leftisgreater = True rightisgreater = False if rightisgreater: a[i],a[r] = a[r],a[i] self.maxheapify(a, heapsize, r) else: a[i],a[l] = a[l],a[i] self.maxheapify(a, heapsize, l) def buildmaxheap(self, nums, heapsize): for i in reversed(range(len(nums)//2)): self.maxheapify(nums, heapsize,i) def heapsort(self, nums): heapsize = len(nums) self.buildmaxheap(nums, heapsize) for i in range(len(nums)): nums[0],nums[heapsize-1]=nums[heapsize-1],nums[0] heapsize-=1 self.maxheapify(nums, heapsize, 0) def sortArray(self, nums: List[int]) -> List[int]: self.heapsort(nums) return nums
train
APPS_structured
Your classmates asked you to copy some paperwork for them. You know that there are 'n' classmates and the paperwork has 'm' pages. Your task is to calculate how many blank pages do you need. ### Example: ```python paperwork(5, 5) == 25 ``` **Note:** if `n < 0` or `m < 0` return `0`! Waiting for translations and Feedback! Thanks!
paperwork = lambda a,b: a*b if min(a,b)>0 else 0
paperwork = lambda a,b: a*b if min(a,b)>0 else 0
train
APPS_structured
Chef is the judge of a competition. There are two players participating in this competition — Alice and Bob. The competition consists of N races. For each i (1 ≤ i ≤ N), Alice finished the i-th race in Ai minutes, while Bob finished it in Bi minutes. The player with the smallest sum of finish times wins. If this total time is the same for Alice and for Bob, a draw is declared. The rules of the competition allow each player to choose a race which will not be counted towards their total time. That is, Alice may choose an index x and her finish time in the race with this index will be considered zero; similarly, Bob may choose an index y and his finish time in the race with this index will be considered zero. Note that x can be different from y; the index chosen by Alice does not affect Bob's total time or vice versa. Chef, as the judge, needs to announce the result of the competition. He knows that both Alice and Bob play optimally and will always choose the best option. Please help Chef determine the result! -----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 A1, A2, ..., AN. - The third line contains N space-separated integers B1, B2, ..., BN. -----Output----- For each test case, print a single line containing the string "Alice" if Alice wins, "Bob" if Bob wins or "Draw" if the result is a draw (without quotes). -----Constraints----- - 1 ≤ T ≤ 100 - 2 ≤ N ≤ 100 - 1 ≤ Ai ≤ 1000 for each valid i - 1 ≤ Bi ≤ 1000 for each valid i -----Example----- Input: 3 5 3 1 3 3 4 1 6 2 5 3 5 1 6 2 5 3 3 1 3 3 4 3 4 1 3 2 2 7 Output: Alice Bob Draw -----Explanation----- Example case 1: Alice will choose the finish time in the last race to be considered zero, which means her sum of finish times is 3 + 1 + 3 + 3 + 0 = 10, while Bob will choose the finish time of his second race to be considered zero, so his total sum of finish times is 1 + 0 + 2 + 5 + 3 = 11. Since Alice's sum is smaller, she is considered the winner. Example case 2: We're dealing with the same situation as in the previous case, but finish times for the players are swapped, so Bob wins this time. Example case 3: Alice will choose the finish time of the first race to be considered zero, which means her total time is 0 + 1 + 3 = 4. Bob will choose the finish time of his last race to be considered zero, which makes his total time 2 + 2 + 0 = 4. The competition is considered a draw because both players have equal sums of finish times.
t=int(input()) while t>0: n=int(input()) a=list(map(int,input().split())) b=list(map(int,input().split())) a.sort() a.pop() b.sort() b.pop() al=sum(a) bob=sum(b) if(al<bob): print('Alice') elif(al==bob): print('Draw') else: print('Bob') t=t-1
t=int(input()) while t>0: n=int(input()) a=list(map(int,input().split())) b=list(map(int,input().split())) a.sort() a.pop() b.sort() b.pop() al=sum(a) bob=sum(b) if(al<bob): print('Alice') elif(al==bob): print('Draw') else: print('Bob') t=t-1
train
APPS_structured
You are given a permutation $p_1, p_2, \ldots, p_n$. In one move you can swap two adjacent values. You want to perform a minimum number of moves, such that in the end there will exist a subsegment $1,2,\ldots, k$, in other words in the end there should be an integer $i$, $1 \leq i \leq n-k+1$ such that $p_i = 1, p_{i+1} = 2, \ldots, p_{i+k-1}=k$. Let $f(k)$ be the minimum number of moves that you need to make a subsegment with values $1,2,\ldots,k$ appear in the permutation. You need to find $f(1), f(2), \ldots, f(n)$. -----Input----- The first line of input contains one integer $n$ ($1 \leq n \leq 200\,000$): the number of elements in the permutation. The next line of input contains $n$ integers $p_1, p_2, \ldots, p_n$: given permutation ($1 \leq p_i \leq n$). -----Output----- Print $n$ integers, the minimum number of moves that you need to make a subsegment with values $1,2,\ldots,k$ appear in the permutation, for $k=1, 2, \ldots, n$. -----Examples----- Input 5 5 4 3 2 1 Output 0 1 3 6 10 Input 3 1 2 3 Output 0 0 0
import heapq class DynamicMedian(): def __init__(self): self.l_q = [] self.r_q = [] self.l_sum = 0 self.r_sum = 0 def add(self, val): if len(self.l_q) == len(self.r_q): self.l_sum += val val = -heapq.heappushpop(self.l_q, -val) self.l_sum -= val heapq.heappush(self.r_q, val) self.r_sum += val else: self.r_sum += val val = heapq.heappushpop(self.r_q, val) self.r_sum -= val heapq.heappush(self.l_q, -val) self.l_sum += val def median_low(self): if len(self.l_q) + 1 == len(self.r_q): return self.r_q[0] else: return -self.l_q[0] def median_high(self): return self.r_q[0] def minimum_query(self): res1 = (len(self.l_q) * self.median_high() - self.l_sum) res2 = (self.r_sum - len(self.r_q) * self.median_high()) return res1 + res2 #Binary Indexed Tree (Fenwick Tree) class BIT(): def __init__(self, n): self.n = n self.bit = [0] * (n + 1) def add(self, i, val): i = i + 1 while i <= self.n: self.bit[i] += val i += i & -i def _sum(self, i): s = 0 while i > 0: s += self.bit[i] i -= i & -i return s def sum(self, i, j): return self._sum(j) - self._sum(i) import sys input = sys.stdin.readline n = int(input()) a = list(map(int, input().split())) bit = BIT(n) dm = DynamicMedian() memo = {} for i in range(n): memo[a[i] - 1] = i b = [0] * n for i in range(n): dm.add(memo[i]) b[i] = dm.minimum_query() - (i+1)**2 // 4 ans = [0] * n tmp = 0 for i in range(len(a)): bit.add(memo[i], 1) tmp += bit.sum(memo[i] + 1, n) ans[i] = tmp + b[i] print(*ans)
import heapq class DynamicMedian(): def __init__(self): self.l_q = [] self.r_q = [] self.l_sum = 0 self.r_sum = 0 def add(self, val): if len(self.l_q) == len(self.r_q): self.l_sum += val val = -heapq.heappushpop(self.l_q, -val) self.l_sum -= val heapq.heappush(self.r_q, val) self.r_sum += val else: self.r_sum += val val = heapq.heappushpop(self.r_q, val) self.r_sum -= val heapq.heappush(self.l_q, -val) self.l_sum += val def median_low(self): if len(self.l_q) + 1 == len(self.r_q): return self.r_q[0] else: return -self.l_q[0] def median_high(self): return self.r_q[0] def minimum_query(self): res1 = (len(self.l_q) * self.median_high() - self.l_sum) res2 = (self.r_sum - len(self.r_q) * self.median_high()) return res1 + res2 #Binary Indexed Tree (Fenwick Tree) class BIT(): def __init__(self, n): self.n = n self.bit = [0] * (n + 1) def add(self, i, val): i = i + 1 while i <= self.n: self.bit[i] += val i += i & -i def _sum(self, i): s = 0 while i > 0: s += self.bit[i] i -= i & -i return s def sum(self, i, j): return self._sum(j) - self._sum(i) import sys input = sys.stdin.readline n = int(input()) a = list(map(int, input().split())) bit = BIT(n) dm = DynamicMedian() memo = {} for i in range(n): memo[a[i] - 1] = i b = [0] * n for i in range(n): dm.add(memo[i]) b[i] = dm.minimum_query() - (i+1)**2 // 4 ans = [0] * n tmp = 0 for i in range(len(a)): bit.add(memo[i], 1) tmp += bit.sum(memo[i] + 1, n) ans[i] = tmp + b[i] print(*ans)
train
APPS_structured
You know how sometimes you write the the same word twice in a sentence, but then don't notice that it happened? For example, you've been distracted for a second. Did you notice that *"the"* is doubled in the first sentence of this description? As as aS you can see, it's not easy to spot those errors, especially if words differ in case, like *"as"* at the beginning of the sentence. Write a function that counts the number of sections repeating the same word (case insensitive). The occurence of two or more equal words next after each other count as one. **Example:** ``` "dog cat" --> 0 "dog DOG cat" --> 1 "apple dog cat" --> 0 "pineapple apple dog cat" --> 0 "apple apple dog cat" --> 1 "apple dog apple dog cat" --> 0 "dog dog DOG dog dog dog" --> 1 "dog dog dog dog cat cat" --> 2 "cat cat dog dog cat cat" --> 3 ```
import re;count_adjacent_pairs=lambda s:len(re.findall(r'(\b\w+)(\s+\1)+',s,re.I))
import re;count_adjacent_pairs=lambda s:len(re.findall(r'(\b\w+)(\s+\1)+',s,re.I))
train
APPS_structured
Toad Rash has a binary string $s$. A binary string consists only of zeros and ones. Let $n$ be the length of $s$. Rash needs to find the number of such pairs of integers $l$, $r$ that $1 \leq l \leq r \leq n$ and there is at least one pair of integers $x$, $k$ such that $1 \leq x, k \leq n$, $l \leq x < x + 2k \leq r$, and $s_x = s_{x+k} = s_{x+2k}$. Find this number of pairs for Rash. -----Input----- The first line contains the string $s$ ($1 \leq |s| \leq 300\,000$), consisting of zeros and ones. -----Output----- Output one integer: the number of such pairs of integers $l$, $r$ that $1 \leq l \leq r \leq n$ and there is at least one pair of integers $x$, $k$ such that $1 \leq x, k \leq n$, $l \leq x < x + 2k \leq r$, and $s_x = s_{x+k} = s_{x+2k}$. -----Examples----- Input 010101 Output 3 Input 11001100 Output 0 -----Note----- In the first example, there are three $l$, $r$ pairs we need to count: $1$, $6$; $2$, $6$; and $1$, $5$. In the second example, there are no values $x$, $k$ for the initial string, so the answer is $0$.
X = [[], ['0', '1'], ['00', '01', '10', '11'], ['001', '010', '011', '100', '101', '110'], ['0010', '0011', '0100', '0101', '0110', '1001', '1010', '1011', '1100', '1101'], ['00100', '00101', '00110', '01001', '01011', '01100', '01101', '10010', '10011', '10100', '10110', '11001', '11010', '11011'], ['001001', '001011', '001100', '001101', '010010', '010011', '010110', '011001', '011010', '011011', '100100', '100101', '100110', '101001', '101100', '101101', '110010', '110011', '110100', '110110'], ['0010011', '0011001', '0011010', '0011011', '0100101', '0101100', '0101101', '0110011', '1001100', '1010010', '1010011', '1011010', '1100100', '1100101', '1100110', '1101100'], ['00110011', '01011010', '01100110', '10011001', '10100101', '11001100']] s = input() N = len(s) ans = (N-1)*(N-2)//2 for i in range(N): for j in range(i+3, min(i+9, N+1)): if s[i:j] in X[j-i]: ans -= 1 print(ans)
X = [[], ['0', '1'], ['00', '01', '10', '11'], ['001', '010', '011', '100', '101', '110'], ['0010', '0011', '0100', '0101', '0110', '1001', '1010', '1011', '1100', '1101'], ['00100', '00101', '00110', '01001', '01011', '01100', '01101', '10010', '10011', '10100', '10110', '11001', '11010', '11011'], ['001001', '001011', '001100', '001101', '010010', '010011', '010110', '011001', '011010', '011011', '100100', '100101', '100110', '101001', '101100', '101101', '110010', '110011', '110100', '110110'], ['0010011', '0011001', '0011010', '0011011', '0100101', '0101100', '0101101', '0110011', '1001100', '1010010', '1010011', '1011010', '1100100', '1100101', '1100110', '1101100'], ['00110011', '01011010', '01100110', '10011001', '10100101', '11001100']] s = input() N = len(s) ans = (N-1)*(N-2)//2 for i in range(N): for j in range(i+3, min(i+9, N+1)): if s[i:j] in X[j-i]: ans -= 1 print(ans)
train
APPS_structured
-----Description----- The Antique Comedians of India prefer comedies to tragedies. Unfortunately, most of the ancient plays are tragedies. Therefore the dramatic advisor of ACI has decided to transfigure some tragedies into comedies. Obviously, this work is very hard because the basic sense of the play must be kept intact, although all the things change to their opposites. For example the numbers: if any number appears in the tragedy, it must be converted to its reversed form before being accepted into the comedy play. A reversed number is a number written in Arabic numerals but the order of digits is reversed. The first digit becomes last and vice versa. For example, if the main hero had 1245 strawberries in the tragedy, he has 5421 of them now. Note that all the leading zeros are omitted. That means if the number ends with a zero, the zero is lost by reversing (e.g. 1200 gives 21). Also, note that the reversed number never has any trailing zeros. ACI needs to calculate with reversed numbers. Your task is to add two reversed numbers and output their reversed sum. Of course, the result is not unique because any particular number is a reversed form of several numbers (e.g. 23 could be 32, 320, or 3200 before reversing). Thus we must assume that no zeros were lost by reversing (e.g. assume that the original number was 23). -----Input----- The input consists of N cases. The first line of the input contains only positive integer N. Then follow the cases. Each case consists of exactly one line with two positive integers separated by space. These are the reversed numbers you are to add. Numbers will be at most 200 characters long. -----Output----- For each case, print exactly one line containing only one integer - the reversed sum of two reversed numbers. Omit any leading zeros in the output. -----Sample Input----- 3 24 1 4358 754 305 794 -----Sample Output----- 34 1998 1
#include<stdio.h> int reverse(int a) { int sum =0; while(a>0) { sum =sum*10 + (a%10); a = a/10; } return sum; } int main(){ int n; int a,b; scanf("%d",&n); for(int i=0;i<n;i++){ scanf("%d%d",&a,&b); a=reverse(a); b=reverse(b); printf("%d ",reverse(a+b)); } }
#include<stdio.h> int reverse(int a) { int sum =0; while(a>0) { sum =sum*10 + (a%10); a = a/10; } return sum; } int main(){ int n; int a,b; scanf("%d",&n); for(int i=0;i<n;i++){ scanf("%d%d",&a,&b); a=reverse(a); b=reverse(b); printf("%d ",reverse(a+b)); } }
train
APPS_structured
Many internet protocols these days include the option of associating a media type with the content being sent. The type is usually inferred from the file extension. You are to write a program that facilitates the lookup of media types for a number of files. You will be given a table of media type associations that associate a certain file extension with a certain media type. You will then be given a number of file names, and tasked to determine the correct media type for each file. A file extension is defined as the part of the file name after the final period. If a file name has no periods, then it has no extension and the media type cannot be determined. If the file extension is not present in the table, then the media type cannot be determined. In such cases you will print "unknown" as the media type. If the file extension does appear in the table (case matters), then print the associated media type. -----Input----- Input begins with 2 integers N and Q on a line. N is the number of media type associations, and Q is the number of file names. Following this are N lines, each containing a file extension and a media type, separated by a space. Finally, Q lines, each containing the name of a file. N and Q will be no greater than 100 each. File extensions will consist only of alphanumeric characters, will have length at most 10, and will be distinct. Media types will have length at most 50, and will contain only alphanumeric characters and punctuation. File names will consist only of alphanumeric characters and periods and have length at most 50. -----Output----- For each of the Q file names, print on a line the media type of the file. If there is no matching entry, print "unknown" (quotes for clarity). -----Sample Input----- 5 6 html text/html htm text/html png image/png svg image/svg+xml txt text/plain index.html this.file.has.lots.of.dots.txt nodotsatall virus.exe dont.let.the.png.fool.you case.matters.TXT -----Sample Output----- text/html text/plain unknown unknown unknown unknown
# cook your dish here n,q=map(int,input().split()) x={} for _ in range(n): a,b=map(str,input().split()) x[a]=b for _ in range(q): h=input().strip() if("." in h): c=h.split(".")[-1] if(c in x): print(x[c]) else: print("unknown") else: print("unknown")
# cook your dish here n,q=map(int,input().split()) x={} for _ in range(n): a,b=map(str,input().split()) x[a]=b for _ in range(q): h=input().strip() if("." in h): c=h.split(".")[-1] if(c in x): print(x[c]) else: print("unknown") else: print("unknown")
train
APPS_structured
Given an integer, write a function to determine if it is a power of two. Example 1: Input: 1 Output: true Explanation: 20 = 1 Example 2: Input: 16 Output: true Explanation: 24 = 16 Example 3: Input: 218 Output: false
class Solution: def isPowerOfTwo(self, n): """ :type n: int :rtype: bool """ # so let's take a look at what it means to be a power of two # 2^2 = 4 = 0100 | Now note when we subtract one | 2^2 - 1 = 3 = 0011 # 2^3 = 8 = 1000 | Now note when we subtract one | 2^3 - 1 = 7 = 0111 # Now note if we do n AND n-1, we should always get 0 | 1000 & 0111 = 0000 = 0 return n>0 and not (n & n-1) # This holds true for all powers of 2. However note if we used 0 & anything else, it would show to be a power of 2. # To fix this we can add another clause v & (earlier clause) or we can simply check if value is greater than 0.
class Solution: def isPowerOfTwo(self, n): """ :type n: int :rtype: bool """ # so let's take a look at what it means to be a power of two # 2^2 = 4 = 0100 | Now note when we subtract one | 2^2 - 1 = 3 = 0011 # 2^3 = 8 = 1000 | Now note when we subtract one | 2^3 - 1 = 7 = 0111 # Now note if we do n AND n-1, we should always get 0 | 1000 & 0111 = 0000 = 0 return n>0 and not (n & n-1) # This holds true for all powers of 2. However note if we used 0 & anything else, it would show to be a power of 2. # To fix this we can add another clause v & (earlier clause) or we can simply check if value is greater than 0.
train
APPS_structured
Given two equal-size strings s and t. In one step you can choose any character of t and replace it with another character. Return the minimum number of steps to make t an anagram of s. An Anagram of a string is a string that contains the same characters with a different (or the same) ordering. Example 1: Input: s = "bab", t = "aba" Output: 1 Explanation: Replace the first 'a' in t with b, t = "bba" which is anagram of s. Example 2: Input: s = "leetcode", t = "practice" Output: 5 Explanation: Replace 'p', 'r', 'a', 'i' and 'c' from t with proper characters to make t anagram of s. Example 3: Input: s = "anagram", t = "mangaar" Output: 0 Explanation: "anagram" and "mangaar" are anagrams. Example 4: Input: s = "xxyyzz", t = "xxyyzz" Output: 0 Example 5: Input: s = "friend", t = "family" Output: 4 Constraints: 1 <= s.length <= 50000 s.length == t.length s and t contain lower-case English letters only.
class Solution: def minSteps(self, s: str, t: str) -> int: help_dict = defaultdict(int) res = 0 for char in s: help_dict[char] += 1 for char in t: if help_dict[char] > 0: help_dict[char] -= 1 else: res += 1 return res
class Solution: def minSteps(self, s: str, t: str) -> int: help_dict = defaultdict(int) res = 0 for char in s: help_dict[char] += 1 for char in t: if help_dict[char] > 0: help_dict[char] -= 1 else: res += 1 return res
train
APPS_structured
Linked Lists - Get Nth Implement a GetNth() function that takes a linked list and an integer index and returns the node stored at the Nth index position. GetNth() uses the C numbering convention that the first node is index 0, the second is index 1, ... and so on. So for the list 42 -> 13 -> 666, GetNth() with index 1 should return Node(13); The index should be in the range [0..length-1]. If it is not, GetNth() should throw/raise an exception (`ArgumentException` in C#, `InvalidArgumentException` in PHP). You should also raise an exception (`ArgumentException` in C#, `InvalidArgumentException` in PHP) if the list is empty/null/None. Prerequisite Kata (may be in beta): - Linked Lists - Push & BuildOneTwoThree - Linked Lists - Length & Count > The push() and buildOneTwoThree() (`BuildOneTwoThree` in C#, `build_one_two_three()` in PHP) functions do not need to be redefined.
class Node(object): def __init__(self, data): self.data = data self.next = None def get_nth(node, index): assert(node and index >= 0) for _ in range(index): node = node.next assert(node) return node
class Node(object): def __init__(self, data): self.data = data self.next = None def get_nth(node, index): assert(node and index >= 0) for _ in range(index): node = node.next assert(node) return node
train
APPS_structured
You are given a colored permutation $p_1, p_2, \dots, p_n$. The $i$-th element of the permutation has color $c_i$. Let's define an infinite path as infinite sequence $i, p[i], p[p[i]], p[p[p[i]]] \dots$ where all elements have same color ($c[i] = c[p[i]] = c[p[p[i]]] = \dots$). We can also define a multiplication of permutations $a$ and $b$ as permutation $c = a \times b$ where $c[i] = b[a[i]]$. Moreover, we can define a power $k$ of permutation $p$ as $p^k=\underbrace{p \times p \times \dots \times p}_{k \text{ times}}$. Find the minimum $k > 0$ such that $p^k$ has at least one infinite path (i.e. there is a position $i$ in $p^k$ such that the sequence starting from $i$ is an infinite path). It can be proved that the answer always exists. -----Input----- The first line contains single integer $T$ ($1 \le T \le 10^4$) — the number of test cases. Next $3T$ lines contain test cases — one per three lines. The first line contains single integer $n$ ($1 \le n \le 2 \cdot 10^5$) — the size of the permutation. The second line contains $n$ integers $p_1, p_2, \dots, p_n$ ($1 \le p_i \le n$, $p_i \neq p_j$ for $i \neq j$) — the permutation $p$. The third line contains $n$ integers $c_1, c_2, \dots, c_n$ ($1 \le c_i \le n$) — the colors of elements of the permutation. It is guaranteed that the total sum of $n$ doesn't exceed $2 \cdot 10^5$. -----Output----- Print $T$ integers — one per test case. For each test case print minimum $k > 0$ such that $p^k$ has at least one infinite path. -----Example----- Input 3 4 1 3 4 2 1 2 2 3 5 2 3 4 5 1 1 2 3 4 5 8 7 4 5 6 1 8 3 2 5 3 6 4 7 5 8 4 Output 1 5 2 -----Note----- In the first test case, $p^1 = p = [1, 3, 4, 2]$ and the sequence starting from $1$: $1, p[1] = 1, \dots$ is an infinite path. In the second test case, $p^5 = [1, 2, 3, 4, 5]$ and it obviously contains several infinite paths. In the third test case, $p^2 = [3, 6, 1, 8, 7, 2, 5, 4]$ and the sequence starting from $4$: $4, p^2[4]=8, p^2[8]=4, \dots$ is an infinite path since $c_4 = c_8 = 4$.
T = int(input()) for _ in range(T): n = int(input()) perm = list([int(x) - 1 for x in input().split()]) color = list(map(int, input().split())) SMALL = n unseen = set(range(n)) while unseen: start = unseen.pop() l = [start] nex = start while perm[nex] != start: nex = perm[nex] l.append(nex) unseen.remove(nex) size = len(l) factors = [] curr = 1 while curr * curr <= size: if size % curr == 0: factors.append(curr) factors.append(size//curr) curr += 1 for f in factors: works = [True] * f for i in range(size): if color[l[i]] != color[l[i % f]]: works[i % f] = False for b in works: if b: SMALL = min(SMALL, f) break print(SMALL)
T = int(input()) for _ in range(T): n = int(input()) perm = list([int(x) - 1 for x in input().split()]) color = list(map(int, input().split())) SMALL = n unseen = set(range(n)) while unseen: start = unseen.pop() l = [start] nex = start while perm[nex] != start: nex = perm[nex] l.append(nex) unseen.remove(nex) size = len(l) factors = [] curr = 1 while curr * curr <= size: if size % curr == 0: factors.append(curr) factors.append(size//curr) curr += 1 for f in factors: works = [True] * f for i in range(size): if color[l[i]] != color[l[i % f]]: works[i % f] = False for b in works: if b: SMALL = min(SMALL, f) break print(SMALL)
train
APPS_structured
Chef has an array A consisting of N elements. He wants to find number of pairs of non-intersecting segments [a, b] and [c, d] (1 ≤ a ≤ b < c ≤ d ≤ N) such there is no number that occurs in the subarray {Aa, Aa+1, ... , Ab} and {Ac, Ac+1, ... , Ad} simultaneously. Help Chef to find this number. -----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 elements in the array. - The second line contains N space-separated integers A1, A2, ..., AN. -----Output----- - For each test case, output a single line containing one integer - number of pairs of non-intersecting segments. -----Constraints----- - 1 ≤ T ≤ 5 - 1 ≤ N ≤ 1000 - 1 ≤ Ai ≤ 109 -----Subtasks-----Subtask 1 (7 points) - 1 ≤ N ≤ 20Subtask 2 (34 points) - 1 ≤ N ≤ 300Subtask 3 (59 points) - Original constraints -----Example----- Input: 2 3 1 2 3 4 1 2 1 2 Output: 5 4 -----Explanation----- Example case 1. All possible variants are correct: {[1, 1], [2, 2]}, {[1, 1], [2, 3]}, {[1, 2], [3, 3]}, {[2, 2], [3, 3]}, {[1,1], [3, 3]}. Example case 2. Correct segments: {[1, 1], [2, 2]}, {[1, 1], [4, 4]}, {[2, 2], [3, 3]}, {[3, 3], [4, 4]}.
t = eval(input()) while t>0: n = eval(input()) ar = list(map(int,input().split())) c = 0 for i in range(0,n): for j in range(i,n): for k in range(j+1,n): for l in range(k,n): res = [] res = list(set(ar[i:j+1]).intersection(set(ar[k:l+1]))) #print ar[i:j+1], ar[k:l+1] if len(res)==0: c+=1 print(c) t-=1
t = eval(input()) while t>0: n = eval(input()) ar = list(map(int,input().split())) c = 0 for i in range(0,n): for j in range(i,n): for k in range(j+1,n): for l in range(k,n): res = [] res = list(set(ar[i:j+1]).intersection(set(ar[k:l+1]))) #print ar[i:j+1], ar[k:l+1] if len(res)==0: c+=1 print(c) t-=1
train
APPS_structured
For this game of `BINGO`, you will receive a single array of 10 numbers from 1 to 26 as an input. Duplicate numbers within the array are possible. Each number corresponds to their alphabetical order letter (e.g. 1 = A. 2 = B, etc). Write a function where you will win the game if your numbers can spell `"BINGO"`. They do not need to be in the right order in the input array). Otherwise you will lose. Your outputs should be `"WIN"` or `"LOSE"` respectively.
BINGO = {ord(c)-64 for c in "BINGO"} def bingo(lst): return "WIN" if set(lst) >= BINGO else "LOSE"
BINGO = {ord(c)-64 for c in "BINGO"} def bingo(lst): return "WIN" if set(lst) >= BINGO else "LOSE"
train
APPS_structured
You should have done Product Partitions I to do this second part. If you solved it, you should have notice that we try to obtain the multiplicative partitions with ```n ≤ 100 ```. In this kata we will have more challenging values, our ```n ≤ 10000```. So, we need a more optimized a faster code. We need the function ```prod_int_partII()``` that will give all the amount of different products, excepting the number itself multiplied by one. The function ```prod_int_partII()``` will receive two arguments, the number ```n``` for the one we have to obtain all the multiplicative partitions, and an integer s that determines the products that have an amount of factors equals to ```s```. The function will output a list with this structure: ```python [(1), (2), [(3)]] (1) Total amount of different products we can obtain, using the factors of n. (We do not consider the product n . 1) (2) Total amount of products that have an amount of factors equals to s. [(3)] A list of lists with each product represented with by a sorted list of the factors. All the product- lists should be sorted also. If we have only one product-list as a result, the function will give only the list and will not use the list of lists ``` Let's see some cases: ```python prod_int_partII(36, 3) == [8, 3, [[2, 2, 9], [2, 3, 6], [3, 3, 4]]] /// (1) ----> 8 # Amount of different products, they are: [2, 2, 3, 3], [2, 2, 9], [2, 3, 6], [2, 18], [3, 3, 4], [3, 12], [4, 9], [6, 6] (8 products) (2) ----> 3 # Amount of products with three factors (see them bellow) (3) ----> [[2, 2, 9], [2, 3, 6], [3, 3, 4]] # These are the products with 3 factors ``` ```python prod_int_partII(48, 5) == [11, 1, [2, 2, 2, 2, 3]] # Only one list. ``` Again consider that some numbers will not have multiplicative partitions. ```python prod_int_partII(37, 2) == [0, 0, []] ``` Happy coding!! (Recursion is advisable)
def prod_int_partII(n, s): part = list(mul_part_gen(n))[:-1] sub = [p for p in part if len(p) == s] return [len(part), len(sub), sub[0] if len(sub) == 1 else sub] def mul_part_gen(n, k=2): if n == 1: yield [] for i in range(k, n+1): if n % i == 0: for part in mul_part_gen(n//i, i): yield [i] + part
def prod_int_partII(n, s): part = list(mul_part_gen(n))[:-1] sub = [p for p in part if len(p) == s] return [len(part), len(sub), sub[0] if len(sub) == 1 else sub] def mul_part_gen(n, k=2): if n == 1: yield [] for i in range(k, n+1): if n % i == 0: for part in mul_part_gen(n//i, i): yield [i] + part
train
APPS_structured
Given two integer arrays of equal length target and arr. In one step, you can select any non-empty sub-array of arr and reverse it. You are allowed to make any number of steps. Return True if you can make arr equal to target, or False otherwise. Example 1: Input: target = [1,2,3,4], arr = [2,4,1,3] Output: true Explanation: You can follow the next steps to convert arr to target: 1- Reverse sub-array [2,4,1], arr becomes [1,4,2,3] 2- Reverse sub-array [4,2], arr becomes [1,2,4,3] 3- Reverse sub-array [4,3], arr becomes [1,2,3,4] There are multiple ways to convert arr to target, this is not the only way to do so. Example 2: Input: target = [7], arr = [7] Output: true Explanation: arr is equal to target without any reverses. Example 3: Input: target = [1,12], arr = [12,1] Output: true Example 4: Input: target = [3,7,9], arr = [3,7,11] Output: false Explanation: arr doesn't have value 9 and it can never be converted to target. Example 5: Input: target = [1,1,1,1,1], arr = [1,1,1,1,1] Output: true Constraints: target.length == arr.length 1 <= target.length <= 1000 1 <= target[i] <= 1000 1 <= arr[i] <= 1000
class Solution: def canBeEqual(self, target: List[int], arr: List[int]) -> bool: for i in range(len(target)): for j in range(i, len(target)): if arr[j] == target[i]: break else: return False arr[i:j+1] = reversed(arr[i:j+1:]) return arr == target
class Solution: def canBeEqual(self, target: List[int], arr: List[int]) -> bool: for i in range(len(target)): for j in range(i, len(target)): if arr[j] == target[i]: break else: return False arr[i:j+1] = reversed(arr[i:j+1:]) return arr == target
train
APPS_structured
The town sheriff dislikes odd numbers and wants all odd numbered families out of town! In town crowds can form and individuals are often mixed with other people and families. However you can distinguish the family they belong to by the number on the shirts they wear. As the sheriff's assistant it's your job to find all the odd numbered families and remove them from the town! ~~~if-not:cpp Challenge: You are given a list of numbers. The numbers each repeat a certain number of times. Remove all numbers that repeat an odd number of times while keeping everything else the same. ~~~ ~~~if:cpp Challenge: You are given a vector of numbers. The numbers each repeat a certain number of times. Remove all numbers that repeat an odd number of times while keeping everything else the same. ~~~ ```python odd_ones_out([1, 2, 3, 1, 3, 3]) = [1, 1] ``` In the above example: - the number 1 appears twice - the number 2 appears once - the number 3 appears three times `2` and `3` both appear an odd number of times, so they are removed from the list. The final result is: `[1,1]` Here are more examples: ```python odd_ones_out([1, 1, 2, 2, 3, 3, 3]) = [1, 1, 2, 2] odd_ones_out([26, 23, 24, 17, 23, 24, 23, 26]) = [26, 24, 24, 26] odd_ones_out([1, 2, 3]) = [] odd_ones_out([1]) = [] ``` Are you up to the challenge?
from collections import Counter def odd_ones_out(a): d = Counter(a) return [x for x in a if not d[x] % 2]
from collections import Counter def odd_ones_out(a): d = Counter(a) return [x for x in a if not d[x] % 2]
train
APPS_structured
-----Problem Statement----- One of the things JEC is known for is its GR (Group Recreation) where juniors and seniors do friendly interaction ;P As for the new session of 2020 seniors decided to have their first GR and give them some treat. Juniors were excited about it they came to college canteen aligned in a line and counted themselves one by one from left to right so that every junior gets his/her treat. But seniors played a game and they will treat only the ones who passes in this game. Game is simple all they need to do is to alternate their language (between Hindi and English) while telling their positions that is if the junior just before you told 2 in English you need to say 3 in Hindi . You do not want to be the one left without a treat. You are the junior standing at position $X$ from left and the counting could start from left or right you have to predict which number you have to speak and in which language when your turn comes. -----Input:----- - First line will contain $T$, number of testcases. Then the testcases follow. - Each testcase contains 2 lines first consist 2 space separated integers, $N$ (total count) , $X$ (your position from left), next line consist of 2 space separated characters L or R (Direction from which counting starts L-left, R-Right) and H or E (the language to start counting). -----Output:----- For each testcase, output a single line consisting space seperated Integer P and Character L where P is the number you will speak and L is the language (H or E). -----Constraints----- - $1 \leq T \leq 1000$ - $1 \leq N \leq 120$ - $1 \leq X \leq N$ -----Sample Input:----- 2 15 5 L H 20 14 R E *try to trim extra white spaces like new line during input in case of wrong answer -----Sample Output:----- 5 H 7 E -----EXPLANATION:----- - When counting starts from left with H it alternates like H E H E H….. on the fifth position H comes - When Count starts from right with E it alternates like E H E H E H E….. with E on the position of 14th student from right.
tt = int(input()) for _ in range(tt): n,x = map(int, input().rstrip().split(' ')) s, l = input().rstrip().split(' ') initial = l que = [] for i in range(n): que.append(initial) if initial=='H': initial = 'E' continue elif initial=='E': initial = 'H' continue if s=='R': dd = n-x+1 que = que[::-1] pp = que[-dd] else: dd = x pp = que[x-1] print(dd, end=" ") print(pp)
tt = int(input()) for _ in range(tt): n,x = map(int, input().rstrip().split(' ')) s, l = input().rstrip().split(' ') initial = l que = [] for i in range(n): que.append(initial) if initial=='H': initial = 'E' continue elif initial=='E': initial = 'H' continue if s=='R': dd = n-x+1 que = que[::-1] pp = que[-dd] else: dd = x pp = que[x-1] print(dd, end=" ") print(pp)
train
APPS_structured
The business has been suffering for years under the watch of Homie the Clown. Every time there is a push to production it requires 500 hands-on deck, a massive manual process, and the fire department is on stand-by along with Fire Marshall Bill the king of manual configuration management. He is called a Fire Marshall because production pushes often burst into flames and rollbacks are a hazard. The business demands change and as such has hired a new leader who wants to convert it all to DevOps…..there is a new Sheriff in town. The Sheriff's first order of business is to build a DevOps team. He likes Microservices, Cloud, Open-Source, and wants to push to production 9500 times per day without even pressing a button, beautiful seamless immutable infrastructure properly baked in the Continuous Delivery oven is the goal. The only problem is Homie the Clown along with Legacy Pete are grandfathered in and union, they started out in the era of green screens and punch cards and are set in their ways. They are not paid by an outcome but instead are measured by the amount of infrastructure under management and total staff headcount. The Sheriff has hired a new team of DevOps Engineers. They advocate Open Source, Cloud, and never doing a manual task more than one time. They believe Operations to be a first class citizen with Development and are preparing to shake things up within the company. Since Legacy is not going away, yet, the Sheriff's job is to get everyone to cooperate so DevOps and the Cloud will be standard. The New Kids on the Block have just started work and are looking to build common services with Legacy Pete and Homie the Clown. ``` Every Time the NKOTB propose a DevOps pattern…… Homie stands up and says "Homie don't Play that!" IE: NKOTB Say -> "We need Cloud now!" Homie Say -> "Cloud! Homie dont play that!" NKOTB Say -> "We need Automation now!" Homie Say -> "Automation! Homie dont play that!" NKOTB Say -> "We need Microservices now!" Homie Say -> "Microservices! Homie dont play that!" ``` Task You will receive a two-dimensional array with strings made of the NKOTB’s requirements. Each Array contains a domain of DevOps patterns that each of the 5 NKOTB are asking for. The requirements array will ALWAYS have five sub-arrays structured like this: ``` requirements[0] = monitoring requirements[1] = automation requirements[2] = deployment requirements[3] = cloud requirements[4] = microservices Each sub-array will always contain strings in the same format The strings will always be in the following format(case insensitive): "We need Microservices now!" Your job is to create the response from Homie the Clown following the pattern above. Then return the responses in an array. "Microservices! Homie dont play that!" ``` The first word of the response is always Capitalized and all other letters are lowercase regardless of how you recieve them, the rest of the sentence is always in the format ``` Homie dont play that!```. Strings should be returned in the same order. ``` In addition to the responses create a count of each domain and return it as the last element of the return array in the following format. '6 monitoring objections, 4 automation, 6 deployment pipeline, 6 cloud, and 3 microservices.' ``` For more information on Homie the Clown. https://www.youtube.com/watch?v=_QhuBIkPXn0 Fire Marshall Bill on Vacation! https://www.youtube.com/watch?v=IIIsCB4Y8sw#t=202.002651
import re def nkotb_vs_homie(requirements): return ['{}! Homie dont play that!'.format(s[8:-5].capitalize()) for r in requirements for s in r]\ + ['{} monitoring objections, {} automation, {} deployment pipeline, {} cloud, and {} microservices.'.format(*map(len, requirements))]
import re def nkotb_vs_homie(requirements): return ['{}! Homie dont play that!'.format(s[8:-5].capitalize()) for r in requirements for s in r]\ + ['{} monitoring objections, {} automation, {} deployment pipeline, {} cloud, and {} microservices.'.format(*map(len, requirements))]
train
APPS_structured
There are $N$ cities on a circle, numbered $1$ through $N$. For each $i$ ($1 \le i \le N-1$), cities $i$ and $i+1$ are directly connected by a bidirectional road with length $A_i$, and cities $N$ and $1$ are also directly connected by a bidirectional road with length $A_N$. However, we do not know the lengths of some roads. For each city $i$, we do know that it has an opposite city — formally, there is a city $j \neq i$ such that the clockwise distance between cities $i$ and $j$ is equal to the counterclockwise distance between these cities. Please find the lengths of all roads in such a way that the above condition is satisfied and the sum of lengths of all roads is minimised. -----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 the input contains a single integer $N$. - The second line contains $N$ space-separated integers $A_1, A_2, \dots, A_N$. For each valid $i$, $A_i = -1$ denotes that the length of road $i$ is unknown. -----Output----- For each test case, print a line containing the string "NO" if there is no solution or "YES" otherwise. If a solution exists, print a second line containing $N$ space-separated positive integers — the lengths of all roads in your solution. Each of these integers should be $\le 10^9$. If there are multiple solutions, you may print any one. -----Constraints----- - $1 \le T \le 100$ - $3 \le N \le 10^5$ - $1 \le A_i \le 10^9$ or $A_i = -1$ for each valid $i$ - the sum of $N$ for all test cases does not exceed $3\cdot 10^5$ -----Subtasks----- Subtask #1 (10 points): $N \le 4$ Subtask #2 (20 points): $A_i = \pm 1$ for each valid $i$ Subtask #3 (70 points): original constraints -----Example Input----- 4 4 1 1 1 1 4 1 1 1 2 4 1 -1 -1 4 4 1 -1 2 -1 -----Example Output----- YES 1 1 1 1 NO YES 1 4 1 4 NO
t = int(input()) while t>0: t -= 1 n = int(input()) dis = [int(x) for x in input().split()] if n%2 == 1: print('NO') continue mid = n//2 for i in range(mid): if dis[i] == -1 and dis[mid+i] == -1: dis[i] = dis[i+mid] = 1 elif dis[i] == -1: dis[i] = dis[i+mid] elif dis[i+mid] == -1: dis[i+mid] = dis[i] flag = True for i in range(mid): if dis[i] != dis[i+mid]: flag = False print('NO') break if flag: print('YES') for i in range(n): print(dis[i], end=' ') print()
t = int(input()) while t>0: t -= 1 n = int(input()) dis = [int(x) for x in input().split()] if n%2 == 1: print('NO') continue mid = n//2 for i in range(mid): if dis[i] == -1 and dis[mid+i] == -1: dis[i] = dis[i+mid] = 1 elif dis[i] == -1: dis[i] = dis[i+mid] elif dis[i+mid] == -1: dis[i+mid] = dis[i] flag = True for i in range(mid): if dis[i] != dis[i+mid]: flag = False print('NO') break if flag: print('YES') for i in range(n): print(dis[i], end=' ') print()
train
APPS_structured
Get n seconds before the target time. See Example Test Cases about the format.
from dateutil import parser import datetime def seconds_ago(s,n): timej = parser.parse(s) - datetime.timedelta(seconds=n) return str(timej)
from dateutil import parser import datetime def seconds_ago(s,n): timej = parser.parse(s) - datetime.timedelta(seconds=n) return str(timej)
train
APPS_structured
Determine the total number of digits in the integer (`n>=0`) given as input to the function. For example, 9 is a single digit, 66 has 2 digits and 128685 has 6 digits. Be careful to avoid overflows/underflows. All inputs will be valid.
def digits(n): print(n) z=[int(x) for x in str(n)] # your code here print(z) return len(z)
def digits(n): print(n) z=[int(x) for x in str(n)] # your code here print(z) return len(z)
train
APPS_structured
Given an integer N, Chef wants to find the smallest positive integer M such that the bitwise XOR of M and M+1 is N. If no such M exists output -1. -----Input----- The first line of input contain an integer T denoting the number of test cases. Each of the following T lines contains an integer N for that test case. -----Output----- For each test case, output a single line containing the number M or -1 as described above. -----Constraints----- - 1 ≤ T ≤ 5000 - 1 ≤ N ≤ 230 -----Example----- Input: 1 3 Output: 1 -----Explanation-----First Example : M desired in the problem would be 1. As bitwise XOR of 1 and 2 is equal to 3.
d = {1:0} st = 1 prev = 1 while True: new = st+st+1 d[new] = prev prev = new st = new if st>2*(2**30): break for _ in range(int(input())): n = int(input()) if n == 1: print(2) else: try: print(d[n]) except: print(-1)
d = {1:0} st = 1 prev = 1 while True: new = st+st+1 d[new] = prev prev = new st = new if st>2*(2**30): break for _ in range(int(input())): n = int(input()) if n == 1: print(2) else: try: print(d[n]) except: print(-1)
train
APPS_structured
In 1978 the British Medical Journal reported on an outbreak of influenza at a British boarding school. There were `1000` students. The outbreak began with one infected student. We want to study the spread of the disease through the population of this school. The total population may be divided into three: the infected `(i)`, those who have recovered `(r)`, and those who are still susceptible `(s)` to get the disease. We will study the disease on a period of `tm` days. One model of propagation uses 3 differential equations: ``` (1) s'(t) = -b * s(t) * i(t) (2) i'(t) = b * s(t) * i(t) - a * i(t) (3) r'(t) = a * i(t) ``` where `s(t), i(t), r(t)` are the susceptible, infected, recovered at time `t` and `s'(t), i'(t), r'(t)` the corresponding derivatives. `b` and `a` are constants: `b` is representing a number of contacts which can spread the disease and `a` is a fraction of the infected that will recover. We can transform equations `(1), (2), (3)` in finite differences (https://en.wikipedia.org/wiki/Finite_difference_method#Example:_ordinary_differential_equation) (http://www.codewars.com/kata/56347fcfd086de8f11000014) ``` (I) S[k+1] = S[k] - dt * b * S[k] * I[k] (II) I[k+1] = I[k] + dt * (b * S[k] * I[k] - a * I[k]) (III) R[k+1] = R[k] + dt * I[k] *a ``` The interval `[0, tm]` will be divided in `n` small intervals of length `dt = tm/n`. Initial conditions here could be : `S0 = 999, I0 = 1, R0 = 0` Whatever S0 and I0, R0 (number of recovered at time 0) is always 0. The function `epidemic` will return the maximum number of infected as an *integer* (truncate to integer the result of max(I)). # Example: ``` tm = 14 ;n = 336 ;s0 = 996 ;i0 = 2 ;b = 0.00206 ;a = 0.41 epidemic(tm, n, s0, i0, b, a) --> 483 ``` # Notes: - You will pass the tests if `abs(actual - expected) <= 1` - Keeping track of the values of susceptible, infected and recovered you can plot the solutions of the 3 differential equations. See an example below on the plot. ![alternative text](http://i.imgur.com/xB6VSqzm.png)
def epidemic(tm, n, s0, i0, b, a): s = [s0]; i = [i0]; r = [0] t=0 dt = tm/n t += dt for k in range(n): s[k] = s[k-1] - dt*b*s[k-1]*i[k-1] i[k] = i[k-1] + dt * (b * s[k-1] * i[k-1] - a * i[k-1]) r[k] = r[k-1] + dt * i[k-1] *a s.append(s[k]) i.append(i[k]) r.append(r[k]) return int(max(i))
def epidemic(tm, n, s0, i0, b, a): s = [s0]; i = [i0]; r = [0] t=0 dt = tm/n t += dt for k in range(n): s[k] = s[k-1] - dt*b*s[k-1]*i[k-1] i[k] = i[k-1] + dt * (b * s[k-1] * i[k-1] - a * i[k-1]) r[k] = r[k-1] + dt * i[k-1] *a s.append(s[k]) i.append(i[k]) r.append(r[k]) return int(max(i))
train
APPS_structured
You are given a sequence of integers $A_1,A_2,…,A_N$ and a magical non-zero integer $x$ You have to select a subsegment of sequence A (possibly empty), and replace the elements in that subsegment after dividing them by x. Formally, replace any one subsegment $A_l, A_{l+1}, ..., A_r$ with $A_l/x, A_{l+1}/x, ..., A_r/x$ where $l \leq r$ What is the minimum possible sum you can obtain? Note: The given operation can only be performed once -----Input ----- - The first line of the input contains two positive integer n denoting the size of array, and x denoting the magical integer - Next line contains $N$ space separated integers -----Output----- Single line containing one real number, denoting the minimum possible sum you can obtain. Your answer will be considered correct if its absolute or relative error does not exceed $10^{-2}$ -----Constraints----- - $1 \leq n \leq 10^3$ - $1 \leq |x| \leq 10^3$ - $ |A_i| \leq 10^3$ -----Sample Input----- 3 2 1 -2 3 -----Sample Output----- 0.5 -----Explanation----- Array 1 -2 3, selecting subsegment {3}, you get 1 -2 1.5, which gives $sum=0.5$
# cook your dish here n,x=list(map(int,input().split())) a=list(map(int,input().split())) total=sum(a) current_max=a[0] total_max=a[0] for i in range(1,len(a)): current_max=max(a[i],current_max+a[i]) total_max=max(total_max,current_max) print(total-total_max+(total_max/x))
# cook your dish here n,x=list(map(int,input().split())) a=list(map(int,input().split())) total=sum(a) current_max=a[0] total_max=a[0] for i in range(1,len(a)): current_max=max(a[i],current_max+a[i]) total_max=max(total_max,current_max) print(total-total_max+(total_max/x))
train
APPS_structured
You've purchased a ready-meal from the supermarket. The packaging says that you should microwave it for 4 minutes and 20 seconds, based on a 600W microwave. Oh no, your microwave is 800W! How long should you cook this for?! ___ # Input You'll be given 4 arguments: ## 1. needed power The power of the needed microwave. Example: `"600W"` ## 2. minutes The number of minutes shown on the package. Example: `4` ## 3. seconds The number of seconds shown on the package. Example: `20` ## 4. power The power of your microwave. Example: `"800W"` ___ # Output The amount of time you should cook the meal for formatted as a string. Example: `"3 minutes 15 seconds"` Note: the result should be rounded up. ``` 59.2 sec --> 60 sec --> return "1 minute 0 seconds" ``` ___ ## All comments/feedback/translations appreciated.
import math def cooking_time(needed_power, minutes, seconds, power): in_seconds = 60 * minutes + seconds increase = int(needed_power[:-1]) / int(power[:-1]) new_seconds = in_seconds * increase output_minutes = int(new_seconds/60) output_seconds = new_seconds % 60 if math.ceil(output_seconds) == 60: output_seconds = 0 output_minutes += 1 return str(math.ceil(output_minutes)) + ' minutes ' + str(math.ceil(output_seconds)) + ' seconds'
import math def cooking_time(needed_power, minutes, seconds, power): in_seconds = 60 * minutes + seconds increase = int(needed_power[:-1]) / int(power[:-1]) new_seconds = in_seconds * increase output_minutes = int(new_seconds/60) output_seconds = new_seconds % 60 if math.ceil(output_seconds) == 60: output_seconds = 0 output_minutes += 1 return str(math.ceil(output_minutes)) + ' minutes ' + str(math.ceil(output_seconds)) + ' seconds'
train
APPS_structured
Reverse and invert all integer values in a given list. Python: reverse_invert([1,12,'a',3.4,87,99.9,-42,50,5.6]) = [-1,-21,-78,24,-5] Ignore all other types than integer.
def reverse_invert(lst): return [(-1)**(v>0)*int(str(abs(v))[::-1]) for v in lst if isinstance(v,int)]
def reverse_invert(lst): return [(-1)**(v>0)*int(str(abs(v))[::-1]) for v in lst if isinstance(v,int)]
train
APPS_structured
Write a function that returns the count of characters that have to be removed in order to get a string with no consecutive repeats. *Note:* This includes any characters ## Examples ```python 'abbbbc' => 'abc' # answer: 3 'abbcca' => 'abca' # answer: 2 'ab cca' => 'ab ca' # answer: 1 ```
def count_repeats(str): return sum(a == b for a, b in zip(str, str[1:]))
def count_repeats(str): return sum(a == b for a, b in zip(str, str[1:]))
train
APPS_structured
Alex and Lee continue their games with piles of stones.  There are a number of piles arranged in a row, and each pile has a positive integer number of stones piles[i].  The objective of the game is to end with the most stones.  Alex and Lee take turns, with Alex starting first.  Initially, M = 1. On each player's turn, that player can take all the stones in the first X remaining piles, where 1 <= X <= 2M.  Then, we set M = max(M, X). The game continues until all the stones have been taken. Assuming Alex and Lee play optimally, return the maximum number of stones Alex can get. Example 1: Input: piles = [2,7,9,4,4] Output: 10 Explanation: If Alex takes one pile at the beginning, Lee takes two piles, then Alex takes 2 piles again. Alex can get 2 + 4 + 4 = 10 piles in total. If Alex takes two piles at the beginning, then Lee can take all three piles left. In this case, Alex get 2 + 7 = 9 piles in total. So we return 10 since it's larger. Constraints: 1 <= piles.length <= 100 1 <= piles[i] <= 10 ^ 4
class Solution: def stoneGameII(self, piles: List[int]) -> int: @lru_cache(maxsize=None) def minimax(st, m, player): if st >= len(piles): return 0 if player: return max([sum(piles[st:st+x]) + minimax(st+x, max(m,x), player^1) for x in range(1, 2*m+1)]) else: return min([minimax(st+x, max(m,x), player^1) for x in range(1, 2*m+1)]) return minimax(0, 1, 1) # [NOTE] Really good explanation here: # https://leetcode.com/problems/stone-game-ii/discuss/345222/Python-Minimax-DP-solution # The idea of minimax : # If am the player 1 (whose winning sum we are trying to calculate), then I recurse on all possibilities and get the max. # If am the player 2 (the opponent), then I try to minimize what P1 gets, and since we are not interested in what score P2 gets, we only calculate the min(all P1 next moves) and dont include the score P2 gets. # Thanks to @douzigege for his comment which explains the minimax scenario specifically for this problem. # if player == 1st player, # gain = first x piles + minimax(..., 2nd player), where the gain is maximized # if player == 2nd player, # gain = 0 + minimax(..., 1st player), where the gain is minimized because the 2nd player tries to maximize this # TLE for this input without@lru_cache # [8270,7145,575,5156,5126,2905,8793,7817,5532,5726,7071,7730,5200,5369,5763,7148,8287,9449,7567,4850,1385,2135,1737,9511,8065,7063,8023,7729,7084,8407]
class Solution: def stoneGameII(self, piles: List[int]) -> int: @lru_cache(maxsize=None) def minimax(st, m, player): if st >= len(piles): return 0 if player: return max([sum(piles[st:st+x]) + minimax(st+x, max(m,x), player^1) for x in range(1, 2*m+1)]) else: return min([minimax(st+x, max(m,x), player^1) for x in range(1, 2*m+1)]) return minimax(0, 1, 1) # [NOTE] Really good explanation here: # https://leetcode.com/problems/stone-game-ii/discuss/345222/Python-Minimax-DP-solution # The idea of minimax : # If am the player 1 (whose winning sum we are trying to calculate), then I recurse on all possibilities and get the max. # If am the player 2 (the opponent), then I try to minimize what P1 gets, and since we are not interested in what score P2 gets, we only calculate the min(all P1 next moves) and dont include the score P2 gets. # Thanks to @douzigege for his comment which explains the minimax scenario specifically for this problem. # if player == 1st player, # gain = first x piles + minimax(..., 2nd player), where the gain is maximized # if player == 2nd player, # gain = 0 + minimax(..., 1st player), where the gain is minimized because the 2nd player tries to maximize this # TLE for this input without@lru_cache # [8270,7145,575,5156,5126,2905,8793,7817,5532,5726,7071,7730,5200,5369,5763,7148,8287,9449,7567,4850,1385,2135,1737,9511,8065,7063,8023,7729,7084,8407]
train
APPS_structured
Write a simple function that takes polar coordinates (an angle in degrees and a radius) and returns the equivalent cartesian coordinates (rouded to 10 places). ``` For example: coordinates(90,1) => (0.0, 1.0) coordinates(45, 1) => (0.7071067812, 0.7071067812) ```
from math import radians, sin, cos def coordinates(degrees, radius): return (round(radius*cos(radians(degrees)),10),round(radius*sin(radians(degrees)),10))
from math import radians, sin, cos def coordinates(degrees, radius): return (round(radius*cos(radians(degrees)),10),round(radius*sin(radians(degrees)),10))
train
APPS_structured
Chef has $N$ axis-parallel rectangles in a 2D Cartesian coordinate system. These rectangles may intersect, but it is guaranteed that all their $4N$ vertices are pairwise distinct. Unfortunately, Chef lost one vertex, and up until now, none of his fixes have worked (although putting an image of a point on a milk carton might not have been the greatest idea after all…). Therefore, he gave you the task of finding it! You are given the remaining $4N-1$ points and you should find the missing one. -----Input----- - The first line of the input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows. - The first line of each test case contains a single integer $N$. - Then, $4N-1$ lines follow. Each of these lines contains two space-separated integers $x$ and $y$ denoting a vertex $(x, y)$ of some rectangle. -----Output----- For each test case, print a single line containing two space-separated integers $X$ and $Y$ ― the coordinates of the missing point. It can be proved that the missing point can be determined uniquely. -----Constraints----- - $T \le 100$ - $1 \le N \le 2 \cdot 10^5$ - $|x|, |y| \le 10^9$ - the sum of $N$ over all test cases does not exceed $2 \cdot 10^5$ -----Subtasks----- Subtask #1 (20 points): - $T = 5$ - $N \le 20$ Subtask #2 (30 points): $|x|, |y| \le 10^5$ Subtask #3 (50 points): original constraints -----Example Input----- 1 2 1 1 1 2 4 6 2 1 9 6 9 3 4 3 -----Example Output----- 2 2 -----Explanation----- The original set of points are: Upon adding the missing point $(2, 2)$, $N = 2$ rectangles can be formed:
test_case = int(input()) while test_case : n = int(input()) xdict = {} ydict = {} total_points = 4*n-1 for _ in range(total_points) : x,y = map(int, input().split()) if x not in xdict : xdict[x] = 1 else: xdict[x] += 1 if y not in ydict : ydict[y] = 1 else: ydict[y] += 1 for key in xdict.keys() : if xdict[key] % 2 != 0 : print(key, end = ' ') break for key in ydict.keys(): if ydict[key] % 2 != 0 : print(key) break test_case -= 1
test_case = int(input()) while test_case : n = int(input()) xdict = {} ydict = {} total_points = 4*n-1 for _ in range(total_points) : x,y = map(int, input().split()) if x not in xdict : xdict[x] = 1 else: xdict[x] += 1 if y not in ydict : ydict[y] = 1 else: ydict[y] += 1 for key in xdict.keys() : if xdict[key] % 2 != 0 : print(key, end = ' ') break for key in ydict.keys(): if ydict[key] % 2 != 0 : print(key) break test_case -= 1
train
APPS_structured
*This is the advanced version of the [Minimum and Maximum Product of k Elements](https://www.codewars.com/kata/minimum-and-maximum-product-of-k-elements/) kata.* --- Given a list of **integers** and a positive integer `k` (> 0), find the minimum and maximum possible product of `k` elements taken from the list. If you cannot take enough elements from the list, return `None`/`nil`. ## Examples ```python numbers = [1, -2, -3, 4, 6, 7] k = 1 ==> -3, 7 k = 2 ==> -21, 42 # -3*7, 6*7 k = 3 ==> -126, 168 # -3*6*7, 4*6*7 k = 7 ==> None # there are only 6 elements in the list ``` Note: the test lists can contain up to 500 elements, so a naive approach will not work. --- ## My other katas If you enjoyed this kata then please try [my other katas](https://www.codewars.com/collections/katas-created-by-anter69)! :-) #### *Translations are welcome!*
from functools import reduce def find_min_max_product(arr, k): if k <= len(arr): arr = sorted(arr, key=abs) lasts = arr[-k:] v1 = reduce(int.__mul__, lasts) v0 = reduce(int.__mul__, arr[:k]) first_SameOrOpp = [next((v for v in lasts if cmp(v<0, v1<0) ), None) for cmp in (int.__eq__, int.__ne__)] prevVal_OppOrSame = [next((v for v in reversed(arr[:-k]) if cmp(v<0, v1<0) ), None) for cmp in (int.__ne__, int.__eq__)] ans = [v0,v1] + [ v1*n//f for f,n in zip(first_SameOrOpp, prevVal_OppOrSame) if None not in (f,n) ] return min(ans), max(ans)
from functools import reduce def find_min_max_product(arr, k): if k <= len(arr): arr = sorted(arr, key=abs) lasts = arr[-k:] v1 = reduce(int.__mul__, lasts) v0 = reduce(int.__mul__, arr[:k]) first_SameOrOpp = [next((v for v in lasts if cmp(v<0, v1<0) ), None) for cmp in (int.__eq__, int.__ne__)] prevVal_OppOrSame = [next((v for v in reversed(arr[:-k]) if cmp(v<0, v1<0) ), None) for cmp in (int.__ne__, int.__eq__)] ans = [v0,v1] + [ v1*n//f for f,n in zip(first_SameOrOpp, prevVal_OppOrSame) if None not in (f,n) ] return min(ans), max(ans)
train
APPS_structured
Given a m * n matrix mat and an integer K, return a matrix answer where each answer[i][j] is the sum of all elements mat[r][c] for i - K <= r <= i + K, j - K <= c <= j + K, and (r, c) is a valid position in the matrix. Example 1: Input: mat = [[1,2,3],[4,5,6],[7,8,9]], K = 1 Output: [[12,21,16],[27,45,33],[24,39,28]] Example 2: Input: mat = [[1,2,3],[4,5,6],[7,8,9]], K = 2 Output: [[45,45,45],[45,45,45],[45,45,45]] Constraints: m == mat.length n == mat[i].length 1 <= m, n, K <= 100 1 <= mat[i][j] <= 100
class Solution: def matrixBlockSum(self, mat: List[List[int]], K: int) -> List[List[int]]: m, n = len(mat), len(mat[0]) res = [[0]*n for _ in range(m)] # vert_slid_win = [0]*(K*2+1) # for ii in range(0, K+1): # if ii>=0 and ii<m: # vert_slid_win[ii] = sum([mat[ii][c] for c in range(0, K+1) if c >=0 and c<m]) for i in range(m): hori_slid_win = [0]*(K*2+1) for jj in range(0, K+1): if jj>=0 and jj<n: hori_slid_win[jj+K] = sum([mat[r][jj] for r in range(i - K, i+K+1) if r >=0 and r<m]) for j in range(n): res[i][j] = sum(hori_slid_win) hori_slid_win.pop(0) if j+K+1< n: hori_slid_win.append(sum([mat[r][j+K+1] for r in range(i - K, i+K+1) if r >=0 and r<m])) # print(hori_slid_win) return res
class Solution: def matrixBlockSum(self, mat: List[List[int]], K: int) -> List[List[int]]: m, n = len(mat), len(mat[0]) res = [[0]*n for _ in range(m)] # vert_slid_win = [0]*(K*2+1) # for ii in range(0, K+1): # if ii>=0 and ii<m: # vert_slid_win[ii] = sum([mat[ii][c] for c in range(0, K+1) if c >=0 and c<m]) for i in range(m): hori_slid_win = [0]*(K*2+1) for jj in range(0, K+1): if jj>=0 and jj<n: hori_slid_win[jj+K] = sum([mat[r][jj] for r in range(i - K, i+K+1) if r >=0 and r<m]) for j in range(n): res[i][j] = sum(hori_slid_win) hori_slid_win.pop(0) if j+K+1< n: hori_slid_win.append(sum([mat[r][j+K+1] for r in range(i - K, i+K+1) if r >=0 and r<m])) # print(hori_slid_win) return res
train
APPS_structured
### Longest Palindrome Find the length of the longest substring in the given string `s` that is the same in reverse. As an example, if the input was “I like racecars that go fast”, the substring (`racecar`) length would be `7`. If the length of the input string is `0`, the return value must be `0`. ### Example: ``` "a" -> 1 "aab" -> 2 "abcde" -> 1 "zzbaabcd" -> 4 "" -> 0 ```
def longest_palindrome (s): longest = 0 for j in range(1, len(s)+1): for i in range(j): t = s[i:j] if t == t[::-1]: longest = max(longest, len(t)) return longest
def longest_palindrome (s): longest = 0 for j in range(1, len(s)+1): for i in range(j): t = s[i:j] if t == t[::-1]: longest = max(longest, len(t)) return longest
train
APPS_structured
You are given an array of positive and negative integers and a number ```n``` and ```n > 1```. The array may have elements that occurs more than once. Find all the combinations of n elements of the array that their sum are 0. ```python arr = [1, -1, 2, 3, -2] n = 3 find_zero_sum_groups(arr, n) == [-2, -1, 3] # -2 - 1 + 3 = 0 ``` The function should ouput every combination or group in increasing order. We may have more than one group: ```python arr = [1, -1, 2, 3, -2, 4, 5, -3 ] n = 3 find_zero_sum_groups(arr, n) == [[-3, -2, 5], [-3, -1, 4], [-3, 1, 2], [-2, -1, 3]] ``` In the case above the function should output a sorted 2D array. The function will not give a group twice, or more, only once. ```python arr = [1, -1, 2, 3, -2, 4, 5, -3, -3, -1, 2, 1, 4, 5, -3 ] n = 3 find_zero_sum_groups(arr, n) == [[-3, -2, 5], [-3, -1, 4], [-3, 1, 2], [-2, -1, 3]] ``` If there are no combinations with sum equals to 0, the function will output an alerting message. ```python arr = [1, 1, 2, 3] n = 2 find_zero_sum_groups(arr, n) == "No combinations" ``` If the function receives an empty array will output an specific alert: ```python arr = [] n = 2 find_zero_sum_groups(arr, n) == "No elements to combine" ``` As you have seen the solutions may have a value occurring only once. Enjoy it!
from itertools import combinations def find_zero_sum_groups(a, n): li = sorted(map(sorted,filter(lambda x:sum(x)==0,combinations(set(a),n)))) return li if len(li)>1 else li[0] if li else "No combinations" if a else "No elements to combine"
from itertools import combinations def find_zero_sum_groups(a, n): li = sorted(map(sorted,filter(lambda x:sum(x)==0,combinations(set(a),n)))) return li if len(li)>1 else li[0] if li else "No combinations" if a else "No elements to combine"
train
APPS_structured
Some numbers have funny properties. For example: > 89 --> 8¹ + 9² = 89 * 1 > 695 --> 6² + 9³ + 5⁴= 1390 = 695 * 2 > 46288 --> 4³ + 6⁴+ 2⁵ + 8⁶ + 8⁷ = 2360688 = 46288 * 51 Given a positive integer n written as abcd... (a, b, c, d... being digits) and a positive integer p - we want to find a positive integer k, if it exists, such as the sum of the digits of n taken to the successive powers of p is equal to k * n. In other words: > Is there an integer k such as : (a ^ p + b ^ (p+1) + c ^(p+2) + d ^ (p+3) + ...) = n * k If it is the case we will return k, if not return -1. **Note**: n and p will always be given as strictly positive integers. ```python dig_pow(89, 1) should return 1 since 8¹ + 9² = 89 = 89 * 1 dig_pow(92, 1) should return -1 since there is no k such as 9¹ + 2² equals 92 * k dig_pow(695, 2) should return 2 since 6² + 9³ + 5⁴= 1390 = 695 * 2 dig_pow(46288, 3) should return 51 since 4³ + 6⁴+ 2⁵ + 8⁶ + 8⁷ = 2360688 = 46288 * 51 ```
def dig_pow(n, p): digits = [int(d) for d in str(n)] sum = 0 for i, d in enumerate(digits): sum += d ** (p+i) if sum % n == 0: return sum / n else: return -1
def dig_pow(n, p): digits = [int(d) for d in str(n)] sum = 0 for i, d in enumerate(digits): sum += d ** (p+i) if sum % n == 0: return sum / n else: return -1
train
APPS_structured
The city of Siruseri is impeccably planned. The city is divided into a rectangular array of cells with $M$ rows and $N$ columns. Each cell has a metro station. There is one train running left to right and back along each row, and one running top to bottom and back along each column. Each trains starts at some time $T$ and goes back and forth along its route (a row or a column) forever. Ordinary trains take two units of time to go from one station to the next. There are some fast trains that take only one unit of time to go from one station to the next. Finally, there are some slow trains that take three units of time to go from one station the next. You may assume that the halting time at any station is negligible. Here is a description of a metro system with $3$ rows and $4$ columns: $ $ S(1) F(2) O(2) F(4) F(3) . . . . S(2) . . . . O(2) . . . . $ $ The label at the beginning of each row/column indicates the type of train (F for fast, O for ordinary, S for slow) and its starting time. Thus, the train that travels along row 1 is a fast train and it starts at time $3$. It starts at station ($1$, $1$) and moves right, visiting the stations along this row at times $3, 4, 5$ and $6$ respectively. It then returns back visiting the stations from right to left at times $6, 7, 8$ and $9$. It again moves right now visiting the stations at times $9, 10, 11$ and $12$, and so on. Similarly, the train along column $3$ is an ordinary train starting at time $2$. So, starting at the station ($3$,$1$), it visits the three stations on column $3$ at times $2, 4$ and $6$, returns back to the top of the column visiting them at times $6,8$ and $10$, and so on. Given a starting station, the starting time and a destination station, your task is to determine the earliest time at which one can reach the destination using these trains. For example suppose we start at station ($2$,$3$) at time $8$ and our aim is to reach the station ($1$,$1$). We may take the slow train of the second row at time $8$ and reach ($2$,$4$) at time $11$. It so happens that at time $11$, the fast train on column $4$ is at ($2$,$4$) travelling upwards, so we can take this fast train and reach ($1$,$4$) at time $12$. Once again we are lucky and at time $12$ the fast train on row $1$ is at ($1$,$4$), so we can take this fast train and reach ($1$, $1$) at time $15$. An alternative route would be to take the ordinary train on column $3$ from ($2$,$3$) at time $8$ and reach ($1$,$3$) at time $10$. We then wait there till time $13$ and take the fast train on row $1$ going left, reaching ($1$,$1$) at time $15$. You can verify that there is no way of reaching ($1$,$1$) earlier than that. -----Input:----- The first line contains two integers $M$ and $N$ indicating the number rows and columns in the metro system. This is followed by $M$ lines, lines $2, 3, …, M+1$, describing the trains along the $M$ rows. The first letter on each line is either F or O or S, indicating whether the train is a fast train, an ordinary train or a slow train. Following this, separated by a blank space, is an integer indicating the time at which this train starts running. The next $N$ lines, lines $M+2, M+3, …, N+M+1$, contain similar descriptions of the trains along the $N$ columns. The last line, line $N+M+2$, contains $5$ integers $a, b, c, d$ and $e$ where ($a$,$b$) is the starting station, $c$ is the starting time and ($d$,$e$) is the destination station. -----Output:----- A single integer indicating the earliest time at which one may reach the destination. -----Constraints:----- - $1 \leq M, N \leq 50$. - $1 \leq a, d \leq M$ - $1 \leq b, e \leq N$ - $1 \leq$ all times in input $\leq 20$ -----Sample Input----- 3 4 F 3 S 2 O 2 S 1 F 2 O 2 F 4 2 3 8 1 1 -----Sample Output----- 15
from queue import PriorityQueue m,n=list(map(int,input().split())) rr=[] cc=[] speed={'S':3,'O':2,'F':1} visited=set() dp=[] def qwerty(cur,x,y,f): if f==0: gg=rr[x][1]+y*rr[x][0] while gg<cur: gg+=(2*(n-1))*rr[x][0] return gg-cur+rr[x][0] elif f==1: gg=rr[x][1]+(2*(n-1)-y)*rr[x][0] while gg<cur: gg+=(2*(n-1))*rr[x][0] return gg-cur+rr[x][0] elif f==2: gg=cc[y][1]+x*cc[y][0] while gg<cur: gg+=(2*(m-1))*cc[y][0] return gg-cur+cc[y][0] elif f==3: gg=cc[y][1]+(2*(m-1)-x)*cc[y][0] while gg<cur: gg+=(2*(m-1))*cc[y][0] return gg-cur+cc[y][0] dirx=[0, 0, 1, -1] diry=[1, -1, 0, 0] for i in range(m): o=[x for x in input().split()] o[0]=speed[o[0]] o[1]=int(o[1]) rr.append(o) for i in range(n): o=[x for x in input().split()] o[0]=speed[o[0]] o[1]=int(o[1]) cc.append(o) sx,sy,stt,dx,dy=list(map(int,input().split())) sx-=1 sy-=1 dx-=1 dy-=1 for i in range(m): dp.append([10**9]*n) dp[sx][sy]=stt pq = PriorityQueue() pq.put((stt, sx, sy)) while not pq.empty(): #print(dp) (t,cxx,cyy)=pq.get() if (cxx,cyy) in visited: continue visited.add((cxx,cyy)) for i in range(len(dirx)): nxx=cxx+dirx[i] nyy=cyy+diry[i] if nxx>=0 and nxx<m and nyy>=0 and nyy<n and (nxx,nyy) not in visited: coo=qwerty(dp[cxx][cyy],cxx,cyy,i) if coo+dp[cxx][cyy]<dp[nxx][nyy]: dp[nxx][nyy]=coo+dp[cxx][cyy] pq.put((dp[nxx][nyy],nxx,nyy)) print(dp[dx][dy])
from queue import PriorityQueue m,n=list(map(int,input().split())) rr=[] cc=[] speed={'S':3,'O':2,'F':1} visited=set() dp=[] def qwerty(cur,x,y,f): if f==0: gg=rr[x][1]+y*rr[x][0] while gg<cur: gg+=(2*(n-1))*rr[x][0] return gg-cur+rr[x][0] elif f==1: gg=rr[x][1]+(2*(n-1)-y)*rr[x][0] while gg<cur: gg+=(2*(n-1))*rr[x][0] return gg-cur+rr[x][0] elif f==2: gg=cc[y][1]+x*cc[y][0] while gg<cur: gg+=(2*(m-1))*cc[y][0] return gg-cur+cc[y][0] elif f==3: gg=cc[y][1]+(2*(m-1)-x)*cc[y][0] while gg<cur: gg+=(2*(m-1))*cc[y][0] return gg-cur+cc[y][0] dirx=[0, 0, 1, -1] diry=[1, -1, 0, 0] for i in range(m): o=[x for x in input().split()] o[0]=speed[o[0]] o[1]=int(o[1]) rr.append(o) for i in range(n): o=[x for x in input().split()] o[0]=speed[o[0]] o[1]=int(o[1]) cc.append(o) sx,sy,stt,dx,dy=list(map(int,input().split())) sx-=1 sy-=1 dx-=1 dy-=1 for i in range(m): dp.append([10**9]*n) dp[sx][sy]=stt pq = PriorityQueue() pq.put((stt, sx, sy)) while not pq.empty(): #print(dp) (t,cxx,cyy)=pq.get() if (cxx,cyy) in visited: continue visited.add((cxx,cyy)) for i in range(len(dirx)): nxx=cxx+dirx[i] nyy=cyy+diry[i] if nxx>=0 and nxx<m and nyy>=0 and nyy<n and (nxx,nyy) not in visited: coo=qwerty(dp[cxx][cyy],cxx,cyy,i) if coo+dp[cxx][cyy]<dp[nxx][nyy]: dp[nxx][nyy]=coo+dp[cxx][cyy] pq.put((dp[nxx][nyy],nxx,nyy)) print(dp[dx][dy])
train
APPS_structured
< PREVIOUS KATA NEXT KATA > ## Task: You have to write a function `pattern` which returns the following Pattern(See Examples) upto desired number of rows. * Note:```Returning``` the pattern is not the same as ```Printing``` the pattern. ### Parameters: pattern( n , x , y ); ^ ^ ^ | | | Term upto which Number of times Number of times Basic Pattern Basic Pattern Basic Pattern should be should be should be created repeated repeated horizontally vertically * Note: `Basic Pattern` means what we created in Complete The Pattern #12 ## Rules/Note: * The pattern should be created using only unit digits. * If `n < 1` then it should return "" i.e. empty string. * If `x <= 1` then the basic pattern should not be repeated horizontally. * If `y <= 1` then the basic pattern should not be repeated vertically. * `The length of each line is same`, and is equal to the length of longest line in the pattern. * Range of Parameters (for the sake of CW Compiler) : + `n ∈ (-∞,25]` + `x ∈ (-∞,10]` + `y ∈ (-∞,10]` * If only two arguments are passed then the function `pattern` should run as if `y <= 1`. * If only one argument is passed then the function `pattern` should run as if `x <= 1` & `y <= 1`. * The function `pattern` should work when extra arguments are passed, by ignoring the extra arguments. ## Examples: * Having Three Arguments- + pattern(4,3,2): 1 1 1 1 2 2 2 2 2 2 3 3 3 3 3 3 4 4 4 3 3 3 3 3 3 2 2 2 2 2 2 1 1 1 1 2 2 2 2 2 2 3 3 3 3 3 3 4 4 4 3 3 3 3 3 3 2 2 2 2 2 2 1 1 1 1 * Having Two Arguments- + pattern(10,2): 1 1 1 2 2 2 2 3 3 3 3 4 4 4 4 5 5 5 5 6 6 6 6 7 7 7 7 8 8 8 8 9 9 9 9 0 0 9 9 9 9 8 8 8 8 7 7 7 7 6 6 6 6 5 5 5 5 4 4 4 4 3 3 3 3 2 2 2 2 1 1 1 * Having Only One Argument- + pattern(25): 1 1 2 2 3 3 4 4 5 5 6 6 7 7 8 8 9 9 0 0 1 1 2 2 3 3 4 4 5 5 6 6 7 7 8 8 9 9 0 0 1 1 2 2 3 3 4 4 5 4 4 3 3 2 2 1 1 0 0 9 9 8 8 7 7 6 6 5 5 4 4 3 3 2 2 1 1 0 0 9 9 8 8 7 7 6 6 5 5 4 4 3 3 2 2 1 1 >>>LIST OF ALL MY KATAS<<<
def getHorizontal(s,x): return s+s[1:]*(x-1) def pattern(n,x=1,y=1,*a): if n<1: return '' l, x, y = 2*n-1, max(1,x), max(1,y) sngl = [getHorizontal('{}{}{}'.format(z%10, ' '*(l-2*z), z%10 if z!=n else '').center(l), x) for z in range(1,n+1)] cross = sngl + sngl[:-1][::-1] return '\n'.join( cross + cross[1:]*(y-1) )
def getHorizontal(s,x): return s+s[1:]*(x-1) def pattern(n,x=1,y=1,*a): if n<1: return '' l, x, y = 2*n-1, max(1,x), max(1,y) sngl = [getHorizontal('{}{}{}'.format(z%10, ' '*(l-2*z), z%10 if z!=n else '').center(l), x) for z in range(1,n+1)] cross = sngl + sngl[:-1][::-1] return '\n'.join( cross + cross[1:]*(y-1) )
train
APPS_structured
Given an integer, write an algorithm to convert it to hexadecimal. For negative integer, two’s complement method is used. Note: All letters in hexadecimal (a-f) must be in lowercase. The hexadecimal string must not contain extra leading 0s. If the number is zero, it is represented by a single zero character '0'; otherwise, the first character in the hexadecimal string will not be the zero character. The given number is guaranteed to fit within the range of a 32-bit signed integer. You must not use any method provided by the library which converts/formats the number to hex directly. Example 1: Input: 26 Output: "1a" Example 2: Input: -1 Output: "ffffffff"
class Solution: def toHex(self, num): """ :type num: int :rtype: str """ if num == 0: return '0' hexKey = '0123456789abcdef' ans = '' for _ in range(8): ans = hexKey[num & 15] + ans num >>= 4 return ans.lstrip('0')
class Solution: def toHex(self, num): """ :type num: int :rtype: str """ if num == 0: return '0' hexKey = '0123456789abcdef' ans = '' for _ in range(8): ans = hexKey[num & 15] + ans num >>= 4 return ans.lstrip('0')
train
APPS_structured
On her way to ChefLand, Marichka noticed $10^K$ road signs (numbered $0$ through $10^K - 1$). For each valid $i$, the sign with number $i$ had the integer $i$ written on one side and $10^K-i-1$ written on the other side. Now, Marichka is wondering — how many road signs have exactly two distinct decimal digits written on them (on both sides in total)? Since this number may be large, compute it modulo $10^9+7$. For example, if $K = 3$, the two integers written on the road sign $363$ are $363$ and $636$, and they contain two distinct digits $3$ and $6$, but on the road sign $362$, there are integers $362$ and $637$, which contain four distinct digits — $2$, $3$, $6$ and $7$. On the road sign $11$, there are integers $11$ and $988$, which contain three distinct digits — $1$, $9$ and $8$. -----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 a single integer $K$. -----Output----- For each test case, print a single line containing one integer — the number of road signs with exactly two digits, modulo $10^9+7$. -----Constraints----- - $1 \le T \le 10^5$ - $1 \le K \le 10^9$ -----Subtasks----- Subtask #1 (20 points): $1 \le T, K \le 5$ Subtask #2 (80 points): original constraints -----Example Input----- 1 1 -----Example Output----- 10
t = int(input()) for i in range(t): k = int(input()) print(10*(2**(k-1)))
t = int(input()) for i in range(t): k = int(input()) print(10*(2**(k-1)))
train
APPS_structured
You've had a baby. Well done. Nice isn't it? Life destroying... but in a good way. Part of your new routine is lying awake at night worrying that you've either lost the baby... or that you have more than 1! Given a string of words (x), you need to calculate how many babies are in it. To count as a baby you must have all of the letters in baby ('b', 'a', 'b', 'y'). That counts as 1. They do not need to be in order in the string. Upper and lower case letters count. Examples: If there are no babies in the string - you lost the baby!! Return a different value, as shown below: ```if-not:kotlin 'none here' = "Where's the baby?!" '' = "Where's the baby?!" ``` ```if:kotlin "none here" = null "" = null ```
def baby_count(x): b = 0 a = 0 y = 0 for c in x.upper(): if c == "B": b += 1 elif c == "A": a += 1 elif c == "Y": y += 1 count = min(a, b//2, y) return count if count > 0 else 'Where\'s the baby?!'
def baby_count(x): b = 0 a = 0 y = 0 for c in x.upper(): if c == "B": b += 1 elif c == "A": a += 1 elif c == "Y": y += 1 count = min(a, b//2, y) return count if count > 0 else 'Where\'s the baby?!'
train
APPS_structured
Write a method named `getExponent(n,p)` that returns the largest integer exponent `x` such that p^(x) evenly divides `n`. if `p<=1` the method should return `null`/`None` (throw an `ArgumentOutOfRange` exception in C#).
def get_exponent(n, p): if p <=1 : return return max([i for i in range(1,int(abs(n)**.5)) if n% (p ** i)==0],default=0)
def get_exponent(n, p): if p <=1 : return return max([i for i in range(1,int(abs(n)**.5)) if n% (p ** i)==0],default=0)
train
APPS_structured
Given a square grid of integers arr, a falling path with non-zero shifts is a choice of exactly one element from each row of arr, such that no two elements chosen in adjacent rows are in the same column. Return the minimum sum of a falling path with non-zero shifts. Example 1: Input: arr = [[1,2,3],[4,5,6],[7,8,9]] Output: 13 Explanation: The possible falling paths are: [1,5,9], [1,5,7], [1,6,7], [1,6,8], [2,4,8], [2,4,9], [2,6,7], [2,6,8], [3,4,8], [3,4,9], [3,5,7], [3,5,9] The falling path with the smallest sum is [1,5,7], so the answer is 13. Constraints: 1 <= arr.length == arr[i].length <= 200 -99 <= arr[i][j] <= 99
class Solution: def minFallingPathSum(self, A: List[List[int]]) -> int: n = len(A) dp = [[0 for j in range(n)] for i in range(n)] for i in range(n): dp[-1][i] = A[-1][i] for i in range(n-2,-1,-1): for j in range(n): dp[i][j] = A[i][j] + min(dp[i+1][:j]+dp[i+1][j+1:]) return min(dp[0])
class Solution: def minFallingPathSum(self, A: List[List[int]]) -> int: n = len(A) dp = [[0 for j in range(n)] for i in range(n)] for i in range(n): dp[-1][i] = A[-1][i] for i in range(n-2,-1,-1): for j in range(n): dp[i][j] = A[i][j] + min(dp[i+1][:j]+dp[i+1][j+1:]) return min(dp[0])
train
APPS_structured
The Menger Sponge is a three-dimensional fractal, first described by Karl Menger in 1926. ![Mengers Sponge (Level 0-3)](http://i.imgur.com/V6Rb4Za.jpg) ###### _An illustration of the iterative construction of a Menger sponge_ A method of constructing a Menger Sponge can be visualized as follows: 1. Start from a cube (first part of image). 2. Scale down the cube so that side length is 1/3 of its original, and make 20 copies of it. 3. Place the copies so that they measure the same size as the original cube but without its central parts (next part of image) 4. Repeat the process from step 2 for the new smaller cubes from the previous step. 5. In each iteration (e.g. repeating the last three steps), the effect will be that parts of the cube will be removed, they'll never be added. Menger sponge will always consist of parts will never be removed, regardless of how many iterations you do. ___ An alternative explanation: 1. Start from a cube (first part of image). 2. Devide each cube into 27 equal sized cubes. 3. Remove the middle-cube and the six cubes on each side of the group of 27 cubes (second part of image). 4. Repeat the process from step 2 for the smaller cubes (third and fourth part of image). ## Task In this kata you will create a function that takes non negative integers (from 0 to n) and return the amount of cubes that the Menger Sponge would have in that specific iteration. ## Example ``` calc_ms(0) == 1 calc_ms(1) == 20 calc_ms(2) == 400 calc_ms(3) == 8000 calc_ms(4) == 160000 calc_ms(5) == 3200000 calc_ms(6) == 64000000 ``` Happy coding!
def calc_ms(n): return 20 ** n
def calc_ms(n): return 20 ** n
train
APPS_structured
Chef is again playing a game with his best friend Garry. As usual, the rules of this game are extremely strange and uncommon. First, they are given a stack of $N$ discs. Each disc has a distinct, non-negative integer written on it. The players exchange turns to make a move. Before the start of the game, they both agree upon a set of positive integers $S$ of size $K$. It is guaranteed that S contains the integer $1$. In a move, a player can select any value $x$ from $S$ and pop exactly $x$ elements from the top of the stack. The game ends when there are no discs remaining. Chef goes first. Scoring: For every disc a player pops, his score increases by $2^p$ where $p$ is the integer written on the disc. For example, if a player pops the discs, with integers $p_1, p_2, p_3, \dots, p_m$ written on it, during the entire course of the game, then his total score will be $2^{p_1} + 2^{p_2} + 2^{p_3} + \dots + 2^{p_m}$. The player with higher score wins the game. Determine the winner if both the players play optimally, or if the game ends in a draw. -----Input:----- - First line contains $T$, the number of testcases. Then the testcases follow. - The first line of each test case contains two space separated integers $N$ and $K$, denoting the size of the stack and the set S respectively. - Next line contains $N$ space separated integers $A_i$ where $A_1$ is the topmost element, denoting the initial arrangement of the stack. - The last line of each test case contains $K$ space separated integers each denoting $x_i$. -----Output:----- For each testcase, output "Chef" (without quotes) if Chef wins, "Garry" (without quotes) if Garry wins, otherwise "Draw" (without quotes) in a separate line. -----Constraints----- - $1 \leq T \leq 1000$ - $1 \leq N \leq 10^5$ - $1 \leq K \leq \min(100, N)$ - $0 \leq A_i \leq 10^9$ - $1 \leq x_i \leq N$ - $x_i \neq x_j$ for all $i \neq j$ - $A_i \neq A_j$ for all $i \neq j$ - Set $S$ contains integer $1$. - Sum of $N$ over all test cases does not exceed $10^5$. -----Sample Input:----- 1 3 2 5 7 1 1 2 -----Sample Output:----- Chef -----Explanation:----- Chef can select 2 from the set and draw the top two discs (with integers 5 and 7 written on it) from the stack. Garry cannot select 2 from the set as there is only 1 disc left in the stack. However, he can select 1 from the set and pop the last disc. So, Chef's score = $2^5$ + $2^7$ = $160$ Garry's score = $2^1$ = $2$ Chef wins.
for t in range(int(input())): n,k=list(map(int,input().split())) arr=list(map(int,input().split())) brr=list(map(int,input().split())) arr.append(-1) arr=arr[::-1] x=arr.index(max(arr)) # print(arr) dp=[0]*(n+1) for i in range(1,n+1,1): for l in brr: # print(i-l) if i-l<0: continue elif i-l<x and x<=i: dp[i]=1 else: dp[i]|=not dp[i-l] # print(dp) if dp[n]: print("Chef") else: print("Garry")
for t in range(int(input())): n,k=list(map(int,input().split())) arr=list(map(int,input().split())) brr=list(map(int,input().split())) arr.append(-1) arr=arr[::-1] x=arr.index(max(arr)) # print(arr) dp=[0]*(n+1) for i in range(1,n+1,1): for l in brr: # print(i-l) if i-l<0: continue elif i-l<x and x<=i: dp[i]=1 else: dp[i]|=not dp[i-l] # print(dp) if dp[n]: print("Chef") else: print("Garry")
train
APPS_structured
Mathison recently inherited an ancient papyrus that contained some text. Unfortunately, the text was not a pangram. Now, Mathison has a particular liking for holoalphabetic strings and the text bothers him. The good news is that Mathison can buy letters from the local store in order to turn his text into a pangram. However, each letter has a price and Mathison is not very rich. Can you help Mathison find the cheapest way to obtain a pangram? -----Input----- The first line of the input file will contain one integer, T, representing the number of tests. Each test will be formed from two lines. The first one contains 26 space-separated integers, representing the prices of all letters. The second will contain Mathison's initial text (a string of N lowercase letters). -----Output----- The output file will contain T lines, one for each test. Each line will contain the answer for the corresponding test. -----Constraints and notes----- - 1 ≤ T ≤ 10 - 1 ≤ N ≤ 50,000 - All prices are natural numbers between 1 and 1,000,000 (i.e. 106). - A pangram is a string that contains every letter of the Latin alphabet at least once. - All purchased letters are added to the end of the string. -----Subtaks----- Subtask #1 (30 points): - N = 1 Subtask #2 (70 points): - Original constraints -----Example----- Input: 2 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 abcdefghijklmopqrstuvwz 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 thequickbrownfoxjumpsoverthelazydog Output: 63 0 -----Explanation----- First test There are three letters missing from the original string: n (price 14), x (price 24), and y (price 25). Therefore the answer is 14 + 24 + 25 = 63. Second test No letter is missing so there is no point in buying something. The answer is 0.
# cook your dish here t=int(input()) for i in range(t): arr = list(map(int,input().split())) s=input() brr=list(map(chr,range(97,123))) count=0 for j in range(len(brr)): if brr[j] in s: continue else: count+=arr[j] print(count)
# cook your dish here t=int(input()) for i in range(t): arr = list(map(int,input().split())) s=input() brr=list(map(chr,range(97,123))) count=0 for j in range(len(brr)): if brr[j] in s: continue else: count+=arr[j] print(count)
train
APPS_structured
# Task John is a programmer. He treasures his time very much. He lives on the `n` floor of a building. Every morning he will go downstairs as quickly as possible to begin his great work today. There are two ways he goes downstairs: walking or taking the elevator. When John uses the elevator, he will go through the following steps: ``` 1. Waiting the elevator from m floor to n floor; 2. Waiting the elevator open the door and go in; 3. Waiting the elevator close the door; 4. Waiting the elevator down to 1 floor; 5. Waiting the elevator open the door and go out; (the time of go in/go out the elevator will be ignored) ``` Given the following arguments: ``` n: An integer. The floor of John(1-based). m: An integer. The floor of the elevator(1-based). speeds: An array of integer. It contains four integer [a,b,c,d] a: The seconds required when the elevator rises or falls 1 floor b: The seconds required when the elevator open the door c: The seconds required when the elevator close the door d: The seconds required when John walks to n-1 floor ``` Please help John to calculate the shortest time to go downstairs. # Example For `n = 5, m = 6 and speeds = [1,2,3,10]`, the output should be `12`. John go downstairs by using the elevator: `1 + 2 + 3 + 4 + 2 = 12` For `n = 1, m = 6 and speeds = [1,2,3,10]`, the output should be `0`. John is already at 1 floor, so the output is `0`. For `n = 5, m = 4 and speeds = [2,3,4,5]`, the output should be `20`. John go downstairs by walking: `5 x 4 = 20`
def shortest_time(n, m, speeds): a, b, c, d = speeds return min(d * (n - 1), (abs(m - n) + n - 1) * a + 2 * b + c)
def shortest_time(n, m, speeds): a, b, c, d = speeds return min(d * (n - 1), (abs(m - n) + n - 1) * a + 2 * b + c)
train
APPS_structured
Inspired by the development team at Vooza, write the function `howManyLightsabersDoYouOwn`/`how_many_light_sabers_do_you_own` that * accepts the name of a programmer, and * returns the number of lightsabers owned by that person. The only person who owns lightsabers is Zach, by the way. He owns 18, which is an awesome number of lightsabers. Anyone else owns 0. ```if:coffeescript,javascript,php,python,ruby,typescript **Note**: your function should have a default parameter. ``` ```c# Kata.HowManyLightsabersDoYouOwn("Adam") == 0 Kata.HowManyLightsabersDoYouOwn("Zach") == 18 ``` ```python how_many_light_sabers_do_you_own('Zach') == 18 how_many_light_sabers_do_you_own('Adam') == 0 how_many_light_sabers_do_you_own() == 0 ```
# Do your stuff here! def how_many_light_sabers_do_you_own(name=''): if name == "Zach": return 18 else: return 0
# Do your stuff here! def how_many_light_sabers_do_you_own(name=''): if name == "Zach": return 18 else: return 0
train
APPS_structured
You are given a tree rooted at node $1$ with $N$ vertices. The $i$$th$ vertex initially has value $A_i (1 \leq i \leq N)$. You are also given $Q$ queries. In each query you are given a vertex $V$. Let $S = \{ S_1 , S_2 , ... S_x \} $ denote the set of vertices such that $S_i$ is in the subtree of $V$, distance between $S_i$ and $V$ is even and $S_i \neq V$ for all $i$. For all $S_i$ , add $A$$S_i$ to $A_V$ and change the value of $A$$S_i$ to zero. Find the values of all the vertices after all queries are performed. Note-The distance between two vertices is defined as the number of edges traversed on the shortest path from one vertex to the other. -----Input:----- - The first line contains an integer $T$ denoting the number of test cases. - The first line of each test case contain two integers $N$ and $Q$. - The second line contains $N$ space separated integers, $A_1, A_2, ..., A_n$ denoting the initial values of the vertices. - The next $N-1$ lines contain two integers $u$ and $v$ denoting an edge between $u$and $v$. - The next $Q$ lines contain a single integer which is the query. -----Output:----- - Print a single line containing $N$ integers for each test case which is the final values of the vertices. -----Constraints:----- - $1\leq T \leq 10$ - $1 \leq N \leq 200000$ - $1 \leq Q \leq 200000$ - $0 \leq A_i \leq 10^9$ - The sum of $N$ over all test cases does not exceed $200000$. - The sum of $Q$ over all test cases does not exceed $200000$. -----Sample Input----- 1 4 3 6 2 7 3 1 2 2 3 3 4 3 2 1 -----Sample Output----- 13 5 0 0 -----Explanation----- Node $3$ has no child in its subtree which is at an even distance so there is no change in the values. Values of nodes after $1st$ query: $6, 2, 7, 3$. Node $4$ is at an even distance in the subtree of node $2$ so $A_4$ gets added to $A_2$ and $A_4$ becomes 0. Values of nodes after $2nd$ query: $6, 5, 7, 0$. Node $3$ is at an even distance in the subtree of node $1$ so $A_3$ gets added to $A_1$ and $A_3$ becomes 0. Values of nodes after $3rd$ query: $13, 5, 0, 0$.
from collections import defaultdict as dd,deque as dq def opbfs(u,vis,ll,parr): q=dq([(u,0)]) uu=u su=0 while q: u,lol=q.pop() par=parr[u] if(lol%2==0): vis[u]=1 su+=ll[u-1] ll[u-1]=0 for j in d[u]: if(j!=par): q.appendleft((j,lol+1)) ll[uu-1]=su def bfs(height,d,parr): q=dq([1]) while q: u=q.pop() height[u]=height[parr[u]]+1 for i in d[u]: if(i!=parr[u]): q.appendleft(i) parr[i]=u t=int(input()) while t: n,q=map(int,input().split()) ll=list(map(int,input().split())) d=dd(list) for i in range(n-1): u,v=map(int,input().split()) d[u].append(v) d[v].append(u) vis=[0]*(n+1) l=[] height=[0]*(n+1) parr=[0]*(n+1) bfs(height,d,parr) for i in range(q): u=int(input()) l.append((height[u],u,i)) l.sort() vis=[0]*(n+1) #print(l) for i in l: he,u,ind=i if(vis[u]==0): #print(u) opbfs(u,vis,ll,parr) print(*ll) t-=1
from collections import defaultdict as dd,deque as dq def opbfs(u,vis,ll,parr): q=dq([(u,0)]) uu=u su=0 while q: u,lol=q.pop() par=parr[u] if(lol%2==0): vis[u]=1 su+=ll[u-1] ll[u-1]=0 for j in d[u]: if(j!=par): q.appendleft((j,lol+1)) ll[uu-1]=su def bfs(height,d,parr): q=dq([1]) while q: u=q.pop() height[u]=height[parr[u]]+1 for i in d[u]: if(i!=parr[u]): q.appendleft(i) parr[i]=u t=int(input()) while t: n,q=map(int,input().split()) ll=list(map(int,input().split())) d=dd(list) for i in range(n-1): u,v=map(int,input().split()) d[u].append(v) d[v].append(u) vis=[0]*(n+1) l=[] height=[0]*(n+1) parr=[0]*(n+1) bfs(height,d,parr) for i in range(q): u=int(input()) l.append((height[u],u,i)) l.sort() vis=[0]*(n+1) #print(l) for i in l: he,u,ind=i if(vis[u]==0): #print(u) opbfs(u,vis,ll,parr) print(*ll) t-=1
train
APPS_structured
# Scenario **_Several people_** are standing in *a row divided into two teams*. The **_first person_** goes into **_team 1_**, **_the second_** goes into **_team 2_**, **_the third_** goes into **_team 1_**, and so on. ___ # Task **_Given_** *an array of positive integers (the weights of the people)*, **_return_** *a new array/tuple of two integers*, **_where_** **_the first_** one is the **_total weight of team 1_**, and **_the second_** one is the **_total weight of team 2_**. ___ # Notes * **_Array size_** is *at least 1*. * **_All numbers_** will be **positive**. ___ # Input >> Output Examples ``` rowWeights([13, 27, 49]) ==> return (62, 27) ``` ## **_Explanation_**: **_The first element_** `62` is *the total weight of team 1*, and **_the second element_** `27` is *the total weight of team 2*. ___ ``` rowWeights([50, 60, 70, 80]) ==> return (120, 140) ``` ## **_Explanation_**: **_The first element_** `120` is *the total weight of team 1*, and **_the second element_** `140` is *the total weight of team 2*. ___ ``` rowWeights([80]) ==> return (80, 0) ``` ## **_Explanation_**: **_The first element_** `80` is *the total weight of team 1*, and **_the second element_** `0` is *the total weight of team 2*. ___ ___ ___ # [Playing with Numbers Series](https://www.codewars.com/collections/playing-with-numbers) # [Playing With Lists/Arrays Series](https://www.codewars.com/collections/playing-with-lists-slash-arrays) # [For More Enjoyable Katas](http://www.codewars.com/users/MrZizoScream/authored) ___ ## ALL translations are welcomed ## Enjoy Learning !! # Zizou
def row_weights(array): return sum(x for i, x in enumerate(array) if not i % 2), sum(x for i, x in enumerate(array) if i % 2)
def row_weights(array): return sum(x for i, x in enumerate(array) if not i % 2), sum(x for i, x in enumerate(array) if i % 2)
train
APPS_structured
Given an array of integers with possible duplicates, randomly output the index of a given target number. You can assume that the given target number must exist in the array. Note: The array size can be very large. Solution that uses too much extra space will not pass the judge. Example: int[] nums = new int[] {1,2,3,3,3}; Solution solution = new Solution(nums); // pick(3) should return either index 2, 3, or 4 randomly. Each index should have equal probability of returning. solution.pick(3); // pick(1) should return 0. Since in the array only nums[0] is equal to 1. solution.pick(1);
class Solution: def __init__(self, nums): """ :type nums: List[int] """ self.nums = nums; def pick(self, target): """ :type target: int :rtype: int """ indices = [i for i, x in enumerate(self.nums) if x == target] return random.choice(indices) # Your Solution object will be instantiated and called as such: # obj = Solution(nums) # param_1 = obj.pick(target)
class Solution: def __init__(self, nums): """ :type nums: List[int] """ self.nums = nums; def pick(self, target): """ :type target: int :rtype: int """ indices = [i for i, x in enumerate(self.nums) if x == target] return random.choice(indices) # Your Solution object will be instantiated and called as such: # obj = Solution(nums) # param_1 = obj.pick(target)
train
APPS_structured
In genetics a reading frame is a way to divide a sequence of nucleotides (DNA bases) into a set of consecutive non-overlapping triplets (also called codon). Each of this triplets is translated into an amino-acid during a translation process to create proteins. In a single strand of DNA you find 3 Reading frames, for example the following sequence: ``` AGGTGACACCGCAAGCCTTATATTAGC ``` will be decompose in: ``` Frame 1: AGG·TGA·CAC·CGC·AAG·CCT·TAT·ATT·AGC Frame 2: A·GGT·GAC·ACC·GCA·AGC·CTT·ATA·TTA·GC Frame 3: AG·GTG·ACA·CCG·CAA·GCC·TTA·TAT·TAG·C ``` In a double strand DNA you find 3 more Reading frames base on the reverse complement-strand, given the previous DNA sequence, in the reverse complement ( A-->T, G-->C, T-->A, C-->G). Due to the splicing of DNA strands and the fixed reading direction of a nucleotide strand, the reverse complement gets read from right to left ``` AGGTGACACCGCAAGCCTTATATTAGC Reverse complement: TCCACTGTGGCGTTCGGAATATAATCG reversed reverse frame: GCTAATATAAGGCTTGCGGTGTCACCT ``` You have: ``` Reverse Frame 1: GCT AAT ATA AGG CTT GCG GTG TCA CCT reverse Frame 2: G CTA ATA TAA GGC TTG CGG TGT CAC CT reverse Frame 3: GC TAA TAT AAG GCT TGC GGT GTC ACC T ``` You can find more information about the Open Reading frame in wikipedia just [here] (https://en.wikipedia.org/wiki/Reading_frame) Given the [standard table of genetic code](http://www.ncbi.nlm.nih.gov/Taxonomy/Utils/wprintgc.cgi#SG1): ``` AAs = FFLLSSSSYY**CC*WLLLLPPPPHHQQRRRRIIIMTTTTNNKKSSRRVVVVAAAADDEEGGGG Base1 = TTTTTTTTTTTTTTTTCCCCCCCCCCCCCCCCAAAAAAAAAAAAAAAAGGGGGGGGGGGGGGGG Base2 = TTTTCCCCAAAAGGGGTTTTCCCCAAAAGGGGTTTTCCCCAAAAGGGGTTTTCCCCAAAAGGGG Base3 = TCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAG ``` The tri-nucleotide TTT = F, TTC = F, TTA = L... So our 6 frames will be translate as: ``` Frame 1: AGG·TGA·CAC·CGC·AAG·CCT·TAT·ATT·AGC R * H R K P Y I S Frame 2: A·GGT·GAC·ACC·GCA·AGC·CTT·ATA·TTA·GC G D T A S L I L Frame 3: AG·GTG·ACA·CCG·CAA·GCC·TTA·TAT·TAG·C V T P Q A L Y * Reverse Frame 1: GCT AAT ATA AGG CTT GCG GTG TCA CCT A N I R L A V S P Reverse Frame 2: G CTA ATA TAA GGC TTG CGG TGT CAC CT L I * G L R C H Reverse Frame 3: GC TAA TAT AAG GCT TGC GGT GTC ACC T * Y K A C G V T ``` In this kata you should create a function that translates DNA on all 6 frames, this function takes 2 arguments. The first one is the DNA sequence the second one is an array of frame number for example if we want to translate in Frame 1 and Reverse 1 this array will be [1,-1]. Valid frames are 1, 2, 3 and -1, -2, -3. The translation hash is available for you under a translation hash `$codons` [Ruby] or `codon` [other languages] (for example to access value of 'TTT' you should call $codons['TTT'] => 'F'). The function should return an array with all translation asked for, by default the function do the translation on all 6 frames.
import re def translate_with_frame(dna, frames=[1, 2, 3, -1, -2, -3]): AAs = 'FFLLSSSSYY**CC*WLLLLPPPPHHQQRRRRIIIMTTTTNNKKSSRRVVVVAAAADDEEGGGG' Base1 = 'TTTTTTTTTTTTTTTTCCCCCCCCCCCCCCCCAAAAAAAAAAAAAAAAGGGGGGGGGGGGGGGG' Base2 = 'TTTTCCCCAAAAGGGGTTTTCCCCAAAAGGGGTTTTCCCCAAAAGGGGTTTTCCCCAAAAGGGG' Base3 = 'TCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAG' trans = {'A': 'T', 'G': 'C', 'T': 'A', 'C': 'G'} intab = "AGTC" outtab = "TCAG" map = dict() for i, c in enumerate(AAs): code = Base1[i]+Base2[i]+Base3[i] map[code] = c res = [] for i in frames: trantab = dna.maketrans(intab, outtab) DNA = dna if i > 0 else dna[::-1].translate(trantab) res.append(''.join(map[x] for x in re.findall(r'.{3}', DNA[abs(i)-1:]))) return res
import re def translate_with_frame(dna, frames=[1, 2, 3, -1, -2, -3]): AAs = 'FFLLSSSSYY**CC*WLLLLPPPPHHQQRRRRIIIMTTTTNNKKSSRRVVVVAAAADDEEGGGG' Base1 = 'TTTTTTTTTTTTTTTTCCCCCCCCCCCCCCCCAAAAAAAAAAAAAAAAGGGGGGGGGGGGGGGG' Base2 = 'TTTTCCCCAAAAGGGGTTTTCCCCAAAAGGGGTTTTCCCCAAAAGGGGTTTTCCCCAAAAGGGG' Base3 = 'TCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAG' trans = {'A': 'T', 'G': 'C', 'T': 'A', 'C': 'G'} intab = "AGTC" outtab = "TCAG" map = dict() for i, c in enumerate(AAs): code = Base1[i]+Base2[i]+Base3[i] map[code] = c res = [] for i in frames: trantab = dna.maketrans(intab, outtab) DNA = dna if i > 0 else dna[::-1].translate(trantab) res.append(''.join(map[x] for x in re.findall(r'.{3}', DNA[abs(i)-1:]))) return res
train
APPS_structured
The Leetcode file system keeps a log each time some user performs a change folder operation. The operations are described below: "../" : Move to the parent folder of the current folder. (If you are already in the main folder, remain in the same folder). "./" : Remain in the same folder. "x/" : Move to the child folder named x (This folder is guaranteed to always exist). You are given a list of strings logs where logs[i] is the operation performed by the user at the ith step. The file system starts in the main folder, then the operations in logs are performed. Return the minimum number of operations needed to go back to the main folder after the change folder operations. Example 1: Input: logs = ["d1/","d2/","../","d21/","./"] Output: 2 Explanation: Use this change folder operation "../" 2 times and go back to the main folder. Example 2: Input: logs = ["d1/","d2/","./","d3/","../","d31/"] Output: 3 Example 3: Input: logs = ["d1/","../","../","../"] Output: 0 Constraints: 1 <= logs.length <= 103 2 <= logs[i].length <= 10 logs[i] contains lowercase English letters, digits, '.', and '/'. logs[i] follows the format described in the statement. Folder names consist of lowercase English letters and digits.
class Solution: def minOperations(self, logs: List[str]) -> int: c = 0 i = 0 while i<len(logs): if logs[i] == '../': if c != 0: c -= 1 elif logs[i] == './': pass else: c += 1 i += 1 return c
class Solution: def minOperations(self, logs: List[str]) -> int: c = 0 i = 0 while i<len(logs): if logs[i] == '../': if c != 0: c -= 1 elif logs[i] == './': pass else: c += 1 i += 1 return c
train
APPS_structured
According to ISO 8601, the first calendar week (1) starts with the week containing the first thursday in january. Every year contains of 52 (53 for leap years) calendar weeks. **Your task is** to calculate the calendar week (1-53) from a given date. For example, the calendar week for the date `2019-01-01` (string) should be 1 (int). Good luck 👍 See also [ISO week date](https://en.wikipedia.org/wiki/ISO_week_date) and [Week Number](https://en.wikipedia.org/wiki/Week#Week_numbering) on Wikipedia for further information about calendar weeks. On [whatweekisit.org](http://whatweekisit.org/) you may click through the calender and study calendar weeks in more depth. *heads-up:* `require(xxx)` has been disabled Thanks to @ZED.CWT, @Unnamed and @proxya for their feedback.
from datetime import date def get_calendar_week(s): return date(*map(int, s.split("-"))).isocalendar()[1]
from datetime import date def get_calendar_week(s): return date(*map(int, s.split("-"))).isocalendar()[1]
train
APPS_structured
Chef has an array A = (A1, A2, ..., AN), which has N integers in it initially. Chef found that for i ≥ 1, if Ai > 0, Ai+1 > 0, and Ai+2 exists, then he can decrease both Ai, and Ai+1 by one and increase Ai+2 by one. If Ai+2 doesn't exist, but Ai > 0, and Ai+1 > 0, then he can decrease both Ai, and Ai+1 (which will be the currently last two elements of the array) by one and add a new element at the end, whose value is 1. Now Chef wants to know the number of different arrays that he can make from A using this operation as many times as he wishes. Help him find this, and because the answer could be very large, he is fine with you reporting the answer modulo 109+7. Two arrays are same if they have the same number of elements and if each corresponding element is the same. For example arrays (2,1,1) and (1,1,2) are different. -----Input----- - The first line of the input contains a single integer T denoting the number of test cases. - The first line contains a single integer N denoting the initial number of elements in A. - The second line contains N space-separated integers: A1, A2, ... , AN. -----Output----- For each test case, output answer modulo 109+7 in a single line. -----Constraints----- - 1 ≤ T ≤ 5 - 1 ≤ N ≤ 50 - 0 ≤ Ai ≤ 50 -----Subtasks----- - Subtask 1 (20 points) : 1 ≤ N ≤ 8, 0 ≤ Ai ≤ 4 - Subtask 2 (80 points) : Original constraints -----Example----- Input: 3 3 2 3 1 2 2 2 3 1 2 3 Output: 9 4 9 -----Explanation----- Example case 1. We'll list the various single steps that you can take (ie. in one single usage of the operation): - (2, 3, 1) → (2, 2, 0, 1) - (2, 2, 0, 1) → (1, 1, 1, 1) - (1, 1, 1, 1) → (1, 1, 0, 0, 1) - (1, 1, 0, 0, 1) → (0, 0, 1, 0, 1) - (1, 1, 1, 1) → (1, 0, 0, 2) - (1, 1, 1, 1) → (0, 0, 2, 1) - (2, 3, 1) → (1, 2, 2) - (1, 2, 2) → (0, 1, 3) So all the arrays you can possibly get are: (2, 3, 1), (2, 2, 0, 1), (1, 1, 1, 1), (1, 1, 0, 0, 1), (0, 0, 1, 0, 1), (1, 0, 0, 2), (0, 0, 2, 1), (1, 2, 2), and (0, 1, 3) Since there are 9 different arrays that you can reach, the answer is 9.
import pdb def gen_sig(arr): sig = ';'.join(map(str,arr)) return sig def solve(arr,cache): l = len(arr) cnt =0 for i in range(l-1): if arr[i] >0 and arr[i+1]>0: if i == l-2: arr[i]-=1 arr[i+1]-=1 arr.append(1) sig = gen_sig(arr) if (sig in cache) == False: cache[sig]=1 ret = solve(arr,cache) if ret >=0: cnt+=ret+1 arr.pop(-1) arr[i+1]+=1 arr[i]+=1 else: arr[i]-=1 arr[i+1]-=1 arr[i+2]+=1 sig = gen_sig(arr) if (sig in cache) == False: cache[sig]=1 ret = solve(arr,cache) if ret >=0: cnt+=ret+1 arr[i]+=1 arr[i+1]+=1 arr[i+2]-=1 #cache[gen_sig(arr)] = cnt return cnt def __starting_point(): T = int(input()) for t in range(T): n = int(input()) arr = list(map(int, input().split())) cache = {} cache[gen_sig(arr)]=1 solve(arr,cache) print(len(cache)) __starting_point()
import pdb def gen_sig(arr): sig = ';'.join(map(str,arr)) return sig def solve(arr,cache): l = len(arr) cnt =0 for i in range(l-1): if arr[i] >0 and arr[i+1]>0: if i == l-2: arr[i]-=1 arr[i+1]-=1 arr.append(1) sig = gen_sig(arr) if (sig in cache) == False: cache[sig]=1 ret = solve(arr,cache) if ret >=0: cnt+=ret+1 arr.pop(-1) arr[i+1]+=1 arr[i]+=1 else: arr[i]-=1 arr[i+1]-=1 arr[i+2]+=1 sig = gen_sig(arr) if (sig in cache) == False: cache[sig]=1 ret = solve(arr,cache) if ret >=0: cnt+=ret+1 arr[i]+=1 arr[i+1]+=1 arr[i+2]-=1 #cache[gen_sig(arr)] = cnt return cnt def __starting_point(): T = int(input()) for t in range(T): n = int(input()) arr = list(map(int, input().split())) cache = {} cache[gen_sig(arr)]=1 solve(arr,cache) print(len(cache)) __starting_point()
train
APPS_structured
```if:csharp ## Terminal Game - Create Hero Class In this first kata in the series, you need to define a Hero class to be used in a terminal game. The hero should have the following attributes: attribute | type | value ---|---|--- Name | string | user argument or "Hero" Position | string | "00" Health | float | 100 Damage | float | 5 Experience | int | 0 ``` ```if-not:csharp ## Terminal Game - Create Hero Prototype In this first kata in the series, you need to define a Hero prototype to be used in a terminal game. The hero should have the following attributes: attribute | value ---|--- name | user argument or 'Hero' position | '00' health | 100 damage | 5 experience | 0 ```
class Hero(object): def __init__(self, *name): self.name = "Hero" for a in name: self.name = name[0] self.experience = 0 self.position = "00" self.health = 100 self.damage = 5
class Hero(object): def __init__(self, *name): self.name = "Hero" for a in name: self.name = name[0] self.experience = 0 self.position = "00" self.health = 100 self.damage = 5
train
APPS_structured
Ashish and Vivek play a game on a matrix consisting of $n$ rows and $m$ columns, where they take turns claiming cells. Unclaimed cells are represented by $0$, while claimed cells are represented by $1$. The initial state of the matrix is given. There can be some claimed cells in the initial state. In each turn, a player must claim a cell. A cell may be claimed if it is unclaimed and does not share a row or column with any other already claimed cells. When a player is unable to make a move, he loses and the game ends. If Ashish and Vivek take turns to move and Ashish goes first, determine the winner of the game if both of them are playing optimally. Optimal play between two players means that both players choose the best possible strategy to achieve the best possible outcome for themselves. -----Input----- The first line consists of a single integer $t$ $(1 \le t \le 50)$ — the number of test cases. The description of the test cases follows. The first line of each test case consists of two space-separated integers $n$, $m$ $(1 \le n, m \le 50)$ — the number of rows and columns in the matrix. The following $n$ lines consist of $m$ integers each, the $j$-th integer on the $i$-th line denoting $a_{i,j}$ $(a_{i,j} \in \{0, 1\})$. -----Output----- For each test case if Ashish wins the game print "Ashish" otherwise print "Vivek" (without quotes). -----Example----- Input 4 2 2 0 0 0 0 2 2 0 0 0 1 2 3 1 0 1 1 1 0 3 3 1 0 0 0 0 0 1 0 0 Output Vivek Ashish Vivek Ashish -----Note----- For the first case: One possible scenario could be: Ashish claims cell $(1, 1)$, Vivek then claims cell $(2, 2)$. Ashish can neither claim cell $(1, 2)$, nor cell $(2, 1)$ as cells $(1, 1)$ and $(2, 2)$ are already claimed. Thus Ashish loses. It can be shown that no matter what Ashish plays in this case, Vivek will win. For the second case: Ashish claims cell $(1, 1)$, the only cell that can be claimed in the first move. After that Vivek has no moves left. For the third case: Ashish cannot make a move, so Vivek wins. For the fourth case: If Ashish claims cell $(2, 3)$, Vivek will have no moves left.
from bisect import bisect_left as bl from bisect import bisect_right as br from heapq import heappush,heappop import math from collections import * from functools import reduce,cmp_to_key import sys input = sys.stdin.readline M = mod = 998244353 def factors(n):return sorted(set(reduce(list.__add__, ([i, n//i] for i in range(1, int(n**0.5) + 1) if n % i == 0)))) def inv_mod(n):return pow(n, mod - 2, mod) def li():return [int(i) for i in input().rstrip('\n').split()] def st():return input().rstrip('\n') def val():return int(input().rstrip('\n')) def li2():return [i for i in input().rstrip('\n')] def li3():return [int(i) for i in input().rstrip('\n')] for _ in range(val()): n,m = li() l = [] for i in range(n):l.append(li()) rows = n cols = m for i in range(n): if sum(l[i]):rows -= 1 for j in range(m): for i in range(n): if l[i][j]: cols -= 1 break n = rows m = cols print('Ashish' if min(n,m)&1 else 'Vivek')
from bisect import bisect_left as bl from bisect import bisect_right as br from heapq import heappush,heappop import math from collections import * from functools import reduce,cmp_to_key import sys input = sys.stdin.readline M = mod = 998244353 def factors(n):return sorted(set(reduce(list.__add__, ([i, n//i] for i in range(1, int(n**0.5) + 1) if n % i == 0)))) def inv_mod(n):return pow(n, mod - 2, mod) def li():return [int(i) for i in input().rstrip('\n').split()] def st():return input().rstrip('\n') def val():return int(input().rstrip('\n')) def li2():return [i for i in input().rstrip('\n')] def li3():return [int(i) for i in input().rstrip('\n')] for _ in range(val()): n,m = li() l = [] for i in range(n):l.append(li()) rows = n cols = m for i in range(n): if sum(l[i]):rows -= 1 for j in range(m): for i in range(n): if l[i][j]: cols -= 1 break n = rows m = cols print('Ashish' if min(n,m)&1 else 'Vivek')
train
APPS_structured
Kate and Michael want to buy a pizza and share it. Depending on the price of the pizza, they are going to divide the costs: * If the pizza is less than €5,- Michael invites Kate, so Michael pays the full price. * Otherwise Kate will contribute 1/3 of the price, but no more than €10 (she's broke :-) and Michael pays the rest. How much is Michael going to pay? Calculate the amount with two decimals, if necessary.
def michael_pays(costs): return round(costs, 2) if costs < 5 else round(max(costs-10, costs/3*2), 2)
def michael_pays(costs): return round(costs, 2) if costs < 5 else round(max(costs-10, costs/3*2), 2)
train
APPS_structured
# Do you ever wish you could talk like Siegfried of KAOS ? ## YES, of course you do! https://en.wikipedia.org/wiki/Get_Smart # Task Write the function ```siegfried``` to replace the letters of a given sentence. Apply the rules using the course notes below. Each week you will learn some more rules. Und by ze fifz vek yu vil be speakink viz un aksent lik Siegfried viz no trubl at al! # Lessons ## Week 1 * ```ci``` -> ```si``` * ```ce``` -> ```se``` * ```c``` -> ```k``` (except ```ch``` leave alone) ## Week 2 * ```ph``` -> ```f``` ## Week 3 * remove trailing ```e``` (except for all 2 and 3 letter words) * replace double letters with single letters (e.g. ```tt``` -> ```t```) ## Week 4 * ```th``` -> ```z``` * ```wr``` -> ```r``` * ```wh``` -> ```v``` * ```w``` -> ```v``` ## Week 5 * ```ou``` -> ```u``` * ```an``` -> ```un``` * ```ing``` -> ```ink``` (but only when ending words) * ```sm``` -> ```schm``` (but only when beginning words) # Notes * You must retain the case of the original sentence * Apply rules strictly in the order given above * Rules are cummulative. So for week 3 first apply week 1 rules, then week 2 rules, then week 3 rules
import re def siegfried(week, txt): weeks_have_passed = {0: week_one, 1: week_two, 2: week_three, 3: week_four, 4: week_five} for counter in range(0, week): txt = weeks_have_passed[counter](txt) return txt def week_one(txt): letter_list = list(txt) copy_reverse_letter_list = letter_list.copy() last_letter = '' count = -1 for letter in copy_reverse_letter_list[::-1]: lowercase_letter = letter.lower() if lowercase_letter == 'c': lowercase_letter += last_letter if letter.isupper(): dict_to_know = {'ci': 'S', 'ce': 'S', 'ch': 'C'} to_return = 'K' else: dict_to_know = {'ci': 's', 'ce': 's', 'ch': 'c'} to_return = 'k' letter_list[count] = dict_to_know.get(lowercase_letter, to_return) count -= 1 last_letter = letter final_txt = ''.join(letter_list) return final_txt def week_two(txt): letter_list = list(txt) copy_letter_list = letter_list.copy() copy_letter_list.append('') fix_position = 0 for counter, letter in enumerate(copy_letter_list[:-1]): lowercase_letter = letter.lower() next_letter = copy_letter_list[counter+1] lowcase_next_letter = next_letter.lower() if lowercase_letter == 'p' and lowcase_next_letter == 'h': counter -= fix_position if letter.isupper(): to_change = 'F' else: to_change = 'f' letter_list[counter: counter + 2] = to_change fix_position += 1 new_txt = ''.join(letter_list) return new_txt def week_three(txt): trailling_e = r'[a-zA-Z]{3,}e\b' trailling_list = re.findall(trailling_e, txt) new_txt = txt for trailling_e_word in trailling_list: new_txt = new_txt.replace(trailling_e_word, trailling_e_word[:-1]) letter_list = list(new_txt) copy_letter_list = letter_list.copy() last_letter = '' position = -1 for letter in copy_letter_list[::-1]: lowercase_letter = letter.lower() if lowercase_letter == last_letter and lowercase_letter.isalpha(): del letter_list[position+1] position += 1 last_letter = lowercase_letter position -= 1 final_txt = ''.join(letter_list) return final_txt def week_four(txt): letter_list = list(txt) copy_reverse_letter_list = letter_list.copy() last_letter = '' counter = -1 for letter in copy_reverse_letter_list[::-1]: lowercase_letter = letter.lower() if lowercase_letter == 'w' or lowercase_letter == 't' and last_letter == 'h': lowercase_letter += last_letter if letter.isupper(): dict_to_know = {'wr': 'R', 'wh': 'V', 'th': 'Z'} lonely_w = 'V' else: dict_to_know = {'wr': 'r', 'wh': 'v', 'th': 'z'} lonely_w = 'v' possible_last_letters = {'h', 'r'} if last_letter in possible_last_letters: letter_list[counter: counter+2] = dict_to_know[lowercase_letter] counter += 1 else: letter_list[counter] = lonely_w counter -= 1 last_letter = letter final_txt = ''.join(letter_list) return final_txt def week_five(txt): letter_list = list(txt) copy_reverse_letter_list = letter_list.copy() last_letter = '' counter = -1 for letter in copy_reverse_letter_list[::-1]: lowercase_letter = letter.lower() if lowercase_letter == 'o' and last_letter == 'u': lowercase_or_uppercase = {'o': 'u', 'O': 'U'} letter_list[counter: counter+2] = lowercase_or_uppercase[letter] counter += 1 elif lowercase_letter == 'a' and last_letter == 'n': lowercase_or_uppercase_2 = {'a': 'u', 'A': 'U'} letter_list[counter] = lowercase_or_uppercase_2[letter] last_letter = lowercase_letter counter -= 1 first_txt = ''.join(letter_list) re_to_find_ing = r'[a-zA-Z]{1,}ing\b' all_words_ending_with_ing = re.findall(re_to_find_ing, first_txt) second_txt = first_txt for word in all_words_ending_with_ing: new_word = word[:-1] + 'k' second_txt = second_txt.replace(word, new_word) re_to_find_sm = r'\b[sS][mM][a-zA-Z]*' all_words_starting_with_sm = re.findall(re_to_find_sm, second_txt) third_txt = second_txt for word in all_words_starting_with_sm: new_word = word[0] + 'ch' + word[1:] third_txt = third_txt.replace(word, new_word) final_txt = third_txt return final_txt
import re def siegfried(week, txt): weeks_have_passed = {0: week_one, 1: week_two, 2: week_three, 3: week_four, 4: week_five} for counter in range(0, week): txt = weeks_have_passed[counter](txt) return txt def week_one(txt): letter_list = list(txt) copy_reverse_letter_list = letter_list.copy() last_letter = '' count = -1 for letter in copy_reverse_letter_list[::-1]: lowercase_letter = letter.lower() if lowercase_letter == 'c': lowercase_letter += last_letter if letter.isupper(): dict_to_know = {'ci': 'S', 'ce': 'S', 'ch': 'C'} to_return = 'K' else: dict_to_know = {'ci': 's', 'ce': 's', 'ch': 'c'} to_return = 'k' letter_list[count] = dict_to_know.get(lowercase_letter, to_return) count -= 1 last_letter = letter final_txt = ''.join(letter_list) return final_txt def week_two(txt): letter_list = list(txt) copy_letter_list = letter_list.copy() copy_letter_list.append('') fix_position = 0 for counter, letter in enumerate(copy_letter_list[:-1]): lowercase_letter = letter.lower() next_letter = copy_letter_list[counter+1] lowcase_next_letter = next_letter.lower() if lowercase_letter == 'p' and lowcase_next_letter == 'h': counter -= fix_position if letter.isupper(): to_change = 'F' else: to_change = 'f' letter_list[counter: counter + 2] = to_change fix_position += 1 new_txt = ''.join(letter_list) return new_txt def week_three(txt): trailling_e = r'[a-zA-Z]{3,}e\b' trailling_list = re.findall(trailling_e, txt) new_txt = txt for trailling_e_word in trailling_list: new_txt = new_txt.replace(trailling_e_word, trailling_e_word[:-1]) letter_list = list(new_txt) copy_letter_list = letter_list.copy() last_letter = '' position = -1 for letter in copy_letter_list[::-1]: lowercase_letter = letter.lower() if lowercase_letter == last_letter and lowercase_letter.isalpha(): del letter_list[position+1] position += 1 last_letter = lowercase_letter position -= 1 final_txt = ''.join(letter_list) return final_txt def week_four(txt): letter_list = list(txt) copy_reverse_letter_list = letter_list.copy() last_letter = '' counter = -1 for letter in copy_reverse_letter_list[::-1]: lowercase_letter = letter.lower() if lowercase_letter == 'w' or lowercase_letter == 't' and last_letter == 'h': lowercase_letter += last_letter if letter.isupper(): dict_to_know = {'wr': 'R', 'wh': 'V', 'th': 'Z'} lonely_w = 'V' else: dict_to_know = {'wr': 'r', 'wh': 'v', 'th': 'z'} lonely_w = 'v' possible_last_letters = {'h', 'r'} if last_letter in possible_last_letters: letter_list[counter: counter+2] = dict_to_know[lowercase_letter] counter += 1 else: letter_list[counter] = lonely_w counter -= 1 last_letter = letter final_txt = ''.join(letter_list) return final_txt def week_five(txt): letter_list = list(txt) copy_reverse_letter_list = letter_list.copy() last_letter = '' counter = -1 for letter in copy_reverse_letter_list[::-1]: lowercase_letter = letter.lower() if lowercase_letter == 'o' and last_letter == 'u': lowercase_or_uppercase = {'o': 'u', 'O': 'U'} letter_list[counter: counter+2] = lowercase_or_uppercase[letter] counter += 1 elif lowercase_letter == 'a' and last_letter == 'n': lowercase_or_uppercase_2 = {'a': 'u', 'A': 'U'} letter_list[counter] = lowercase_or_uppercase_2[letter] last_letter = lowercase_letter counter -= 1 first_txt = ''.join(letter_list) re_to_find_ing = r'[a-zA-Z]{1,}ing\b' all_words_ending_with_ing = re.findall(re_to_find_ing, first_txt) second_txt = first_txt for word in all_words_ending_with_ing: new_word = word[:-1] + 'k' second_txt = second_txt.replace(word, new_word) re_to_find_sm = r'\b[sS][mM][a-zA-Z]*' all_words_starting_with_sm = re.findall(re_to_find_sm, second_txt) third_txt = second_txt for word in all_words_starting_with_sm: new_word = word[0] + 'ch' + word[1:] third_txt = third_txt.replace(word, new_word) final_txt = third_txt return final_txt
train
APPS_structured
Given a square matrix mat, return the sum of the matrix diagonals. Only include the sum of all the elements on the primary diagonal and all the elements on the secondary diagonal that are not part of the primary diagonal. Example 1: Input: mat = [[1,2,3],   [4,5,6],   [7,8,9]] Output: 25 Explanation: Diagonals sum: 1 + 5 + 9 + 3 + 7 = 25 Notice that element mat[1][1] = 5 is counted only once. Example 2: Input: mat = [[1,1,1,1],   [1,1,1,1],   [1,1,1,1],   [1,1,1,1]] Output: 8 Example 3: Input: mat = [[5]] Output: 5 Constraints: n == mat.length == mat[i].length 1 <= n <= 100 1 <= mat[i][j] <= 100
class Solution: def diagonalSum(self, mat: List[List[int]]) -> int: leng = len(mat[0]) ans = 0 check = [[0 for _ in range(len(mat[0]))] for _ in range(len(mat))] for i in range(leng): ans+=mat[i][i] check[i][i] = 1 for i in range(leng): if check[i][leng-1] != 1: ans+=mat[i][leng-1] leng-=1 return ans
class Solution: def diagonalSum(self, mat: List[List[int]]) -> int: leng = len(mat[0]) ans = 0 check = [[0 for _ in range(len(mat[0]))] for _ in range(len(mat))] for i in range(leng): ans+=mat[i][i] check[i][i] = 1 for i in range(leng): if check[i][leng-1] != 1: ans+=mat[i][leng-1] leng-=1 return ans
train
APPS_structured
Given two numbers, hour and minutes. Return the smaller angle (in degrees) formed between the hour and the minute hand. Example 1: Input: hour = 12, minutes = 30 Output: 165 Example 2: Input: hour = 3, minutes = 30 Output: 75 Example 3: Input: hour = 3, minutes = 15 Output: 7.5 Example 4: Input: hour = 4, minutes = 50 Output: 155 Example 5: Input: hour = 12, minutes = 0 Output: 0 Constraints: 1 <= hour <= 12 0 <= minutes <= 59 Answers within 10^-5 of the actual value will be accepted as correct.
class Solution: def angleClock(self, hour: int, minutes: int) -> float: hour = hour if hour < 12 else hour - 12 minute_angle = float(minutes) / 60.0 * 360.0 hour_angle = 30.0 * hour + minutes / 60 * 360.0 / 12.0 return abs(minute_angle - hour_angle) if abs(minute_angle - hour_angle) < 180.0 else 360.0 - abs(minute_angle - hour_angle)
class Solution: def angleClock(self, hour: int, minutes: int) -> float: hour = hour if hour < 12 else hour - 12 minute_angle = float(minutes) / 60.0 * 360.0 hour_angle = 30.0 * hour + minutes / 60 * 360.0 / 12.0 return abs(minute_angle - hour_angle) if abs(minute_angle - hour_angle) < 180.0 else 360.0 - abs(minute_angle - hour_angle)
train
APPS_structured
Write a function that takes a string and returns an array containing binary numbers equivalent to the ASCII codes of the characters of the string. The binary strings should be eight digits long. Example: `'man'` should return `[ '01101101', '01100001', '01101110' ]`
def word_to_bin(s): return ["{0:08b}".format(ord(c)) for c in s]
def word_to_bin(s): return ["{0:08b}".format(ord(c)) for c in s]
train
APPS_structured
Vasya and Kolya play a game with a string, using the following rules. Initially, Kolya creates a string s, consisting of small English letters, and uniformly at random chooses an integer k from a segment [0, len(s) - 1]. He tells Vasya this string s, and then shifts it k letters to the left, i. e. creates a new string t = s_{k} + 1s_{k} + 2... s_{n}s_1s_2... s_{k}. Vasya does not know the integer k nor the string t, but he wants to guess the integer k. To do this, he asks Kolya to tell him the first letter of the new string, and then, after he sees it, open one more letter on some position, which Vasya can choose. Vasya understands, that he can't guarantee that he will win, but he wants to know the probability of winning, if he plays optimally. He wants you to compute this probability. Note that Vasya wants to know the value of k uniquely, it means, that if there are at least two cyclic shifts of s that fit the information Vasya knowns, Vasya loses. Of course, at any moment of the game Vasya wants to maximize the probability of his win. -----Input----- The only string contains the string s of length l (3 ≤ l ≤ 5000), consisting of small English letters only. -----Output----- Print the only number — the answer for the problem. You answer is considered correct, if its absolute or relative error does not exceed 10^{ - 6}. Formally, let your answer be a, and the jury's answer be b. Your answer is considered correct if $\frac{|a - b|}{\operatorname{max}(1,|b|)} \leq 10^{-6}$ -----Examples----- Input technocup Output 1.000000000000000 Input tictictactac Output 0.333333333333333 Input bbaabaabbb Output 0.100000000000000 -----Note----- In the first example Vasya can always open the second letter after opening the first letter, and the cyclic shift is always determined uniquely. In the second example if the first opened letter of t is "t" or "c", then Vasya can't guess the shift by opening only one other letter. On the other hand, if the first letter is "i" or "a", then he can open the fourth letter and determine the shift uniquely.
s = input() n = len(s) sett = {} for i in range(n): if s[i] not in sett: sett[s[i]] = [] sett[s[i]].append(s[i + 1:] + s[:i]) ans = 0 # ao fazer sett.items(), é realizado unpack da chave,valor para k,l, respectivamente for k, l in list(sett.items()): tmp = 0 for j in range(n - 1): seen, sett1 = set(), set() for i in range(len(l)): if l[i][j] in sett1: sett1.remove(l[i][j]) elif l[i][j] not in seen: sett1.add(l[i][j]) seen.add(l[i][j]) tmp = max(tmp, len(sett1)) tmp /= n ans += tmp # precisao 10^6 print('{:.7}'.format(ans))
s = input() n = len(s) sett = {} for i in range(n): if s[i] not in sett: sett[s[i]] = [] sett[s[i]].append(s[i + 1:] + s[:i]) ans = 0 # ao fazer sett.items(), é realizado unpack da chave,valor para k,l, respectivamente for k, l in list(sett.items()): tmp = 0 for j in range(n - 1): seen, sett1 = set(), set() for i in range(len(l)): if l[i][j] in sett1: sett1.remove(l[i][j]) elif l[i][j] not in seen: sett1.add(l[i][j]) seen.add(l[i][j]) tmp = max(tmp, len(sett1)) tmp /= n ans += tmp # precisao 10^6 print('{:.7}'.format(ans))
train
APPS_structured
Salmon is playing a game! He is given two integers $N$ and $K$. His goal is to output $K$ pairs $(x_i,y_i)$. He creates a function $f$ such that $f(x_i) = y_i$ and $f$ is undefined for all other values of $x$. His pairs must then meet the following conditions: - All $x_i$ are distinct. - All $y_i$ are distinct. - All $x_i, y_i$ are in the range $[0,2^N - 1]$ and are integers. - $f(f(x_i))$ is defined for all $i$. - Let $H(x)$ be the number of set bits in the binary representation of $x$. Then, $H(x_i) \neq H(f(f(x_i)))$ for all $i$. Unfortunately, Salmon is unable to solve this. Help Salmon win the game! If there are multiple correct solutions, you may output any one of them. It can be proven that a solution exists for all $N$ and $K$ that meet constraints. -----Input----- - The first line input contains a single integer $T$ denoting the number of testcases - Each of the next $T$ lines contains two space-separated integers $N$ and $K$ respectively. -----Output----- - Output $K$ lines for each testcase. - The $i$-th line of a testcase should contain two space-separated integers: $x_i$ and $y_i$, following the given constraints. -----Constraints----- - $1 \leq T \leq 2^{15}$ - $3 \leq N \leq 18$ - $3 \leq K \leq 2^N$ - The sum of $2^N$ over all testcases doesn't exceed $2^{18}$ -----Subtasks----- - Subtask 1 [20 points]: $K \leq 8$ - Subtask 2 [40 points]: $K = 2^N$ - Subtask 3 [40 points]: No additional constraints. -----Sample Input----- 2 3 7 4 6 -----Sample Output----- 5 3 1 7 0 4 2 5 3 1 4 2 7 0 1 10 10 14 15 1 14 13 5 15 13 5 -----Explanation----- In the answer to the first testcase, there are 7 pairs. $x_i$ and $y_i$ are all in the range $[0,2^3 - 1]$, which is the range $[0,7]$. All values of $x_i$ are distinct, and all values of $y_i$ are distinct. However, note that some integers appear in both lists. For example, 5 appears both as $x_1$ and as $y_4$. This is allowed. For all $x_i$, $f(f(x_i))$ is defined and $H(f(f(x_i))) \neq H(x_i)$. For example, $f(f(7)) = 4$. $H(7) = 3$, but $H(4) = 1$. Therefore, $H(f(f(7))) \neq H(7)$, as desired.
# import all important libraries and inbuilt functions from fractions import Fraction import numpy as np import sys,bisect,copyreg,statistics,os,time,socket,socketserver,atexit,io from math import gcd,ceil,floor,sqrt,copysign,factorial,fmod,fsum,degrees from math import expm1,exp,log,log2,acos,asin,cos,tan,sin,pi,e,tau,inf,nan,atan2 from collections import Counter,defaultdict,deque,OrderedDict from itertools import combinations,permutations,accumulate,groupby,compress from numpy.linalg import matrix_power as mp from bisect import bisect_left,bisect_right,bisect,insort,insort_left,insort_right from statistics import * from copy import copy,deepcopy from functools import reduce,cmp_to_key,lru_cache from io import BytesIO, IOBase from scipy.spatial import ConvexHull from heapq import * from decimal import * from queue import Queue,PriorityQueue from re import sub,subn from random import shuffle,randrange,randint,random from types import GeneratorType from string import ascii_lowercase from time import perf_counter from datetime import datetime from operator import ior,mul # never import pow from math library it does not perform modulo # use standard pow -- better than math.pow # end of library import # map system version faults if sys.version_info[0] < 3: from builtins import xrange as range from future_builtins import ascii, filter, hex, map, oct, zip # template of many functions used in competitive programming can add more later # based on need we will use this commonly. # definition of vertex of a graph def graph(vertex): return [[] for i in range(vertex+1)] def lcm(a,b): return (a*b)//gcd(a,b) # most common list in a array of lists def most_frequent(List): return Counter(List).most_common(1)[0][0] # element with highest frequency def most_common(List): return(mode(List)) #In number theory, the Chinese remainder theorem states that #if one knows the remainders of the Euclidean division of an integer n by #several integers, then one can determine uniquely the remainder of the #division of n by the product of these integers, under the condition #that the divisors are pairwise coprime. def chinese_remainder(a, p): prod = reduce(op.mul, p, 1) x = [prod // piii for piii in p] return sum(a[i] * pow(x[i], p[i] - 2, p[i]) * x[i] for i in range(len(a))) % prod def bootstrap(f, stack=[]): def wrappedfunc(*args, **kwargs): if stack: return f(*args, **kwargs) else: to = f(*args, **kwargs) while True: if type(to) is GeneratorType: stack.append(to);to = next(to) else: stack.pop() if not stack: break to = stack[-1].send(to) return to return wrappedfunc # input for a binary tree def readTree(): v = II() adj=[set() for i in range(v+1)] for i in range(v-1): u1,u2 = MI() adj[u1].add(u2) adj[u2].add(u1) return adj,v #count setbits of a number. def setBit(n): return bin(n).count('1'); # sum of digits of a number def digitsSum(n): return sum(list(map(int, str(n).strip()))) # ncr efficiently def ncr(n, r): r = min(r, n - r) numer = reduce(op.mul, list(range(n, n - r, -1)), 1) denom = reduce(op.mul, list(range(1, r + 1)), 1) return numer // denom # or / in Python 2 #factors of a number def factors(n): return list(set(reduce(list.__add__, ([i, n // i] for i in range(1, int(n**0.5) + 1) if n % i == 0)))) #prime factors of a number def prime_factors(n): i,factors = 2,[] while i * i <= n: if n % i: i += 1 else: n //= i factors.append(i) if n > 1: factors.append(n) return set(factors) def prefixSum(arr): for i in range(1, len(arr)): arr[i] = arr[i] + arr[i-1] return arr def binomial_coefficient(n, k): if 0 <= k <= n: ntok = 1 ktok = 1 for t in range(1, min(k, n - k) + 1): ntok *= n ktok *= t n -= 1 return ntok // ktok else: return 0 def get_num_2_5(n): fives = 0 while n>0 and n%5 == 0: n//=5 fives+=1 return (power2(n),fives) def shift(a,i,num): for _ in range(num): a[i],a[i+1],a[i+2] = a[i+2],a[i],a[i+1] def powerOfK(k, max): if k == 1: return [1] if k == -1: return [-1, 1] result = [] n = 1 while n <= max: result.append(n) n *= k return result def getAngle(a, b, c): ang = degrees(atan2(c[1]-b[1], c[0]-b[0]) - atan2(a[1]-b[1], a[0]-b[0])) return ang + 360 if ang < 0 else ang def getLength(a,b): return sqrt((a[0]-b[0])**2 + (a[1]-b[1])**2) # maximum subarray sum use kadane's algorithm def kadane(a,size): max_so_far = curr_max = a[0] for i in range(1,size): curr_max = max(a[i], curr_max + a[i]) max_so_far = max(max_so_far,curr_max) return max_so_far def divisors(n): result = [] for i in range(1,ceil(sqrt(n))+1): if n%i == 0: result.append(i) result.append(n/i) return list(set(result)) def equal(x,y): return abs(x-y) <= 1e-9 def sumtilln(n): return ((n*(n+1))//2) def isPrime(n) : if (n <= 1) : return False if (n <= 3) : return True if (n % 2 == 0 or n % 3 == 0) : return False for i in range(5,ceil(sqrt(n))+1,6): if (n % i == 0 or n % (i + 2) == 0) : return False return True def isPowerOf2(x): return (x and (not(x & (x - 1))) ) def power2(n): return len(str(bin((n & (~(n - 1)))))-1) def sqsum(n): return ((n*(n+1))*(2*n+1)//6) def cusum(n): return ((sumn(n))**2) def pa(a): print(*a) def printarrayasstring(a): print(*a,sep = '') def pm(a): for i in a: print(*i) def pmasstring(a): for i in a: print(*i,sep = '') def print_case_iterable(case_num, iterable): print("Case #{}: {}".format(case_num," ".join(map(str,iterable)))) def print_case_number(case_num, iterable): print("Case #{}: {}".format(case_num,iterable)) def isPerfectSquare(n): return pow(floor(sqrt(n)),2) == n def nC2(n,m): return (((n*(n-1))//2) % m) def modInverse(n,p): return pow(n,p-2,p) def ncrmodp(n, r, p): num = den = 1 for i in range(r): num = (num * (n - i)) % p den = (den * (i + 1)) % p return (num * pow(den,p - 2, p)) % p def reverse(string): return "".join(reversed(string)) def listtostr(s): return ' '.join([str(elem) for elem in s]) def binarySearch(arr, l, r, x): while l <= r: mid = l + (r - l) // 2; if arr[mid] == x: return mid elif arr[mid] < x: l = mid + 1 else: r = mid - 1 return -1 # Returns largest power of p that divides n! def largestPower(n, p): x = 0 while (n): n //= p x += n return x def isarrayodd(a): return len(a) == len(list(filter(lambda x: (x%2 == 1) , a))) def isarrayeven(a): return len(a) == len(list(filter(lambda x: (x%2 == 0) , a))) def isPalindrome(s): return s == s[::-1] def gt(x,h,c,t): return ((x*h+(x-1)*c)/(2*x-1)) def CountFrequency(my_list): return Counter(my_list) def CountFrequencyasPair(my_list1,my_list2,freq): for item in my_list1: freq[item][0] = (freq[item][0] + 1 if (item in freq) else 1) for item in my_list2: freq[item][1] = (freq[item][1] + 1 if (item in freq) else 1) return freq def CountSquares(a, b):return (floor(sqrt(b)) - ceil(sqrt(a)) + 1) def binarySearchCount(arr, n, key): left = 0 right = n - 1 count = 0 while (left <= right): mid = int((right + left) / 2) if (arr[mid] <= key): count,left = mid + 1,mid + 1 else: right = mid - 1 return count def primes(n): sieve,l = [True] * (n+1),[] for p in range(2, n+1): if (sieve[p]): l.append(p) for i in range(p, n+1, p): sieve[i] = False return l def Next_Greater_Element_for_all_in_array(arr): s,n,reta,retb = list(),len(arr),[],[] arr1 = [list([0,i]) for i in range(n)] for i in range(n - 1, -1, -1): while (len(s) > 0 and s[-1][0] <= arr[i]): s.pop() arr1[i][0] = (-1 if len(s) == 0 else s[-1]) s.append(list([arr[i],i])) for i in range(n): reta.append(list([arr[i],i])) retb.append(arr1[i][0]) return reta,retb def find_lcm_array(A): l = A[0] for i in range(1, len(A)): l = lcm(l, A[i]) return l def polygonArea(X,Y,n): area = 0.0 j = n - 1 for i in range(n): area += (X[j] + X[i]) * (Y[j] - Y[i]) j = i return abs(area / 2.0) def merge(a, b): return a|b def subarrayBitwiseOR(A): res,pre = set(),{0} for x in A: pre = {x | y for y in pre} | {x} res |= pre return len(res) # Print the all possible subset sums that lie in a particular interval of l <= sum <= target def subset_sum(numbers,l,target, partial=[]): s = sum(partial) if l <= s <= target: print("sum(%s)=%s" % (partial, s)) if s >= target: return for i in range(len(numbers)): subset_sum(numbers[i+1:], l,target, partial + [numbers[i]]) def isSubsetSum(arr, n, summ): # The value of subarr[i][j] will be true if there is a # subarr of arr[0..j-1] with summ equal to i subarr = ([[False for i in range(summ + 1)] for i in range(n + 1)]) # If summ is 0, then answer is true for i in range(n + 1): subarr[i][0] = True # If summ is not 0 and arr is empty,then answer is false for i in range(1, summ + 1): subarr[0][i]= False # Fill the subarr table in botton up manner for i in range(1, n + 1): for j in range(1, summ + 1): if j<arr[i-1]: subarr[i][j] = subarr[i-1][j] if j>= arr[i-1]: subarr[i][j] = (subarr[i-1][j] or subarr[i - 1][j-arr[i-1]]) return subarr[n][summ] def pre(s): n = len(s) pi = [0] * n for i in range(1, n): j = pi[i - 1] while j and s[i] != s[j]: j = pi[j - 1] if s[i] == s[j]: j += 1 pi[i] = j return pi def prodofarray(a): return np.prod(a) def binary(x, length=16): y = bin(x)[2:] return y if len(y) >= length else "0" * (length - len(y)) + y def printSubsequences(arr, index, subarr): if index == len(arr): if len(subarr) != 0: print(subarr) else: printSubsequences(arr, index + 1, subarr) printSubsequences(arr, index + 1, subarr+[arr[index]]) return def modFact(n, p): if n >= p: return 0 result = 1 for i in range(1, n + 1): result = (result * i) % p return result #defining a LRU Cache # where we can set values and get values based on our requirement class LRUCache: # initialising capacity def __init__(self, capacity: int): self.cache = OrderedDict() self.capacity = capacity # we return the value of the key # that is queried in O(1) and return -1 if we # don't find the key in out dict / cache. # And also move the key to the end # to show that it was recently used. def get(self, key: int) -> int: if key not in self.cache: return -1 else: self.cache.move_to_end(key) return self.cache[key] def put(self, key: int, value: int) -> None: self.cache[key] = value self.cache.move_to_end(key) if len(self.cache) > self.capacity: self.cache.popitem(last = False) class segtree: def __init__(self,n): self.m = 1 while self.m < n: self.m *= 2 self.data = [0] * (2 * self.m) def __setitem__(self,i,x): x = +(x != 1) i += self.m self.data[i] = x i >>= 1 while i: self.data[i] = self.data[2 * i] + self.data[2 * i + 1] i >>= 1 def __call__(self,l,r): l += self.m r += self.m s = 0 while l < r: if l & 1: s += self.data[l] l += 1 if r & 1: r -= 1 s += self.data[r] l >>= 1 r >>= 1 return s class FenwickTree: def __init__(self, n): self.n = n self.bit = [0]*(n+1) def update(self, x, d): while x <= self.n: self.bit[x] += d x += (x & (-x)) def query(self, x): res = 0 while x > 0: res += self.bit[x] x -= (x & (-x)) return res def range_query(self, l, r): return self.query(r) - self.query(l-1) # Python program to print connected # components in an undirected graph class Graph: def __init__(self,V): self.V = V self.adj = [[] for i in range(V)] def DFSUtil(self, temp, v, visited): visited[v] = True temp.append(v) for i in self.adj[v]: if visited[i] == False: temp = self.DFSUtil(temp, i, visited) return temp # method to add an undirected edge def addEdge(self, v, w): self.adj[v].append(w) self.adj[w].append(v) # Method to retrieve connected components in an undirected graph def connectedComponents(self): visited,cc = [False for i in range(self.V)],[] for v in range(self.V): if visited[v] == False: temp = [] cc.append(self.DFSUtil(temp, v, visited)) return cc class MergeFind: def __init__(self, n): self.parent = list(range(n)) self.size = [1] * n self.num_sets = n self.lista = [[_] for _ in range(n)] def find(self, a): to_update = [] while a != self.parent[a]: to_update.append(a) a = self.parent[a] for b in to_update: self.parent[b] = a return self.parent[a] def merge(self, a, b): a = self.find(a) b = self.find(b) if a == b: return if self.size[a] < self.size[b]: a, b = b, a self.num_sets -= 1 self.parent[b] = a self.size[a] += self.size[b] self.lista[a] += self.lista[b] self.lista[b] = [] def set_size(self, a): return self.size[self.find(a)] def __len__(self): return self.num_sets # This is Kosaraju's Algorithm and use this class of graph for only that purpose # can add more template functions here # end of template functions # To enable the file I/O i the below 2 lines are uncommented. # read from in.txt if uncommented if os.path.exists('in.txt'): sys.stdin = open('in.txt','r') # will print on Console if file I/O is not activated if os.path.exists('out.txt'): sys.stdout=open('out.txt', 'w') # inputs template #for fast input we are using sys.stdin def inp(): return sys.stdin.readline() #for fast output, always take string def out(var): sys.stdout.write(str(var) + "\n") # custom base input needed for the program def I(): return (inp()) def II(): return (int(inp())) def FI(): return (float(inp())) def SI(): return (list(str(inp()))) def MI(): return (map(int,inp().split())) def LI(): return (list(MI())) def SLI(): return (sorted(LI())) def MF(): return (map(float,inp().split())) def LF(): return (list(MF())) def SLF(): return (sorted(LF())) # end of inputs template # common modulo values used in competitive programming sys.setrecursionlimit(10**9) INF = float('inf') MOD = 998244353 mod = 10**9+7 # any particular user-defined functions for the code. # can be written here. # end of any user-defined functions # main functions for execution of the program. def __starting_point(): # execute your program from here. # start your main code from here # Write your code k_max = 524288 digmap = defaultdict(list) for i in range(k_max): n_dig = bin(i).count("1") digmap[n_dig].append(i) t = int(eval(input())) for _ in range(t): n, k = map(int, input().split()) seq_max = (1<<n)-1 seq = [None]*k odd_pointer = 0 odd_position = 1 even_pointer = 0 even_position = 0 idx = 0 current_flag = False while idx < k: if current_flag: seq[idx] = digmap[odd_position][odd_pointer] odd_pointer += 1 if odd_pointer >= len(digmap[odd_position]): odd_position += 2 odd_pointer = 0 if digmap[odd_position][odd_pointer] > seq_max: odd_position += 2 odd_pointer = 0 idx += 1 else: seq[idx] = digmap[even_position][even_pointer] even_pointer += 1 if even_pointer >= len(digmap[even_position]): even_position += 2 even_pointer = 0 if digmap[even_position][even_pointer] > seq_max: even_position += 2 even_pointer = 0 idx += 1 if idx & 1: current_flag = not current_flag if (bin(seq[1]).count("1") == bin(seq[k-1]).count("1")): seq[k-1] = seq_max if (bin(seq[1]).count("1") == bin(seq[k-1]).count("1")): seq[k-1] = seq_max for idx in range(k-1): print(seq[idx], seq[idx+1]) print(seq[k-1], seq[0]) # end of main code # end of program # This program is written by : # Shubham Gupta # B.Tech (2019-2023) # Computer Science and Engineering, # Department of EECS # Contact No:8431624358 # Indian Institute of Technology(IIT),Bhilai # Sejbahar, # Datrenga, # Raipur, # Chhattisgarh # 492015 # THANK YOU FOR #YOUR KIND PATIENCE FOR READING THE PROGRAM. __starting_point()
# import all important libraries and inbuilt functions from fractions import Fraction import numpy as np import sys,bisect,copyreg,statistics,os,time,socket,socketserver,atexit,io from math import gcd,ceil,floor,sqrt,copysign,factorial,fmod,fsum,degrees from math import expm1,exp,log,log2,acos,asin,cos,tan,sin,pi,e,tau,inf,nan,atan2 from collections import Counter,defaultdict,deque,OrderedDict from itertools import combinations,permutations,accumulate,groupby,compress from numpy.linalg import matrix_power as mp from bisect import bisect_left,bisect_right,bisect,insort,insort_left,insort_right from statistics import * from copy import copy,deepcopy from functools import reduce,cmp_to_key,lru_cache from io import BytesIO, IOBase from scipy.spatial import ConvexHull from heapq import * from decimal import * from queue import Queue,PriorityQueue from re import sub,subn from random import shuffle,randrange,randint,random from types import GeneratorType from string import ascii_lowercase from time import perf_counter from datetime import datetime from operator import ior,mul # never import pow from math library it does not perform modulo # use standard pow -- better than math.pow # end of library import # map system version faults if sys.version_info[0] < 3: from builtins import xrange as range from future_builtins import ascii, filter, hex, map, oct, zip # template of many functions used in competitive programming can add more later # based on need we will use this commonly. # definition of vertex of a graph def graph(vertex): return [[] for i in range(vertex+1)] def lcm(a,b): return (a*b)//gcd(a,b) # most common list in a array of lists def most_frequent(List): return Counter(List).most_common(1)[0][0] # element with highest frequency def most_common(List): return(mode(List)) #In number theory, the Chinese remainder theorem states that #if one knows the remainders of the Euclidean division of an integer n by #several integers, then one can determine uniquely the remainder of the #division of n by the product of these integers, under the condition #that the divisors are pairwise coprime. def chinese_remainder(a, p): prod = reduce(op.mul, p, 1) x = [prod // piii for piii in p] return sum(a[i] * pow(x[i], p[i] - 2, p[i]) * x[i] for i in range(len(a))) % prod def bootstrap(f, stack=[]): def wrappedfunc(*args, **kwargs): if stack: return f(*args, **kwargs) else: to = f(*args, **kwargs) while True: if type(to) is GeneratorType: stack.append(to);to = next(to) else: stack.pop() if not stack: break to = stack[-1].send(to) return to return wrappedfunc # input for a binary tree def readTree(): v = II() adj=[set() for i in range(v+1)] for i in range(v-1): u1,u2 = MI() adj[u1].add(u2) adj[u2].add(u1) return adj,v #count setbits of a number. def setBit(n): return bin(n).count('1'); # sum of digits of a number def digitsSum(n): return sum(list(map(int, str(n).strip()))) # ncr efficiently def ncr(n, r): r = min(r, n - r) numer = reduce(op.mul, list(range(n, n - r, -1)), 1) denom = reduce(op.mul, list(range(1, r + 1)), 1) return numer // denom # or / in Python 2 #factors of a number def factors(n): return list(set(reduce(list.__add__, ([i, n // i] for i in range(1, int(n**0.5) + 1) if n % i == 0)))) #prime factors of a number def prime_factors(n): i,factors = 2,[] while i * i <= n: if n % i: i += 1 else: n //= i factors.append(i) if n > 1: factors.append(n) return set(factors) def prefixSum(arr): for i in range(1, len(arr)): arr[i] = arr[i] + arr[i-1] return arr def binomial_coefficient(n, k): if 0 <= k <= n: ntok = 1 ktok = 1 for t in range(1, min(k, n - k) + 1): ntok *= n ktok *= t n -= 1 return ntok // ktok else: return 0 def get_num_2_5(n): fives = 0 while n>0 and n%5 == 0: n//=5 fives+=1 return (power2(n),fives) def shift(a,i,num): for _ in range(num): a[i],a[i+1],a[i+2] = a[i+2],a[i],a[i+1] def powerOfK(k, max): if k == 1: return [1] if k == -1: return [-1, 1] result = [] n = 1 while n <= max: result.append(n) n *= k return result def getAngle(a, b, c): ang = degrees(atan2(c[1]-b[1], c[0]-b[0]) - atan2(a[1]-b[1], a[0]-b[0])) return ang + 360 if ang < 0 else ang def getLength(a,b): return sqrt((a[0]-b[0])**2 + (a[1]-b[1])**2) # maximum subarray sum use kadane's algorithm def kadane(a,size): max_so_far = curr_max = a[0] for i in range(1,size): curr_max = max(a[i], curr_max + a[i]) max_so_far = max(max_so_far,curr_max) return max_so_far def divisors(n): result = [] for i in range(1,ceil(sqrt(n))+1): if n%i == 0: result.append(i) result.append(n/i) return list(set(result)) def equal(x,y): return abs(x-y) <= 1e-9 def sumtilln(n): return ((n*(n+1))//2) def isPrime(n) : if (n <= 1) : return False if (n <= 3) : return True if (n % 2 == 0 or n % 3 == 0) : return False for i in range(5,ceil(sqrt(n))+1,6): if (n % i == 0 or n % (i + 2) == 0) : return False return True def isPowerOf2(x): return (x and (not(x & (x - 1))) ) def power2(n): return len(str(bin((n & (~(n - 1)))))-1) def sqsum(n): return ((n*(n+1))*(2*n+1)//6) def cusum(n): return ((sumn(n))**2) def pa(a): print(*a) def printarrayasstring(a): print(*a,sep = '') def pm(a): for i in a: print(*i) def pmasstring(a): for i in a: print(*i,sep = '') def print_case_iterable(case_num, iterable): print("Case #{}: {}".format(case_num," ".join(map(str,iterable)))) def print_case_number(case_num, iterable): print("Case #{}: {}".format(case_num,iterable)) def isPerfectSquare(n): return pow(floor(sqrt(n)),2) == n def nC2(n,m): return (((n*(n-1))//2) % m) def modInverse(n,p): return pow(n,p-2,p) def ncrmodp(n, r, p): num = den = 1 for i in range(r): num = (num * (n - i)) % p den = (den * (i + 1)) % p return (num * pow(den,p - 2, p)) % p def reverse(string): return "".join(reversed(string)) def listtostr(s): return ' '.join([str(elem) for elem in s]) def binarySearch(arr, l, r, x): while l <= r: mid = l + (r - l) // 2; if arr[mid] == x: return mid elif arr[mid] < x: l = mid + 1 else: r = mid - 1 return -1 # Returns largest power of p that divides n! def largestPower(n, p): x = 0 while (n): n //= p x += n return x def isarrayodd(a): return len(a) == len(list(filter(lambda x: (x%2 == 1) , a))) def isarrayeven(a): return len(a) == len(list(filter(lambda x: (x%2 == 0) , a))) def isPalindrome(s): return s == s[::-1] def gt(x,h,c,t): return ((x*h+(x-1)*c)/(2*x-1)) def CountFrequency(my_list): return Counter(my_list) def CountFrequencyasPair(my_list1,my_list2,freq): for item in my_list1: freq[item][0] = (freq[item][0] + 1 if (item in freq) else 1) for item in my_list2: freq[item][1] = (freq[item][1] + 1 if (item in freq) else 1) return freq def CountSquares(a, b):return (floor(sqrt(b)) - ceil(sqrt(a)) + 1) def binarySearchCount(arr, n, key): left = 0 right = n - 1 count = 0 while (left <= right): mid = int((right + left) / 2) if (arr[mid] <= key): count,left = mid + 1,mid + 1 else: right = mid - 1 return count def primes(n): sieve,l = [True] * (n+1),[] for p in range(2, n+1): if (sieve[p]): l.append(p) for i in range(p, n+1, p): sieve[i] = False return l def Next_Greater_Element_for_all_in_array(arr): s,n,reta,retb = list(),len(arr),[],[] arr1 = [list([0,i]) for i in range(n)] for i in range(n - 1, -1, -1): while (len(s) > 0 and s[-1][0] <= arr[i]): s.pop() arr1[i][0] = (-1 if len(s) == 0 else s[-1]) s.append(list([arr[i],i])) for i in range(n): reta.append(list([arr[i],i])) retb.append(arr1[i][0]) return reta,retb def find_lcm_array(A): l = A[0] for i in range(1, len(A)): l = lcm(l, A[i]) return l def polygonArea(X,Y,n): area = 0.0 j = n - 1 for i in range(n): area += (X[j] + X[i]) * (Y[j] - Y[i]) j = i return abs(area / 2.0) def merge(a, b): return a|b def subarrayBitwiseOR(A): res,pre = set(),{0} for x in A: pre = {x | y for y in pre} | {x} res |= pre return len(res) # Print the all possible subset sums that lie in a particular interval of l <= sum <= target def subset_sum(numbers,l,target, partial=[]): s = sum(partial) if l <= s <= target: print("sum(%s)=%s" % (partial, s)) if s >= target: return for i in range(len(numbers)): subset_sum(numbers[i+1:], l,target, partial + [numbers[i]]) def isSubsetSum(arr, n, summ): # The value of subarr[i][j] will be true if there is a # subarr of arr[0..j-1] with summ equal to i subarr = ([[False for i in range(summ + 1)] for i in range(n + 1)]) # If summ is 0, then answer is true for i in range(n + 1): subarr[i][0] = True # If summ is not 0 and arr is empty,then answer is false for i in range(1, summ + 1): subarr[0][i]= False # Fill the subarr table in botton up manner for i in range(1, n + 1): for j in range(1, summ + 1): if j<arr[i-1]: subarr[i][j] = subarr[i-1][j] if j>= arr[i-1]: subarr[i][j] = (subarr[i-1][j] or subarr[i - 1][j-arr[i-1]]) return subarr[n][summ] def pre(s): n = len(s) pi = [0] * n for i in range(1, n): j = pi[i - 1] while j and s[i] != s[j]: j = pi[j - 1] if s[i] == s[j]: j += 1 pi[i] = j return pi def prodofarray(a): return np.prod(a) def binary(x, length=16): y = bin(x)[2:] return y if len(y) >= length else "0" * (length - len(y)) + y def printSubsequences(arr, index, subarr): if index == len(arr): if len(subarr) != 0: print(subarr) else: printSubsequences(arr, index + 1, subarr) printSubsequences(arr, index + 1, subarr+[arr[index]]) return def modFact(n, p): if n >= p: return 0 result = 1 for i in range(1, n + 1): result = (result * i) % p return result #defining a LRU Cache # where we can set values and get values based on our requirement class LRUCache: # initialising capacity def __init__(self, capacity: int): self.cache = OrderedDict() self.capacity = capacity # we return the value of the key # that is queried in O(1) and return -1 if we # don't find the key in out dict / cache. # And also move the key to the end # to show that it was recently used. def get(self, key: int) -> int: if key not in self.cache: return -1 else: self.cache.move_to_end(key) return self.cache[key] def put(self, key: int, value: int) -> None: self.cache[key] = value self.cache.move_to_end(key) if len(self.cache) > self.capacity: self.cache.popitem(last = False) class segtree: def __init__(self,n): self.m = 1 while self.m < n: self.m *= 2 self.data = [0] * (2 * self.m) def __setitem__(self,i,x): x = +(x != 1) i += self.m self.data[i] = x i >>= 1 while i: self.data[i] = self.data[2 * i] + self.data[2 * i + 1] i >>= 1 def __call__(self,l,r): l += self.m r += self.m s = 0 while l < r: if l & 1: s += self.data[l] l += 1 if r & 1: r -= 1 s += self.data[r] l >>= 1 r >>= 1 return s class FenwickTree: def __init__(self, n): self.n = n self.bit = [0]*(n+1) def update(self, x, d): while x <= self.n: self.bit[x] += d x += (x & (-x)) def query(self, x): res = 0 while x > 0: res += self.bit[x] x -= (x & (-x)) return res def range_query(self, l, r): return self.query(r) - self.query(l-1) # Python program to print connected # components in an undirected graph class Graph: def __init__(self,V): self.V = V self.adj = [[] for i in range(V)] def DFSUtil(self, temp, v, visited): visited[v] = True temp.append(v) for i in self.adj[v]: if visited[i] == False: temp = self.DFSUtil(temp, i, visited) return temp # method to add an undirected edge def addEdge(self, v, w): self.adj[v].append(w) self.adj[w].append(v) # Method to retrieve connected components in an undirected graph def connectedComponents(self): visited,cc = [False for i in range(self.V)],[] for v in range(self.V): if visited[v] == False: temp = [] cc.append(self.DFSUtil(temp, v, visited)) return cc class MergeFind: def __init__(self, n): self.parent = list(range(n)) self.size = [1] * n self.num_sets = n self.lista = [[_] for _ in range(n)] def find(self, a): to_update = [] while a != self.parent[a]: to_update.append(a) a = self.parent[a] for b in to_update: self.parent[b] = a return self.parent[a] def merge(self, a, b): a = self.find(a) b = self.find(b) if a == b: return if self.size[a] < self.size[b]: a, b = b, a self.num_sets -= 1 self.parent[b] = a self.size[a] += self.size[b] self.lista[a] += self.lista[b] self.lista[b] = [] def set_size(self, a): return self.size[self.find(a)] def __len__(self): return self.num_sets # This is Kosaraju's Algorithm and use this class of graph for only that purpose # can add more template functions here # end of template functions # To enable the file I/O i the below 2 lines are uncommented. # read from in.txt if uncommented if os.path.exists('in.txt'): sys.stdin = open('in.txt','r') # will print on Console if file I/O is not activated if os.path.exists('out.txt'): sys.stdout=open('out.txt', 'w') # inputs template #for fast input we are using sys.stdin def inp(): return sys.stdin.readline() #for fast output, always take string def out(var): sys.stdout.write(str(var) + "\n") # custom base input needed for the program def I(): return (inp()) def II(): return (int(inp())) def FI(): return (float(inp())) def SI(): return (list(str(inp()))) def MI(): return (map(int,inp().split())) def LI(): return (list(MI())) def SLI(): return (sorted(LI())) def MF(): return (map(float,inp().split())) def LF(): return (list(MF())) def SLF(): return (sorted(LF())) # end of inputs template # common modulo values used in competitive programming sys.setrecursionlimit(10**9) INF = float('inf') MOD = 998244353 mod = 10**9+7 # any particular user-defined functions for the code. # can be written here. # end of any user-defined functions # main functions for execution of the program. def __starting_point(): # execute your program from here. # start your main code from here # Write your code k_max = 524288 digmap = defaultdict(list) for i in range(k_max): n_dig = bin(i).count("1") digmap[n_dig].append(i) t = int(eval(input())) for _ in range(t): n, k = map(int, input().split()) seq_max = (1<<n)-1 seq = [None]*k odd_pointer = 0 odd_position = 1 even_pointer = 0 even_position = 0 idx = 0 current_flag = False while idx < k: if current_flag: seq[idx] = digmap[odd_position][odd_pointer] odd_pointer += 1 if odd_pointer >= len(digmap[odd_position]): odd_position += 2 odd_pointer = 0 if digmap[odd_position][odd_pointer] > seq_max: odd_position += 2 odd_pointer = 0 idx += 1 else: seq[idx] = digmap[even_position][even_pointer] even_pointer += 1 if even_pointer >= len(digmap[even_position]): even_position += 2 even_pointer = 0 if digmap[even_position][even_pointer] > seq_max: even_position += 2 even_pointer = 0 idx += 1 if idx & 1: current_flag = not current_flag if (bin(seq[1]).count("1") == bin(seq[k-1]).count("1")): seq[k-1] = seq_max if (bin(seq[1]).count("1") == bin(seq[k-1]).count("1")): seq[k-1] = seq_max for idx in range(k-1): print(seq[idx], seq[idx+1]) print(seq[k-1], seq[0]) # end of main code # end of program # This program is written by : # Shubham Gupta # B.Tech (2019-2023) # Computer Science and Engineering, # Department of EECS # Contact No:8431624358 # Indian Institute of Technology(IIT),Bhilai # Sejbahar, # Datrenga, # Raipur, # Chhattisgarh # 492015 # THANK YOU FOR #YOUR KIND PATIENCE FOR READING THE PROGRAM. __starting_point()
train
APPS_structured
Akshay is interested in mathematics, one day he came across a problem of modulus operator.He has a list of M integers say arr[M] and has to find all integers K such that : - K > 1 - arr[1]%K = arr[2]%K = arr[3]%K = … = arr[M]%K where '%' is a modulus operator. Help Akshay to find all such K's. -----Input:----- - First line of input contains an integer M. Then M lines follow each containing one integer of the list. Input data is such that at least one integer K will always exist. -----Output:----- - Output all possible integers K separated by space in increasing order. -----Constraints----- - 2<= M <=100 - 1< value of each integer <109 - All integers will be distinct -----Sample Input:----- 3 38 6 34 -----Sample Output:----- 2 4
def find_gcd(x, y): while(y): x, y = y, x % y return x def print_factors(x): for i in range(2, x + 1): if x % i == 0: print(i,end=" ") t=int(input()) l=[] for i in range(t): n=int(input()) l.append(n) l2=[] i=0 for i in range(t-1): l2.append(abs(l[i+1]-l[i])) num1 = l2[0] num2 = l2[1] gcd = find_gcd(num1, num2) for i in range(2, len(l2)): gcd = find_gcd(gcd, l2[i]) #print(gcd) print_factors(gcd)
def find_gcd(x, y): while(y): x, y = y, x % y return x def print_factors(x): for i in range(2, x + 1): if x % i == 0: print(i,end=" ") t=int(input()) l=[] for i in range(t): n=int(input()) l.append(n) l2=[] i=0 for i in range(t-1): l2.append(abs(l[i+1]-l[i])) num1 = l2[0] num2 = l2[1] gcd = find_gcd(num1, num2) for i in range(2, len(l2)): gcd = find_gcd(gcd, l2[i]) #print(gcd) print_factors(gcd)
train
APPS_structured
Chef's new hobby is painting, but he learned the fact that it's not easy to paint 2D pictures in a hard way, after wasting a lot of canvas paper, paint and of course time. From now on, he decided to paint 1D pictures only. Chef's canvas is N millimeters long and is initially all white. For simplicity, colors will be represented by an integer between 0 and 105. 0 indicates white. The picture he is envisioning is also N millimeters long and the ith millimeter consists purely of the color Ci. Unfortunately, his brush isn't fine enough to paint every millimeter one by one. The brush is 3 millimeters wide and so it can only paint three millimeters at a time with the same color. Painting over the same place completely replaces the color by the new one. Also, Chef has lots of bottles of paints of each color, so he will never run out of paint of any color. Chef also doesn't want to ruin the edges of the canvas, so he doesn't want to paint any part beyond the painting. This means, for example, Chef cannot paint just the first millimeter of the canvas, or just the last two millimeters, etc. Help Chef by telling him whether he can finish the painting or not with these restrictions. -----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. The second line contains N space-separated integers C1, C2, ..., CN denoting the colors of Chef's painting. -----Output----- For each test case, output a single line containing either “Yes” or “No” (without quotes), denoting whether Chef can finish the painting or not. -----Constraints----- - 1 ≤ T ≤ 105 - 3 ≤ N ≤ 105 - The sum of the Ns over all the test cases in a single test file is ≤ 5×105 - 1 ≤ Ci ≤ 105 -----Example----- Input:3 4 1 5 5 5 4 1 1 1 5 3 5 5 2 Output:Yes Yes No -----Explanation----- Example case 1. Chef's canvas initially contains the colors [0,0,0,0]. Chef can finish the painting by first painting the first three millimeters with color 1, so the colors become [1,1,1,0], and then the last three millimeters with color 5 so that it becomes [1,5,5,5]. Example case 2. Chef's canvas initially contains the colors [0,0,0,0]. Chef can finish the painting by first painting the last three millimeters by color 5 so the colors become [0,5,5,5], and then the first three millimeters by color 1 so it becomes [1,1,1,5]. Example case 3. In this test case, Chef can only paint the painting as a whole, so all parts must have the same color, and the task is impossible.
for _ in range(int(input())): n=int(input()) a=list(map(int,input().split())) flag=0 for i in range(len(a)-2): if len(set(a[i:i+3]))==1: print('Yes') flag=1 break else: flag=0 if flag==0: print('No')
for _ in range(int(input())): n=int(input()) a=list(map(int,input().split())) flag=0 for i in range(len(a)-2): if len(set(a[i:i+3]))==1: print('Yes') flag=1 break else: flag=0 if flag==0: print('No')
train
APPS_structured
A new pack of n t-shirts came to a shop. Each of the t-shirts is characterized by three integers p_{i}, a_{i} and b_{i}, where p_{i} is the price of the i-th t-shirt, a_{i} is front color of the i-th t-shirt and b_{i} is back color of the i-th t-shirt. All values p_{i} are distinct, and values a_{i} and b_{i} are integers from 1 to 3. m buyers will come to the shop. Each of them wants to buy exactly one t-shirt. For the j-th buyer we know his favorite color c_{j}. A buyer agrees to buy a t-shirt, if at least one side (front or back) is painted in his favorite color. Among all t-shirts that have colors acceptable to this buyer he will choose the cheapest one. If there are no such t-shirts, the buyer won't buy anything. Assume that the buyers come one by one, and each buyer is served only after the previous one is served. You are to compute the prices each buyer will pay for t-shirts. -----Input----- The first line contains single integer n (1 ≤ n ≤ 200 000) — the number of t-shirts. The following line contains sequence of integers p_1, p_2, ..., p_{n} (1 ≤ p_{i} ≤ 1 000 000 000), where p_{i} equals to the price of the i-th t-shirt. The following line contains sequence of integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 3), where a_{i} equals to the front color of the i-th t-shirt. The following line contains sequence of integers b_1, b_2, ..., b_{n} (1 ≤ b_{i} ≤ 3), where b_{i} equals to the back color of the i-th t-shirt. The next line contains single integer m (1 ≤ m ≤ 200 000) — the number of buyers. The following line contains sequence c_1, c_2, ..., c_{m} (1 ≤ c_{j} ≤ 3), where c_{j} equals to the favorite color of the j-th buyer. The buyers will come to the shop in the order they are given in the input. Each buyer is served only after the previous one is served. -----Output----- Print to the first line m integers — the j-th integer should be equal to the price of the t-shirt which the j-th buyer will buy. If the j-th buyer won't buy anything, print -1. -----Examples----- Input 5 300 200 400 500 911 1 2 1 2 3 2 1 3 2 1 6 2 3 1 2 1 1 Output 200 400 300 500 911 -1 Input 2 1000000000 1 1 1 1 2 2 2 1 Output 1 1000000000
n = int(input()) p = [int(i) for i in input().split()] a = [int(i) for i in input().split()] b = [int(i) for i in input().split()] s = [] for i in range(n): s.append([p[i], a[i], b[i]]) s = sorted(s) m = int(input()) c = [int(i) for i in input().split()] idx = [0]*4 ans = [] for i in range(m): ci = c[i] while idx[ci] < n: if s[idx[ci]][1] == ci or s[idx[ci]][2] == ci: s[idx[ci]][1] = 0 s[idx[ci]][2] = 0 ans.append(s[idx[ci]][0]) break idx[ci]+=1 if idx[ci] == n: ans.append(-1) print(*ans)
n = int(input()) p = [int(i) for i in input().split()] a = [int(i) for i in input().split()] b = [int(i) for i in input().split()] s = [] for i in range(n): s.append([p[i], a[i], b[i]]) s = sorted(s) m = int(input()) c = [int(i) for i in input().split()] idx = [0]*4 ans = [] for i in range(m): ci = c[i] while idx[ci] < n: if s[idx[ci]][1] == ci or s[idx[ci]][2] == ci: s[idx[ci]][1] = 0 s[idx[ci]][2] = 0 ans.append(s[idx[ci]][0]) break idx[ci]+=1 if idx[ci] == n: ans.append(-1) print(*ans)
train
APPS_structured
We have three stones at points (0, 0), (1,0), and (0,1) on a two-dimensional plane. These three stones are said to form an L when they satisfy the following conditions: - Each of the stones is at integer coordinates. - Each of the stones is adjacent to another stone. (That is, for each stone, there is another stone whose distance from that stone is 1.) - The three stones do not lie on the same line. Particularly, the initial arrangement of the stone - (0, 0), (1,0), and (0,1) - forms an L. You can do the following operation any number of times: choose one of the stones and move it to any position. However, after each operation, the stones must form an L. You want to do as few operations as possible to put stones at points (ax, ay), (bx, by), and (cx, cy). How many operations do you need to do this? It is guaranteed that the desired arrangement of stones - (ax, ay), (bx, by), and (cx, cy) - forms an L. Under this condition, it is always possible to achieve the objective with a finite number of operations. You will be given T cases of this problem. Solve each of them. -----Notes----- We assume that the three stones are indistinguishable. For example, the stone that is initially at point (0,0) may be at any of the points (ax, ay), (bx, by), and (cx, cy) in the end. -----Constraints----- - 1 \leq T \leq 10^3 - |ax|,|ay|,|bx|,|by|,|cx|,|cy| \leq 10^9 - The desired arrangement of stones - (ax, ay), (bx, by), and (cx, cy) - forms an L. -----Input----- Input is given from Standard Input in the following format: T \text{case}_1 \vdots \text{case}_T Each case is in the following format: ax ay bx by cx cy -----Output----- Print T values. The i-th value should be the minimum number of operations for \text{case}_i. -----Sample Input----- 1 3 2 2 2 2 1 -----Sample Output----- 4 Let us use # to represent a stone. You can move the stones to the specified positions with four operations, as follows: .... .... .... ..#. ..## #... -> ##.. -> .##. -> .##. -> ..#. ##.. .#.. .#.. .... ....
# URL : https://atcoder.jp/contests/arc109/tasks/arc109_d T = int(input()) for _ in range(T): ax, ay, bx, by, cx, cy = list(map(int, input().split())) x = ax + bx + cx y = ay + by + cy if x == y: if x == 1: print((0)) elif x == 2: print((1)) elif x > 0: if x % 3 == 2: print(((x + 1) // 3 * 2)) else: print(((x - 1) // 3 * 2 + 1)) else: x = -x if x % 3 == 2: print(((x + 1) // 3 * 2 + 1)) else: print(((x + 2) // 3 * 2)) else: res = 0 for d in (x, y): if d % 3 == 2: if d > 0: res = max(res, (d - 2) // 3 * 2 + 1) else: res = max(res, (-d - 1) // 3 * 2 + 1) else: if d > 0: res = max(res, (d - 1) // 3 * 2) else: res = max(res, (-d + 1) // 3 * 2) print(res)
# URL : https://atcoder.jp/contests/arc109/tasks/arc109_d T = int(input()) for _ in range(T): ax, ay, bx, by, cx, cy = list(map(int, input().split())) x = ax + bx + cx y = ay + by + cy if x == y: if x == 1: print((0)) elif x == 2: print((1)) elif x > 0: if x % 3 == 2: print(((x + 1) // 3 * 2)) else: print(((x - 1) // 3 * 2 + 1)) else: x = -x if x % 3 == 2: print(((x + 1) // 3 * 2 + 1)) else: print(((x + 2) // 3 * 2)) else: res = 0 for d in (x, y): if d % 3 == 2: if d > 0: res = max(res, (d - 2) // 3 * 2 + 1) else: res = max(res, (-d - 1) // 3 * 2 + 1) else: if d > 0: res = max(res, (d - 1) // 3 * 2) else: res = max(res, (-d + 1) // 3 * 2) print(res)
train
APPS_structured
Gargi is thinking of a solution to a problem. Meanwhile, her friend asks her to solve another problem. Since Gargi is busy in her own problem, she seeks your help to solve the new problem. You are given a string S containing characters a-z (lower case letters) only. You need to change the string to a new string consisting of only one letter from a-z. For a given character S[i] in the string, if you change it to a character having lower ASCII value than the character S[i], you gain points equal to the difference in ASCII value of the old character and the new character. Similarly, for a given character S[j] in the string, if you change it to a character having higher ASCII value than the character S[j], you lose points equal to the difference in ASCII value of the old character and the new character. However, Gargi does not like gaining or losing points. She has asked you to change the string in such a way that the total losing or gaining of points at the end of the string conversion is minimum. Give Gargi the absolute value of the points you have at the end of the string conversion. -----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 of the T test case contains a string S containing only lower case characters (a-z) -----Output----- For each test case, output a single line containing the answer. -----Constraints----- - 1 ≤ T ≤ 10 - 1 ≤ |S| ≤ 100000 -----Example----- Input: 1 abba Output: 2 -----Explanation----- Example case 1. The new string can be aaaa where you have +2 points at the end of string conversion or it can be bbbb where you have -2 points at the end of string conversion. Hence the output is 2.
for t in range(int(input())): s = input() a = [0]*26 for c in s: for i in range(26): a[i] += ord(c)-(ord('a')+i) m = float("inf") for i in a: m = min(m, abs(i)) print(m)
for t in range(int(input())): s = input() a = [0]*26 for c in s: for i in range(26): a[i] += ord(c)-(ord('a')+i) m = float("inf") for i in a: m = min(m, abs(i)) print(m)
train
APPS_structured
Return an output string that translates an input string `s`/`$s` by replacing each character in `s`/`$s` with a number representing the number of times that character occurs in `s`/`$s` and separating each number with the character(s) `sep`/`$sep`.
from collections import Counter def freq_seq(s, sep): dic = Counter(s) result = '' for char in s: for key, value in list(dic.items()): if char == key: result += str(value)+sep return result[:-1]
from collections import Counter def freq_seq(s, sep): dic = Counter(s) result = '' for char in s: for key, value in list(dic.items()): if char == key: result += str(value)+sep return result[:-1]
train
APPS_structured
You are given a string s that consists of lower case English letters and brackets.  Reverse the strings in each pair of matching parentheses, starting from the innermost one. Your result should not contain any brackets. Example 1: Input: s = "(abcd)" Output: "dcba" Example 2: Input: s = "(u(love)i)" Output: "iloveu" Explanation: The substring "love" is reversed first, then the whole string is reversed. Example 3: Input: s = "(ed(et(oc))el)" Output: "leetcode" Explanation: First, we reverse the substring "oc", then "etco", and finally, the whole string. Example 4: Input: s = "a(bcdefghijkl(mno)p)q" Output: "apmnolkjihgfedcbq" Constraints: 0 <= s.length <= 2000 s only contains lower case English characters and parentheses. It's guaranteed that all parentheses are balanced.
class Solution: def reverseParentheses(self, s: str) -> str: stack = [''] for char in s: if char == '(': stack.append('') elif char == ')': temp = stack.pop()[::-1] stack[-1] += temp else: stack[-1] += char return ''.join(stack)
class Solution: def reverseParentheses(self, s: str) -> str: stack = [''] for char in s: if char == '(': stack.append('') elif char == ')': temp = stack.pop()[::-1] stack[-1] += temp else: stack[-1] += char return ''.join(stack)
train
APPS_structured
The principal of a school likes to put challenges to the students related with finding words of certain features. One day she said: "Dear students, the challenge for today is to find a word that has only one vowel and seven consonants but cannot have the letters "y" and "m". I'll give a special award for the first student that finds it." One of the students used his dictionary and spent all the night without sleeping, trying in vain to find the word. The next day, the word had not been found yet. This student observed that the principal has a pattern in the features for the wanted words: - The word should have **n** vowels, may be repeated, for example: in "engineering", n = 5. - The word should have **m** consonants, may be repeated also: in "engineering", m = 6. - The word should not have some forbidden letters (in an array), forbid_letters You will be provided with a list of words, WORD_LIST(python/crystal), wordList(javascript), wordList (haskell), $word_list(ruby), and you have to create the function, ```wanted_words()```, that receives the three arguments in the order given above, ```wanted_words(n, m, forbid_list)```and output an array with the word or an array, having the words in the order given in the pre-loaded list, in the case of two or more words were found. Let's see some cases: ```python wanted_words(1, 7, ["m", "y"]) == ["strength"] wanted_words(3, 7, ["m", "y"]) == ['afterwards', 'background', 'photograph', 'successful', 'understand'] ``` For cases where no words are found the function will output an empty array. ```python wanted_words(3, 7, ["a", "s" , "m", "y"]) == [] ``` Help our student to win this and the next challenges of the school. He needs to sure about a suspect that he has. That many times there are no solutions for what the principal is asking for. All words have its letters in lowercase format. Enjoy it!
from collections import Counter def wanted_words(n, m, forbid_let): result = [] for word in WORD_LIST: # for each word in word list if len(word) == n + m: # if word length is correct letters = Counter(word) # create a count of letters if ( sum(letters[c] for c in "aeiou") == n # if vowel count is correct and all(c not in word for c in forbid_let) ): # and has no forbidden letters result.append(word) # add to the results return result
from collections import Counter def wanted_words(n, m, forbid_let): result = [] for word in WORD_LIST: # for each word in word list if len(word) == n + m: # if word length is correct letters = Counter(word) # create a count of letters if ( sum(letters[c] for c in "aeiou") == n # if vowel count is correct and all(c not in word for c in forbid_let) ): # and has no forbidden letters result.append(word) # add to the results return result
train
APPS_structured
ZS the Coder loves mazes. Your job is to create one so that he can play with it. A maze consists of n × m rooms, and the rooms are arranged in n rows (numbered from the top to the bottom starting from 1) and m columns (numbered from the left to the right starting from 1). The room in the i-th row and j-th column is denoted by (i, j). A player starts in the room (1, 1) and wants to reach the room (n, m). Each room has four doors (except for ones at the maze border), one on each of its walls, and two adjacent by the wall rooms shares the same door. Some of the doors are locked, which means it is impossible to pass through the door. For example, if the door connecting (i, j) and (i, j + 1) is locked, then we can't go from (i, j) to (i, j + 1). Also, one can only travel between the rooms downwards (from the room (i, j) to the room (i + 1, j)) or rightwards (from the room (i, j) to the room (i, j + 1)) provided the corresponding door is not locked. [Image] This image represents a maze with some doors locked. The colored arrows denotes all the possible paths while a red cross denotes a locked door. ZS the Coder considers a maze to have difficulty x if there is exactly x ways of travelling from the room (1, 1) to the room (n, m). Two ways are considered different if they differ by the sequence of rooms visited while travelling. Your task is to create a maze such that its difficulty is exactly equal to T. In addition, ZS the Coder doesn't like large mazes, so the size of the maze and the number of locked doors are limited. Sounds simple enough, right? -----Input----- The first and only line of the input contains a single integer T (1 ≤ T ≤ 10^18), the difficulty of the required maze. -----Output----- The first line should contain two integers n and m (1 ≤ n, m ≤ 50) — the number of rows and columns of the maze respectively. The next line should contain a single integer k (0 ≤ k ≤ 300) — the number of locked doors in the maze. Then, k lines describing locked doors should follow. Each of them should contain four integers, x_1, y_1, x_2, y_2. This means that the door connecting room (x_1, y_1) and room (x_2, y_2) is locked. Note that room (x_2, y_2) should be adjacent either to the right or to the bottom of (x_1, y_1), i.e. x_2 + y_2 should be equal to x_1 + y_1 + 1. There should not be a locked door that appears twice in the list. It is guaranteed that at least one solution exists. If there are multiple solutions, print any of them. -----Examples----- Input 3 Output 3 2 0 Input 4 Output 4 3 3 1 2 2 2 3 2 3 3 1 3 2 3 -----Note----- Here are how the sample input and output looks like. The colored arrows denotes all the possible paths while a red cross denotes a locked door. In the first sample case: [Image] In the second sample case: [Image]
corr = lambda x, y: 1 <= x <= n and 1 <= y <= m T = int(input()) a = [] while T: a.append(T % 6) T //= 6 L = len(a) n = m = L * 2 + 2 ans = [(1, 2, 2, 2), (2, 1, 2, 2)] f = [[1] * 9 for i in range(7)] f[1][2] = f[2][2] = f[2][6] = f[3][5] = 0 f[4][5] = f[4][6] = f[5][2] = f[5][5] = f[5][6] = 0 p = [0] * 9 p[1] = 3, 1, 3, 2 p[2] = 4, 1, 4, 2 p[3] = 4, 2, 5, 2 p[4] = 4, 3, 5, 3 p[5] = 1, 3, 2, 3 p[6] = 1, 4, 2, 4 p[7] = 2, 4, 2, 5 p[8] = 3, 4, 3, 5 for i in range(L): bit = a[L - i - 1] for j in range(1, 9): if not f[bit][j]: continue x1, y1, x2, y2 = p[j]; D = 2 * i x1 += D; y1 += D; x2 += D; y2 += D if corr(x2, y2): ans.append((x1, y1, x2, y2)) for i in range(L - 1): x1, y1 = 5 + i * 2, 1 + i * 2 x2, y2 = 1 + i * 2, 5 + i * 2 ans.append((x1, y1, x1 + 1, y1)) ans.append((x1, y1 + 1, x1 + 1, y1 + 1)) ans.append((x2, y2, x2, y2 + 1)) ans.append((x2 + 1, y2, x2 + 1, y2 + 1)) print(n, m) print(len(ans)) [print(*i) for i in ans]
corr = lambda x, y: 1 <= x <= n and 1 <= y <= m T = int(input()) a = [] while T: a.append(T % 6) T //= 6 L = len(a) n = m = L * 2 + 2 ans = [(1, 2, 2, 2), (2, 1, 2, 2)] f = [[1] * 9 for i in range(7)] f[1][2] = f[2][2] = f[2][6] = f[3][5] = 0 f[4][5] = f[4][6] = f[5][2] = f[5][5] = f[5][6] = 0 p = [0] * 9 p[1] = 3, 1, 3, 2 p[2] = 4, 1, 4, 2 p[3] = 4, 2, 5, 2 p[4] = 4, 3, 5, 3 p[5] = 1, 3, 2, 3 p[6] = 1, 4, 2, 4 p[7] = 2, 4, 2, 5 p[8] = 3, 4, 3, 5 for i in range(L): bit = a[L - i - 1] for j in range(1, 9): if not f[bit][j]: continue x1, y1, x2, y2 = p[j]; D = 2 * i x1 += D; y1 += D; x2 += D; y2 += D if corr(x2, y2): ans.append((x1, y1, x2, y2)) for i in range(L - 1): x1, y1 = 5 + i * 2, 1 + i * 2 x2, y2 = 1 + i * 2, 5 + i * 2 ans.append((x1, y1, x1 + 1, y1)) ans.append((x1, y1 + 1, x1 + 1, y1 + 1)) ans.append((x2, y2, x2, y2 + 1)) ans.append((x2 + 1, y2, x2 + 1, y2 + 1)) print(n, m) print(len(ans)) [print(*i) for i in ans]
train
APPS_structured
Americans are odd people: in their buildings, the first floor is actually the ground floor and there is no 13th floor (due to superstition). Write a function that given a floor in the american system returns the floor in the european system. With the 1st floor being replaced by the ground floor and the 13th floor being removed, the numbers move down to take their place. In case of above 13, they move down by two because there are two omitted numbers below them. Basements (negatives) stay the same as the universal level. [More information here](https://en.wikipedia.org/wiki/Storey#European_scheme) ## Examples ``` 1 => 0 0 => 0 5 => 4 15 => 13 -3 => -3 ```
def get_real_floor(n): if 0 < n < 14: return n - 1 if 13 < n: return n - 2 else: return n
def get_real_floor(n): if 0 < n < 14: return n - 1 if 13 < n: return n - 2 else: return n
train
APPS_structured
Alex and Lee play a game with piles of stones.  There are an even number of piles arranged in a row, and each pile has a positive integer number of stones piles[i]. The objective of the game is to end with the most stones.  The total number of stones is odd, so there are no ties. Alex and Lee take turns, with Alex starting first.  Each turn, a player takes the entire pile of stones from either the beginning or the end of the row.  This continues until there are no more piles left, at which point the person with the most stones wins. Assuming Alex and Lee play optimally, return True if and only if Alex wins the game. Example 1: Input: piles = [5,3,4,5] Output: true Explanation: Alex starts first, and can only take the first 5 or the last 5. Say he takes the first 5, so that the row becomes [3, 4, 5]. If Lee takes 3, then the board is [4, 5], and Alex takes 5 to win with 10 points. If Lee takes the last 5, then the board is [3, 4], and Alex takes 4 to win with 9 points. This demonstrated that taking the first 5 was a winning move for Alex, so we return true. Constraints: 2 <= piles.length <= 500 piles.length is even. 1 <= piles[i] <= 500 sum(piles) is odd.
class Solution: # @lru_cache(None) def stoneGame(self, piles: List[int]) -> bool: result = dict() @lru_cache(None) def Alex(start, end) -> int: if start == end: return piles[start] # if (start, end) in result: # return result[(start, end)] else: # result[(start, end)] = max(Lee(start + 1, end) + piles[start], Lee(start, end - 1) + piles[end]) return max(Lee(start + 1, end) + piles[start], Lee(start, end - 1) + piles[end]) # return result[(start, end)] def Lee(start, end) -> int: if start == end: return 0 # if (start, end) in result: # return result[(start, end)] else: # result[(start, end)] = min(Alex(start + 1, end), Alex(start, end - 1)) return min(Alex(start + 1, end), Alex(start, end - 1)) # return result[(start, end)] Alex(0, len(piles) - 1) summ = sum(piles) # print(result[(0, len(piles - 1))]) # print(summ) return Alex(0, len(piles) - 1) > (summ - Alex(0, len(piles) - 1))
class Solution: # @lru_cache(None) def stoneGame(self, piles: List[int]) -> bool: result = dict() @lru_cache(None) def Alex(start, end) -> int: if start == end: return piles[start] # if (start, end) in result: # return result[(start, end)] else: # result[(start, end)] = max(Lee(start + 1, end) + piles[start], Lee(start, end - 1) + piles[end]) return max(Lee(start + 1, end) + piles[start], Lee(start, end - 1) + piles[end]) # return result[(start, end)] def Lee(start, end) -> int: if start == end: return 0 # if (start, end) in result: # return result[(start, end)] else: # result[(start, end)] = min(Alex(start + 1, end), Alex(start, end - 1)) return min(Alex(start + 1, end), Alex(start, end - 1)) # return result[(start, end)] Alex(0, len(piles) - 1) summ = sum(piles) # print(result[(0, len(piles - 1))]) # print(summ) return Alex(0, len(piles) - 1) > (summ - Alex(0, len(piles) - 1))
train
APPS_structured
=====Problem Statement===== ABC is a right triangle, 90°, at B. Therefore, ANGLE{ABC} = 90°. Point M is the midpoint of hypotenuse AC. You are given the lengths AB and BC. Your task is to find ANGLE{MBC} (angle θ°, as shown in the figure) in degrees. =====Input Format===== The first contains the length of side AB. The second line contains the length of side BC. =====Constraints===== 0<AB≤100 0<BC≤100 Lengths AB and BC are natural numbers. =====Output Format===== Output ANGLE{MBC} in degrees. Note: Round the angle to the nearest integer. Examples: If angle is 56.5000001°, then output 57°. If angle is 56.5000000°, then output 57°. If angle is 56.4999999°, then output 56°.
import math ab = float(input()) bc = float(input()) ac = math.sqrt((ab*ab)+(bc*bc)) bm = ac / 2.0 mc = bm #let, b = mc c = bm a = bc #where b=c angel_b_radian = math.acos(a / (2*b)) angel_b_degree = int(round((180 * angel_b_radian) / math.pi)) output_str = str(angel_b_degree)+'°' print(output_str)
import math ab = float(input()) bc = float(input()) ac = math.sqrt((ab*ab)+(bc*bc)) bm = ac / 2.0 mc = bm #let, b = mc c = bm a = bc #where b=c angel_b_radian = math.acos(a / (2*b)) angel_b_degree = int(round((180 * angel_b_radian) / math.pi)) output_str = str(angel_b_degree)+'°' print(output_str)
train
APPS_structured
A robot on an infinite grid starts at point (0, 0) and faces north.  The robot can receive one of three possible types of commands: -2: turn left 90 degrees -1: turn right 90 degrees 1 <= x <= 9: move forward x units Some of the grid squares are obstacles.  The i-th obstacle is at grid point (obstacles[i][0], obstacles[i][1]) If the robot would try to move onto them, the robot stays on the previous grid square instead (but still continues following the rest of the route.) Return the square of the maximum Euclidean distance that the robot will be from the origin. Example 1: Input: commands = [4,-1,3], obstacles = [] Output: 25 Explanation: robot will go to (3, 4) Example 2: Input: commands = [4,-1,4,-2,4], obstacles = [[2,4]] Output: 65 Explanation: robot will be stuck at (1, 4) before turning left and going to (1, 8) Note: 0 <= commands.length <= 10000 0 <= obstacles.length <= 10000 -30000 <= obstacle[i][0] <= 30000 -30000 <= obstacle[i][1] <= 30000 The answer is guaranteed to be less than 2 ^ 31.
class Solution: def robotSim(self, commands: List[int], obstacles: List[List[int]]) -> int: i = j = mx = d = 0 move, obstacles = [(0, 1), (-1, 0), (0, -1), (1, 0), ], set(map(tuple, obstacles)) for command in commands: if command == -2: d = (d + 1) % 4 elif command == -1: d = (d - 1) % 4 else: x, y = move[d] while command and (i + x, j + y) not in obstacles: i += x j += y command -= 1 mx = max(mx, i ** 2 + j ** 2) return mx
class Solution: def robotSim(self, commands: List[int], obstacles: List[List[int]]) -> int: i = j = mx = d = 0 move, obstacles = [(0, 1), (-1, 0), (0, -1), (1, 0), ], set(map(tuple, obstacles)) for command in commands: if command == -2: d = (d + 1) % 4 elif command == -1: d = (d - 1) % 4 else: x, y = move[d] while command and (i + x, j + y) not in obstacles: i += x j += y command -= 1 mx = max(mx, i ** 2 + j ** 2) return mx
train
APPS_structured
Emily and Mia are friends. Emily got Mia’s essay paper, but since she is a prankster, she decided to meddle with the words present in the paper. She changes all the words in the paper into palindromes. To do this, she follows two rules: - In one operation she can only reduce the value of an alphabet by 1, i.e. she can change ‘d’ to ‘c’, but she cannot change ‘c’ to ‘d’ or ‘d’ to ‘b’. - The alphabet ‘a’ will not be reduced any further. Each reduction in the value of any alphabet is counted as a single operation. Find the minimum number of operations required to convert a given string into a palindrome. -----Input:----- - The first line contains an integer $T$, denoting the number of test cases. - Each test case consists of a string $S$ containing only lowercase characters with no spaces. -----Output:----- For each test case on a new line, print the minimum number of operations for the corresponding test case. -----Constraints----- - $1<=T<=10$ - $1<=|S|<=10^7$, where $|S|$ denotes length of string S. -----Sample Input:----- 4 abc abcba abcd cba -----Sample Output:----- 2 0 4 2 -----EXPLANATION:----- For the first test case string = “abc” c->b->a so the string become “aba” which is a palindrome. For this we perform 2 operations
t = int(input()) lst = ["0","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"] for i in range(t): s = list(input().strip()) count=0 s.insert(0,"temp") for i in range(1,len(s)): #print(s[-i]) if i > len(s)//2 : break if s[i] != s[-i] : count+=abs(lst.index(s[i])-lst.index(s[-i])) print(count)
t = int(input()) lst = ["0","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"] for i in range(t): s = list(input().strip()) count=0 s.insert(0,"temp") for i in range(1,len(s)): #print(s[-i]) if i > len(s)//2 : break if s[i] != s[-i] : count+=abs(lst.index(s[i])-lst.index(s[-i])) print(count)
train
APPS_structured
Given a list of words, each word consists of English lowercase letters. Let's say word1 is a predecessor of word2 if and only if we can add exactly one letter anywhere in word1 to make it equal to word2.  For example, "abc" is a predecessor of "abac". A word chain is a sequence of words [word_1, word_2, ..., word_k] with k >= 1, where word_1 is a predecessor of word_2, word_2 is a predecessor of word_3, and so on. Return the longest possible length of a word chain with words chosen from the given list of words. Example 1: Input: ["a","b","ba","bca","bda","bdca"] Output: 4 Explanation: one of the longest word chain is "a","ba","bda","bdca". Note: 1 <= words.length <= 1000 1 <= words[i].length <= 16 words[i] only consists of English lowercase letters.
class Solution: def longestStrChain(self, words: List[str]) -> int: words.sort(key=len) n = len(words) dp = [1] * n for i in range(n): for j in reversed(list(range(i))): if len(words[i]) == len(words[j]): continue elif len(words[i]) > len(words[j]) + 1: break if self.helper(words[j], words[i]): dp[i] = max(dp[i], dp[j] + 1) return max(dp) def helper(self, w1, w2): # check if w1 is a predecessor of w2 i = 0 while i < len(w1) and w1[i] == w2[i]: i += 1 while i < len(w1) and w1[i] == w2[i + 1]: i += 1 return i == len(w1)
class Solution: def longestStrChain(self, words: List[str]) -> int: words.sort(key=len) n = len(words) dp = [1] * n for i in range(n): for j in reversed(list(range(i))): if len(words[i]) == len(words[j]): continue elif len(words[i]) > len(words[j]) + 1: break if self.helper(words[j], words[i]): dp[i] = max(dp[i], dp[j] + 1) return max(dp) def helper(self, w1, w2): # check if w1 is a predecessor of w2 i = 0 while i < len(w1) and w1[i] == w2[i]: i += 1 while i < len(w1) and w1[i] == w2[i + 1]: i += 1 return i == len(w1)
train
APPS_structured
Bears love candies and games involving eating them. Limak and Bob play the following game. Limak eats 1 candy, then Bob eats 2 candies, then Limak eats 3 candies, then Bob eats 4 candies, and so on. Once someone can't eat what he is supposed to eat, he loses. Limak can eat at most A candies in total (otherwise he would become sick), while Bob can eat at most B candies in total. Who will win the game? Print "Limak" or "Bob" accordingly. -----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 only line of each test case contains two integers A and B denoting the maximum possible number of candies Limak can eat and the maximum possible number of candies Bob can eat respectively. -----Output----- For each test case, output a single line containing one string — the name of the winner ("Limak" or "Bob" without the quotes). -----Constraints----- - 1 ≤ T ≤ 1000 - 1 ≤ A, B ≤ 1000 -----Example----- Input: 10 3 2 4 2 1 1 1 2 1 3 9 3 9 11 9 12 9 1000 8 11 Output: Bob Limak Limak Bob Bob Limak Limak Bob Bob Bob -----Explanation----- Test case 1. We have A = 3 and B = 2. Limak eats 1 candy first, and then Bob eats 2 candies. Then Limak is supposed to eat 3 candies but that would mean 1 + 3 = 4 candies in total. It's impossible because he can eat at most A candies, so he loses. Bob wins, and so we print "Bob". Test case 2. Now we have A = 4 and B = 2. Limak eats 1 candy first, and then Bob eats 2 candies, then Limak eats 3 candies (he has 1 + 3 = 4 candies in total, which is allowed because it doesn't exceed A). Now Bob should eat 4 candies but he can't eat even a single one (he already ate 2 candies). Bob loses and Limak is the winner. Test case 8. We have A = 9 and B = 12. The game looks as follows: - Limak eats 1 candy. - Bob eats 2 candies. - Limak eats 3 candies (4 in total). - Bob eats 4 candies (6 in total). - Limak eats 5 candies (9 in total). - Bob eats 6 candies (12 in total). - Limak is supposed to eat 7 candies but he can't — that would exceed A. Bob wins.
# cook your dish here t=int(input()) for j in range(t): l,b=list(map(int,input().split())) c=0 i=1 while l>-1 and b>-1: if c==0: l=l-i i=i+1 c=1 else: b=b-i i=i+1 c=0 if l<0: print("Bob") else: print("Limak")
# cook your dish here t=int(input()) for j in range(t): l,b=list(map(int,input().split())) c=0 i=1 while l>-1 and b>-1: if c==0: l=l-i i=i+1 c=1 else: b=b-i i=i+1 c=0 if l<0: print("Bob") else: print("Limak")
train
APPS_structured
Given an array of integers nums and a positive integer k, find whether it's possible to divide this array into k non-empty subsets whose sums are all equal. Example 1: Input: nums = [4, 3, 2, 3, 5, 2, 1], k = 4 Output: True Explanation: It's possible to divide it into 4 subsets (5), (1, 4), (2,3), (2,3) with equal sums. Note: 1 . 0 < nums[i] < 10000.
class Solution: def canPartitionKSubsets(self, nums, k): """ :type nums: List[int] :type k: int :rtype: bool """ total = sum(nums) if total % k != 0: return False subsetTotal = total // k visited = [0] * len(nums) return self.helper(k, 0, 0, visited, nums, k, subsetTotal) def helper(self, remainingSets, index, s, visited, nums, k, subsetTotal): if remainingSets == 1: return True if s == subsetTotal: return self.helper(remainingSets - 1, 0, 0, visited, nums, k, subsetTotal) for i in range(index, len(nums)): if visited[i] == 0 and s + nums[i] <= subsetTotal: visited[i] = 1 if self.helper(remainingSets, i + 1, s + nums[i], visited, nums, k, subsetTotal): return True visited[i] = 0 return False
class Solution: def canPartitionKSubsets(self, nums, k): """ :type nums: List[int] :type k: int :rtype: bool """ total = sum(nums) if total % k != 0: return False subsetTotal = total // k visited = [0] * len(nums) return self.helper(k, 0, 0, visited, nums, k, subsetTotal) def helper(self, remainingSets, index, s, visited, nums, k, subsetTotal): if remainingSets == 1: return True if s == subsetTotal: return self.helper(remainingSets - 1, 0, 0, visited, nums, k, subsetTotal) for i in range(index, len(nums)): if visited[i] == 0 and s + nums[i] <= subsetTotal: visited[i] = 1 if self.helper(remainingSets, i + 1, s + nums[i], visited, nums, k, subsetTotal): return True visited[i] = 0 return False
train
APPS_structured
We have the number ```12385```. We want to know the value of the closest cube but higher than 12385. The answer will be ```13824```. Now, another case. We have the number ```1245678```. We want to know the 5th power, closest and higher than that number. The value will be ```1419857```. We need a function ```find_next_power``` ( ```findNextPower``` in JavaScript, CoffeeScript and Haskell), that receives two arguments, a value ```val```, and the exponent of the power,``` pow_```, and outputs the value that we want to find. Let'see some cases: ```python find_next_power(12385, 3) == 13824 find_next_power(1245678, 5) == 1419857 ``` The value, ```val``` will be always a positive integer. The power, ```pow_```, always higher than ```1```. Happy coding!!
find_next_power=lambda n,p:int(n**(1./p)+1)**p
find_next_power=lambda n,p:int(n**(1./p)+1)**p
train
APPS_structured