# Datasets: allenai /lila

Modalities:
Text
Libraries:
Datasets
input
stringlengths
50
13.9k
output_program
stringlengths
5
655k
stringlengths
5
655k
split
stringclasses
1 value
dataset
stringclasses
1 value
Shivam is the youngest programmer in the world, he is just 12 years old. Shivam is learning programming and today he is writing his first program. Program is very simple, Given two integers A and B, write a program to add these two numbers. -----Input----- The first line contains an integer T, the total number of test cases. Then follow T lines, each line contains two Integers A and B. -----Output----- For each test case, add A and B and display it in a new line. -----Constraints----- - 1 ≤ T ≤ 1000 - 0 ≤ A,B ≤ 10000 -----Example----- Input 3 1 2 100 200 10 40 Output 3 300 50
L = [] l = [] x = int(input()) for i in range(x): y = input() z = y.split() a = z[0] b = z[1] L.append(a) l.append(b) for j in range(x): c = int(L[j])+ int(l[j]) print(c)
L = [] l = [] x = int(input()) for i in range(x): y = input() z = y.split() a = z[0] b = z[1] L.append(a) l.append(b) for j in range(x): c = int(L[j])+ int(l[j]) print(c)
train
APPS_structured
Back in 2015, Usain Bolt announced that he'll be retiring after the 2017 World Championship. Though his final season did not end gloriously, we all know that he is a true legend and we witnessed his peak during 2008 - 2013. Post retirement, Usain Bolt is still leading an adventurous life. He's exploring the unexplored parts of the globe. But sometimes he gets bored, and reads questions asked about him on Quora. One such question he read was, "Who would win a race between Usain Bolt and a tiger if the race is on a straight line track and the tiger is $distancetoBolt$ meters behind Bolt? The finishing point is $finish$ meters away from Bolt's starting position. The tiger starts with an initial speed of $0$ $meter/second$, and will accelerate itself with $tigerAccelaration$ $m/s^2$. Bolt can run with a constant speed of $boltSpeed$ $m/s$ from start to finish. Given these values, find out who will win the race - Bolt or the tiger? " Note that Bolt will win the race if and only if he touches the finishing line before the tiger touches it. If both of them finish together, the tiger is announced as the winner since Bolt was given an initial advantage. See the figure below for more clarity. Since Bolt was busy practicing in the tracks during his Physics school classes, he is asking for your help to solve the question. Can you please help him? He just remembers two formulae from the class, and thinks that they will be useful to you: $Displacement (S)$ = $ut$ +$(1/2)at^2$ where $u$ is the initial velocity , #is the acceleration and $t$ is the time taken. $Velocity$ = $Displacement /Time$ -----Input:----- - The first line will contain $T$, the number of testcases. Then the description of each test case follow. - Each test case contains 4 integers $finish, distancetoBolt, tigerAccelaration, boltSpeed$. -----Output:----- For each testcase, output in a single line, the word "Bolt" or "Tiger" without quotes, depending on whether Bolt wins or the tiger wins. -----Constraints----- - $1 \leq T \leq 100000$ - $1 \leq finish\leq 10^5$ - $1 \leq distancetoBolt\leq 10^5$ - $1 \leq tigerAccelaration\leq 10^5$ - $1 \leq boltSpeed\leq 10^5$ -----Sample Input:----- 2 10 100 10 10 100 10 5 10 -----Sample Output:----- Bolt Tiger
import math def func(): t=int(input()) for _ in range(t): fn,dst,ta,bs = map(int,input().split(' ')) t1=fn/bs t2=math.sqrt(2*(fn+dst)/ta) if t1<t2: print("Bolt") else: print("Tiger") func()
import math def func(): t=int(input()) for _ in range(t): fn,dst,ta,bs = map(int,input().split(' ')) t1=fn/bs t2=math.sqrt(2*(fn+dst)/ta) if t1<t2: print("Bolt") else: print("Tiger") func()
train
APPS_structured
Given a binary tree, determine if it is a valid binary search tree (BST). Assume a BST is defined as follows: The left subtree of a node contains only nodes with keys less than the node's key. The right subtree of a node contains only nodes with keys greater than the node's key. Both the left and right subtrees must also be binary search trees. Example 1: Input: 2 / \ 1 3 Output: true Example 2: 5 / \ 1 4   / \   3 6 Output: false Explanation: The input is: [5,1,4,null,null,3,6]. The root node's value   is 5 but its right child's value is 4.
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def isValidBST(self, root): """ :type root: TreeNode :rtype: bool """ stack = [] pre = None while stack or root: while root: stack.append(root) root = root.left root = stack.pop() if pre and root.val <= pre.val: return False pre = root root = root.right return True
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def isValidBST(self, root): """ :type root: TreeNode :rtype: bool """ stack = [] pre = None while stack or root: while root: stack.append(root) root = root.left root = stack.pop() if pre and root.val <= pre.val: return False pre = root root = root.right return True
train
APPS_structured
In a given integer array A, we must move every element of A to either list B or list C. (B and C initially start empty.) Return true if and only if after such a move, it is possible that the average value of B is equal to the average value of C, and B and C are both non-empty. Example : Input: [1,2,3,4,5,6,7,8] Output: true Explanation: We can split the array into [1,4,5,8] and [2,3,6,7], and both of them have the average of 4.5. Note: The length of A will be in the range [1, 30]. A[i] will be in the range of [0, 10000].
from functools import lru_cache class Solution: def splitArraySameAverage(self, A: List[int]) -> bool: # TLE # avg = sum(A) / len(A) # for k in range(1, len(A) // 2 + 1): # for comb in combinations(A, k): # if abs(sum(comb) / k - avg) < 1e-5: # return True # return False N, S = len(A), sum(A) @lru_cache(None) def combinationSum(target, start, k): if target == 0: return k == 0 if start == N or k < 0 or target < 0: return False return combinationSum(target-A[start], start+1, k-1) or combinationSum(target, start+1, k) for k in range(1, N // 2 + 1): if S * k % N == 0: if combinationSum(S * k // N, 0, k): return True return False
from functools import lru_cache class Solution: def splitArraySameAverage(self, A: List[int]) -> bool: # TLE # avg = sum(A) / len(A) # for k in range(1, len(A) // 2 + 1): # for comb in combinations(A, k): # if abs(sum(comb) / k - avg) < 1e-5: # return True # return False N, S = len(A), sum(A) @lru_cache(None) def combinationSum(target, start, k): if target == 0: return k == 0 if start == N or k < 0 or target < 0: return False return combinationSum(target-A[start], start+1, k-1) or combinationSum(target, start+1, k) for k in range(1, N // 2 + 1): if S * k % N == 0: if combinationSum(S * k // N, 0, k): return True return False
train
APPS_structured
If we write out the digits of "60" as English words we get "sixzero"; the number of letters in "sixzero" is seven. The number of letters in "seven" is five. The number of letters in "five" is four. The number of letters in "four" is four: we have reached a stable equilibrium. Note: for integers larger than 9, write out the names of each digit in a single word (instead of the proper name of the number in English). For example, write 12 as "onetwo" (instead of twelve), and 999 as "nineninenine" (instead of nine hundred and ninety-nine). For any integer between 0 and 999, return an array showing the path from that integer to a stable equilibrium:
t = {'1': 'one', '2': 'two', '3': 'three', '4': 'four', '5': 'five', '6': 'six', '7': 'seven', '8': 'eight', '9': 'nine', '0': 'zero'} def numbers_of_letters(n): x = [''.join([t[i] for i in str(n)])] while int(n) != len(x[-1]): n = len(x[-1]) x.append(''.join([t[i] for i in str(n)])) return x
t = {'1': 'one', '2': 'two', '3': 'three', '4': 'four', '5': 'five', '6': 'six', '7': 'seven', '8': 'eight', '9': 'nine', '0': 'zero'} def numbers_of_letters(n): x = [''.join([t[i] for i in str(n)])] while int(n) != len(x[-1]): n = len(x[-1]) x.append(''.join([t[i] for i in str(n)])) return x
train
APPS_structured
# Task A lock has n buttons in it, numbered from 1 to n. To open the lock, you have to press all buttons in some order, i.e. a key to the lock is a permutation of the first n integers. If you push the right button in the right order, it will be pressed into the lock. Otherwise all pressed buttons will pop out. When all buttons are pressed into the lock, it opens. Your task is to calculate the number of times you've got to push buttons in order to open the lock in the worst-case scenario. # Example For n = 3, the result should be 7.  Let's assume the right order is 3-2-1. In the worst-case scenario, we press the buttons: Press 1, wrong, button 1 pop out Press 2, wrong, button 2 pop out Press 3, right, button 3 pressed in Press 1, wrong, button 1,3 pop out Press 3, right, button 3 pressed in Press 2, right, button 2 pressed in Press 1, right, button 1 pressed in We pressed button total 7 times. For n = 4, the result should be 14.  Let's assume the right order is 4-3-2-1. In the worst-case scenario, we press the buttons: Press 1, wrong, button 1 pop out Press 2, wrong, button 2 pop out Press 3, wrong, button 3 pop out Press 4, right, button 4 pressed in Press 1, wrong, button 1,4 pop out Press 4, right, button 4 pressed in Press 2, wrong, button 2,4 pop out Press 4, right, button 4 pressed in Press 3, right, button 3 pressed in Press 1, wrong, button 1,3,4 pop out Press 4, right, button 4 pressed in Press 3, right, button 3 pressed in Press 2, right, button 2 pressed in Press 1, right, button 1 pressed in We pressed button total 14 times. # Input/Output - [input] integer n The number of buttons in the lock. 0 < n ≤ 2000 - [output] an integer The number of times you've got to push buttons in the worst-case scenario.
def press_button(n): return n*(n**2 + 5)/6
def press_button(n): return n*(n**2 + 5)/6
train
APPS_structured
# Description: Find the longest successive exclamation marks and question marks combination in the string. A successive exclamation marks and question marks combination must contains two part: a substring of "!" and a substring "?", they are adjacent. If more than one result are found, return the one which at left side; If no such a combination found, return "". # Examples  find("!!") === "" find("!??") === "!??" find("!?!!") === "?!!" find("!!???!????") === "!!???" find("!!???!?????") === "!?????" find("!????!!!?") === "????!!!" find("!?!!??!!!?") === "??!!!"  # Note Please don't post issue about difficulty or duplicate. Because: >[That's unfair on the kata creator. This is a valid kata and introduces new people to javascript some regex or loops, depending on how they tackle this problem. --matt c](https://www.codewars.com/kata/remove-exclamation-marks/discuss#57fabb625c9910c73000024e)
def find(s): if s == '' or '!' not in s or '?' not in s: return '' s += ' ' counts = [] curr = s[0] count = 0 for i in s: if i == curr: count += 1 else: counts.append(count) count = 1 curr = i n = [] for i in range(len(counts)-1): n.append(counts[i]+counts[i+1]) x = n.index(max(n)) a = sum(counts[:x]) return s[a:a+counts[x]+counts[x+1]]
def find(s): if s == '' or '!' not in s or '?' not in s: return '' s += ' ' counts = [] curr = s[0] count = 0 for i in s: if i == curr: count += 1 else: counts.append(count) count = 1 curr = i n = [] for i in range(len(counts)-1): n.append(counts[i]+counts[i+1]) x = n.index(max(n)) a = sum(counts[:x]) return s[a:a+counts[x]+counts[x+1]]
train
APPS_structured
Pirates have notorious difficulty with enunciating. They tend to blur all the letters together and scream at people. At long last, we need a way to unscramble what these pirates are saying. Write a function that will accept a jumble of letters as well as a dictionary, and output a list of words that the pirate might have meant. For example:  grabscrab( "ortsp", ["sport", "parrot", "ports", "matey"] )  Should return ["sport", "ports"]. Return matches in the same order as in the dictionary. Return an empty array if there are no matches. Good luck!
def grabscrab(w, pw): return [i for i in pw if all(w.count(j)==i.count(j) for j in w)]
def grabscrab(w, pw): return [i for i in pw if all(w.count(j)==i.count(j) for j in w)]
train
APPS_structured
Your task is to return how many times a string contains a given character. The function takes a string(inputS) as a paremeter and a char(charS) which is the character that you will have to find and count. For example, if you get an input string "Hello world" and the character to find is "o", return 2.
def string_counter(string, char): return string.count(char)
def string_counter(string, char): return string.count(char)
train
APPS_structured
We have a sandglass consisting of two bulbs, bulb A and bulb B. These bulbs contain some amount of sand. When we put the sandglass, either bulb A or B lies on top of the other and becomes the upper bulb. The other bulb becomes the lower bulb. The sand drops from the upper bulb to the lower bulb at a rate of 1 gram per second. When the upper bulb no longer contains any sand, nothing happens. Initially at time 0, bulb A is the upper bulb and contains a grams of sand; bulb B contains X-a grams of sand (for a total of X grams). We will turn over the sandglass at time r_1,r_2,..,r_K. Assume that this is an instantaneous action and takes no time. Here, time t refer to the time t seconds after time 0. You are given Q queries. Each query is in the form of (t_i,a_i). For each query, assume that a=a_i and find the amount of sand that would be contained in bulb A at time t_i. -----Constraints----- - 1≤X≤10^9 - 1≤K≤10^5 - 1≤r_1<r_2< .. <r_K≤10^9 - 1≤Q≤10^5 - 0≤t_1<t_2< .. <t_Q≤10^9 - 0≤a_i≤X (1≤i≤Q) - All input values are integers. -----Input----- The input is given from Standard Input in the following format: X K r_1 r_2 .. r_K Q t_1 a_1 t_2 a_2 : t_Q a_Q -----Output----- For each query, print the answer in its own line. -----Sample Input----- 180 3 60 120 180 3 30 90 61 1 180 180 -----Sample Output----- 60 1 120 In the first query, 30 out of the initial 90 grams of sand will drop from bulb A, resulting in 60 grams. In the second query, the initial 1 gram of sand will drop from bulb A, and nothing will happen for the next 59 seconds. Then, we will turn over the sandglass, and 1 second after this, bulb A contains 1 gram of sand at the time in question.
def main(): import sys from operator import itemgetter input = sys.stdin.readline X = int(input()) K = int(input()) R = list(map(int, input().split())) Q = [] for r in R: Q.append((r, -1)) q = int(input()) for _ in range(q): t, a = list(map(int, input().split())) Q.append((t, a)) Q.sort(key=itemgetter(0)) #print(Q) prev = 0 m = 0 M = X flg = -1 R_cs = 0 for t, a in Q: if a < 0: r = t - prev R_cs -= r * flg if flg == -1: m = max(0, m-r) M = max(0, M-r) flg = 1 else: m = min(X, m+r) M = min(X, M+r) flg = -1 prev = t else: if m == M: if flg == 1: print((min(X, m + t - prev))) else: print((max(0, m - t + prev))) else: am = m + R_cs aM = M + R_cs #print('am', am, 'aM', aM, m, M) if a <= am: if flg == 1: print((min(X, m + t - prev))) else: print((max(0, m - t + prev))) elif a >= aM: if flg == 1: print((min(X, M + t - prev))) else: print((max(0, M - t + prev))) else: if flg == 1: print((min(X, m + (a - am) + t - prev))) else: print((max(0, m + (a - am) - t + prev))) def __starting_point(): main() __starting_point()
def main(): import sys from operator import itemgetter input = sys.stdin.readline X = int(input()) K = int(input()) R = list(map(int, input().split())) Q = [] for r in R: Q.append((r, -1)) q = int(input()) for _ in range(q): t, a = list(map(int, input().split())) Q.append((t, a)) Q.sort(key=itemgetter(0)) #print(Q) prev = 0 m = 0 M = X flg = -1 R_cs = 0 for t, a in Q: if a < 0: r = t - prev R_cs -= r * flg if flg == -1: m = max(0, m-r) M = max(0, M-r) flg = 1 else: m = min(X, m+r) M = min(X, M+r) flg = -1 prev = t else: if m == M: if flg == 1: print((min(X, m + t - prev))) else: print((max(0, m - t + prev))) else: am = m + R_cs aM = M + R_cs #print('am', am, 'aM', aM, m, M) if a <= am: if flg == 1: print((min(X, m + t - prev))) else: print((max(0, m - t + prev))) elif a >= aM: if flg == 1: print((min(X, M + t - prev))) else: print((max(0, M - t + prev))) else: if flg == 1: print((min(X, m + (a - am) + t - prev))) else: print((max(0, m + (a - am) - t + prev))) def __starting_point(): main() __starting_point()
train
APPS_structured
In this kata you will be given an **integer n**, which is the number of times that is thown a coin. You will have to return an array of string for all the possibilities (heads[H] and tails[T]). Examples: coin(1) should return {"H", "T"} coin(2) should return {"HH", "HT", "TH", "TT"} coin(3) should return {"HHH", "HHT", "HTH", "HTT", "THH", "THT", "TTH", "TTT"} When finished sort them alphabetically. In C and C++ just return a char* with all elements separated by, (without space): coin(2) should return "HH,HT,TH,TT" INPUT: 0 < n < 18 Careful with performance!! You'll have to pass 3 basic test (n = 1, n = 2, n = 3), many medium tests (3 < n <= 10) and many large tests (10 < n < 18)
from itertools import product def coin(n): return list(map(''.join, product('HT', repeat=n)))
from itertools import product def coin(n): return list(map(''.join, product('HT', repeat=n)))
train
APPS_structured
-----Problem----- Suppose there is a circle. There are N Juice shops on that circle. Juice shops are numbered 0 to N-1 (both inclusive). You have two pieces of information corresponding to each of the juice shop: (1) the amount of Juice that a particular Juice shop can provide and (2) the distance from that juice shop to the next juice shop. Initially, there is a man with a bottle of infinite capacity carrying no juice. He can start the tour at any of the juice shops. Calculate the first point from where the man will be able to complete the circle. Consider that the man will stop at every Juice Shop. The man will move one kilometer for each litre of the juice. -----Input----- - The first line will contain the value of N. - The next N lines will contain a pair of integers each, i.e. the amount of juice that a juice shop can provide(in litres) and the distance between that juice shop and the next juice shop. -----Output----- An integer which will be the smallest index of the juice shop from which he can start the tour. -----Constraints----- - 1 ≤ N ≤ 105 - 1 ≤ amt of juice, distance ≤ 109 -----Sample Input----- 3 1 5 10 3 3 4 -----Sample Output----- 1 -----Explanation----- He can start the tour from the SECOND Juice shop. p { text-align:justify }
a = 0 ans = None for t in range(int(input())): j, d = list(map(int,input().split())) a+=j a-=d if (ans is None): ans = t if (a <= 0): a = 0 ans = None if (ans is None): print(0) else: print(ans)
a = 0 ans = None for t in range(int(input())): j, d = list(map(int,input().split())) a+=j a-=d if (ans is None): ans = t if (a <= 0): a = 0 ans = None if (ans is None): print(0) else: print(ans)
train
APPS_structured
You are given an $array$ of size $N$ and an integer $K$ ( $N > 1 , K > 0$ ). Each element in the array can be incremented by $K$ or decremented by $K$ $at$ $most$ $once$. So there will be $3^n$ possible combinations of final array. (As there are 3 options for every element). Out of these combinations, you have to select a combination, in which the $absolute$ difference between the largest and the smallest element is $maximum$. You have to print the $maximum$ $absolute$ $difference$. -----Input:----- - First line will contain $T$, number of testcases. Then the testcases follow. - Each testcase contains of a two lines of input - First line contains two integers $N, K$. - Second line contains $N$ space separated integers. -----Output:----- For each testcase, output the maximum absolute difference that can be achieved on a new line. -----Constraints----- - $1 \leq T \leq 10$ - $2 \leq N \leq 1000$ - $1 \leq K , arr[i] \leq 10000$ $NOTE$: Large input files, Use of fastio is recommended. -----Sample Input:----- 2 4 3 4 2 5 1 3 5 2 5 3 -----Sample Output:----- 10 13
# cook your dish here try: for _ in range(int(input())): n,k=map(int,input().split()) li=list(map(int,input().split())) a=max(li) b=min(li) c=a+k d=b-k print(c-d) except: pass
# cook your dish here try: for _ in range(int(input())): n,k=map(int,input().split()) li=list(map(int,input().split())) a=max(li) b=min(li) c=a+k d=b-k print(c-d) except: pass
train
APPS_structured
=====Problem Statement===== ABCXYZ company has up to 100 employees. The company decides to create a unique identification number (UID) for each of its employees. The company has assigned you the task of validating all the randomly generated UIDs. A valid UID must follow the rules below: It must contain at least 2 uppercase English alphabet characters. It must contain at least 3 digits (0-9). It should only contain alphanumeric characters (a-z, A-Z & 0-9). No character should repeat. There must be exactly 10 characters in a valid UID. =====Input Format===== The first line contains an integer T, the number of test cases. The next T lines contains an employee's UID. =====Output Format===== For each test case, print 'Valid' if the UID is valid. Otherwise, print 'Invalid', on separate lines. Do not print the quotation marks.
import re def __starting_point(): t = int(input().strip()) for _ in range(t): uid = "".join(sorted(input())) if (len(uid) == 10 and re.match(r'', uid) and re.search(r'[A-Z]{2}', uid) and re.search(r'\d\d\d', uid) and not re.search(r'[^a-zA-Z0-9]', uid) and not re.search(r'(.)\1', uid)): print("Valid") else: print("Invalid") __starting_point()
import re def __starting_point(): t = int(input().strip()) for _ in range(t): uid = "".join(sorted(input())) if (len(uid) == 10 and re.match(r'', uid) and re.search(r'[A-Z]{2}', uid) and re.search(r'\d\d\d', uid) and not re.search(r'[^a-zA-Z0-9]', uid) and not re.search(r'(.)\1', uid)): print("Valid") else: print("Invalid") __starting_point()
train
APPS_structured
You have a collection of lovely poems. Unfortuantely they aren't formatted very well. They're all on one line, like this:  Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Complex is better than complicated.  What you want is to present each sentence on a new line, so that it looks like this:  Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Complex is better than complicated.  Write a function, format_poem() that takes a string like the one line example as an argument and returns a new string that is formatted across multiple lines with each new sentence starting on a new line when you print it out. Try to solve this challenge with the [str.split()](https://docs.python.org/3/library/stdtypes.html#str.split) and the [str.join()](https://docs.python.org/3/library/stdtypes.html#str.join) string methods. Every sentence will end with a period, and every new sentence will have one space before the previous period. Be careful about trailing whitespace in your solution.
def format_poem(poem): poem = poem.split('. ') result = '.\n'.join(poem) return result
def format_poem(poem): poem = poem.split('. ') result = '.\n'.join(poem) return result
train
APPS_structured
Bandwidth of a matrix A is defined as the smallest non-negative integer K such that A(i, j) = 0 for |i - j| > K. For example, a matrix with all zeros will have its bandwith equal to zero. Similarly bandwith of diagonal matrix will also be zero. For example, for the below given matrix, the bandwith of this matrix is 2. 1 0 0 0 1 1 1 1 0 Bandwidth of the below matrix is 1. Bandwidth of the below matrix is 2. Bandwidth of the below matrix is also 2. You will be a given a binary matrix A of dimensions N × N. You are allowed to make following operation as many times as you wish (possibly zero or more). In a single operation, you can swap any two entries of the matrix. Your aim is to minimize the bandwidth of the matrix. Find the minimum bandwidth of the matrix A you can get after making as many operations of above type as you want. -----Input----- The first line of the input contains an integer T denoting the number of test cases. The description of T test cases follow. First line of each test case contains an integer N denoting the height/width of the matrix. Next N lines of each test case contain N space separated binary integers (either zero or one) corresponding to the entries of the matrix. -----Output----- For each test case, output a single integer corresponding to the minimum bandwidth that you can obtain. -----Constraints----- - 1 ≤ T ≤ 10 - 1 ≤ N ≤ 500 - 0 ≤ A(i, j) ≤ 1 -----Subtasks----- - Subtask #1 (40 points) : 1 ≤ N ≤ 100 - Subtask #2 (60 points) : original constraints -----Example----- Input: 6 2 0 0 0 0 2 1 0 0 1 2 1 0 1 0 2 1 0 1 1 3 1 0 0 0 1 1 1 1 0 4 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 Output: 0 0 0 1 1 3 -----Explanation----- Example case 1. The bandwidth of a matrix will all zero entries will be zero. This is the minimum bandwidth you can get, so there is no need of performing any swap operation. Example case 2. The bandwidth of a diagonal matrix will also be zero. Example case 3. You can make the given matrix a diagonal matrix by swapping A(2, 1) and A(2, 2), which will have zero bandwidth. Example case 4. You can not make swaps in any way that can reduce the bandwidth of this matrix. Bandwidth of this matrix is equal to 1, which is the minimum bandwidth that you can get. Example case 5. Bandwidth of the given matrix is 2. You can make it equal to be 1 by swapping A(3, 1) and A(3, 3), i.e. the matrix after the operation will look like 1 0 0 0 1 1 0 1 1 The bandwidth of this matrix is 1. Example case 6. The swap operations won't have any effect on the matrix. Its bandwidth is equal to 3.
from sys import stdin T = int(stdin.readline()) for i in range(0, T): n = int(stdin.readline()) A = [] for i in range(0, n): A.append([int(i) for i in stdin.readline().split(' ')]) ones = sum([sum(i) for i in A]) compare = n ans = 0 for i in range(0, n): if ones <= compare: ans = i break compare += 2*(n-1-i) print(ans)
from sys import stdin T = int(stdin.readline()) for i in range(0, T): n = int(stdin.readline()) A = [] for i in range(0, n): A.append([int(i) for i in stdin.readline().split(' ')]) ones = sum([sum(i) for i in A]) compare = n ans = 0 for i in range(0, n): if ones <= compare: ans = i break compare += 2*(n-1-i) print(ans)
train
APPS_structured
# Bubblesort Algorithm ## Overview The Bubblesort Algorithm is one of many algorithms used to sort a list of similar items (e.g. all numbers or all letters) into either ascending order or descending order. Given a list (e.g.): python [9, 7, 5, 3, 1, 2, 4, 6, 8]  To sort this list in ascending order using Bubblesort, you first have to compare the first two terms of the list. If the first term is larger than the second term, you perform a swap. The list then becomes: python [7, 9, 5, 3, 1, 2, 4, 6, 8] # The "9" and "7" have been swapped because 9 is larger than 7 and thus 9 should be after 7  You then proceed by comparing the 2nd and 3rd terms, performing a swap *when necessary*, and then the 3rd and 4th term, then the 4th and 5th term, etc. etc. When you reach the end of the list, it is said that you have completed **1 complete pass**. ## Task Given an array of integers, your function bubblesortOnce/bubblesort_once/BubblesortOnce (or equivalent, depending on your language's naming conventions) should return a *new* array equivalent to performing exactly **1 complete pass** on the original array. Your function should be pure, i.e. it should **not** mutate the input array.
def bubblesort_once(L): if len(L)<=1 : return L if L[0]<=L[1]: return [L[0]] + bubblesort_once(L[1:]) return [L[1]] + bubblesort_once([L[0]]+L[2:])
def bubblesort_once(L): if len(L)<=1 : return L if L[0]<=L[1]: return [L[0]] + bubblesort_once(L[1:]) return [L[1]] + bubblesort_once([L[0]]+L[2:])
train
APPS_structured
Shivam owns a gambling house, which has a special wheel called The Wheel of Fortune. This wheel is meant for giving free coins to people coming in the house. The wheel of fortune is a game of chance. It uses a spinning wheel with exactly N numbered pockets and a coin is placed in between every consecutive pocket. The wheel is spun in either of the two ways. Before the wheel is turned, all the coins are restored and players bet on a number K. Then a needle is made to point to any one of the pocket which has number K written on it. Wheel is then spun till the needle encounters number K again and the player gets all the coins the needle has encountered. Shivam being the owner of the gambling house, has the authority to place the needle on any of the K numbered pockets and also he could rotate the wheel in either of the two ways. Shivam has to figure out a way to minimize number of coins that he has to spend on every given bet. You are given a wheel having N elements and Q players. Each player bets on a number K from the wheel. For each player you have to print minimum number of coins Shivam has to spend. -----Input----- - The first line of the input contains an integer T denoting the number of test cases . The description of T testcases follow. - The first line of each test case contains single integer N . - The second line of each test case contains N space seperated integers denoting the numbers on the wheel. - The third line of each test case contains a single integer Q denoting the number of players. - Then, Q lines follow a single integer K from the N numbers of the wheel -----Output----- For each player, output the minimum number of coins Shivam has to spend. -----Constraints----- - 1 ≤ T ≤ 10 - 1 ≤ N ≤ 100000 - 1 ≤ Number written on the Wheel ≤ 1000 - 1 ≤ Q ≤ 10000 - 1 ≤ K ≤ 1000 - It is guaranteed that K belongs to the N numbers written on the wheel. -----Example----- Input: 2 3 1 2 3 3 1 2 3 6 2 1 5 3 2 1 4 1 2 3 5 Output: 3 3 3 2 2 6 6
t=int(input()) for _ in range(t): n=int(input()) arr=list(map(int,input().split())) d={} for i in range(n): if arr[i] in d: d[arr[i]].append(i) else: d[arr[i]]=[i] q=int(input()) for i in range(q): m=int(input()) if len(d[m])==1: print(n) elif len(d[m])==2: print(min((d[m][1]-d[m][0]),((n-d[m][1])+d[m][0]))) else: k=100000 for j in range(len(d[m])-1): if (d[m][j+1]-d[m][j])<k: k=d[m][j+1]-d[m][j] else: pass print(min(k,((n-d[m][len(d[m])-1])+d[m][0])))
t=int(input()) for _ in range(t): n=int(input()) arr=list(map(int,input().split())) d={} for i in range(n): if arr[i] in d: d[arr[i]].append(i) else: d[arr[i]]=[i] q=int(input()) for i in range(q): m=int(input()) if len(d[m])==1: print(n) elif len(d[m])==2: print(min((d[m][1]-d[m][0]),((n-d[m][1])+d[m][0]))) else: k=100000 for j in range(len(d[m])-1): if (d[m][j+1]-d[m][j])<k: k=d[m][j+1]-d[m][j] else: pass print(min(k,((n-d[m][len(d[m])-1])+d[m][0])))
train
APPS_structured
Every Friday and Saturday night, farmer counts amount of sheep returned back to his farm (sheep returned on Friday stay and don't leave for a weekend). Sheep return in groups each of the days -> you will be given two arrays with these numbers (one for Friday and one for Saturday night). Entries are always positive ints, higher than zero. Farmer knows the total amount of sheep, this is a third parameter. You need to return the amount of sheep lost (not returned to the farm) after final sheep counting on Saturday. Example 1: Input: {1, 2}, {3, 4}, 15 --> Output: 5 Example 2: Input: {3, 1, 2}, {4, 5}, 21 --> Output: 6 Good luck! :-)
train
APPS_structured
## Number of people in the bus There is a bus moving in the city, and it takes and drop some people in each bus stop. You are provided with a list (or array) of integer arrays (or tuples). Each integer array has two items which represent number of people get into bus (The first item) and number of people get off the bus (The second item) in a bus stop. Your task is to return number of people who are still in the bus after the last bus station (after the last array). Even though it is the last bus stop, the bus is not empty and some people are still in the bus, and they are probably sleeping there :D Take a look on the test cases. Please keep in mind that the test cases ensure that the number of people in the bus is always >= 0. So the return integer can't be negative. The second value in the first integer array is 0, since the bus is empty in the first bus stop.
def number(bus_stops): # Good Luck! return sum((peoplein - peopleout) for peoplein,peopleout in (bus_stops))
def number(bus_stops): # Good Luck! return sum((peoplein - peopleout) for peoplein,peopleout in (bus_stops))
train
APPS_structured
You are given n strings s_1, s_2, ..., s_{n} consisting of characters 0 and 1. m operations are performed, on each of them you concatenate two existing strings into a new one. On the i-th operation the concatenation s_{a}_{i}s_{b}_{i} is saved into a new string s_{n} + i (the operations are numbered starting from 1). After each operation you need to find the maximum positive integer k such that all possible strings consisting of 0 and 1 of length k (there are 2^{k} such strings) are substrings of the new string. If there is no such k, print 0. -----Input----- The first line contains single integer n (1 ≤ n ≤ 100) — the number of strings. The next n lines contain strings s_1, s_2, ..., s_{n} (1 ≤ |s_{i}| ≤ 100), one per line. The total length of strings is not greater than 100. The next line contains single integer m (1 ≤ m ≤ 100) — the number of operations. m lines follow, each of them contains two integers a_{i} abd b_{i} (1 ≤ a_{i}, b_{i} ≤ n + i - 1) — the number of strings that are concatenated to form s_{n} + i. -----Output----- Print m lines, each should contain one integer — the answer to the question after the corresponding operation. -----Example----- Input 5 01 10 101 11111 0 3 1 2 6 5 4 4 Output 1 2 0 -----Note----- On the first operation, a new string "0110" is created. For k = 1 the two possible binary strings of length k are "0" and "1", they are substrings of the new string. For k = 2 and greater there exist strings of length k that do not appear in this string (for k = 2 such string is "00"). So the answer is 1. On the second operation the string "01100" is created. Now all strings of length k = 2 are present. On the third operation the string "1111111111" is created. There is no zero, so the answer is 0.
# -*- coding: utf-8 -*- import math import collections import bisect import heapq import time import random """ created by shhuan at 2017/10/5 15:00 """ N = int(input()) S = [''] for i in range(N): S.append(input()) M = int(input()) # t0 = time.time() # N = 3 # S = ["", "00010110000", "110101110101101010101101101110100010000001101101011000010001011000010101", "11100101100111010"] # M = 1000 A = [[set() for _ in range(10)] for _ in range(M+N+1)] D = collections.defaultdict(int) for i in range(1, N+1): for j in range(1, 10): s = S[i] if j > len(s): break for k in range(len(s)-j+1): A[i][j].add(int(s[k:k+j], 2)) if all(v in A[i][j] for v in range(2**j)): D[i] = j for i in range(M): # a, b = random.randint(1, i+N), random.randint(1, i+N) a, b = list(map(int, input().split())) s, sa, sb = S[a] + S[b], S[a], S[b] if len(s) > 30: S.append(s[:10] + s[-10:]) else: S.append(s) ai = i+N+1 d = max(D[a], D[b]) + 1 for dv in range(d, 10): if len(sa) + len(sb) < dv: break A[ai][dv] = A[a][dv] | A[b][dv] | {int(v, 2) for v in {sa[-i:] + sb[:dv-i] for i in range(1, dv+1)} if len(v) == dv} ans = d-1 for dv in range(d, 10): if any(v not in A[ai][dv] for v in range(2**dv)): break ans = dv print(ans) D[ai] = ans # print(time.time() - t0)
# -*- coding: utf-8 -*- import math import collections import bisect import heapq import time import random """ created by shhuan at 2017/10/5 15:00 """ N = int(input()) S = [''] for i in range(N): S.append(input()) M = int(input()) # t0 = time.time() # N = 3 # S = ["", "00010110000", "110101110101101010101101101110100010000001101101011000010001011000010101", "11100101100111010"] # M = 1000 A = [[set() for _ in range(10)] for _ in range(M+N+1)] D = collections.defaultdict(int) for i in range(1, N+1): for j in range(1, 10): s = S[i] if j > len(s): break for k in range(len(s)-j+1): A[i][j].add(int(s[k:k+j], 2)) if all(v in A[i][j] for v in range(2**j)): D[i] = j for i in range(M): # a, b = random.randint(1, i+N), random.randint(1, i+N) a, b = list(map(int, input().split())) s, sa, sb = S[a] + S[b], S[a], S[b] if len(s) > 30: S.append(s[:10] + s[-10:]) else: S.append(s) ai = i+N+1 d = max(D[a], D[b]) + 1 for dv in range(d, 10): if len(sa) + len(sb) < dv: break A[ai][dv] = A[a][dv] | A[b][dv] | {int(v, 2) for v in {sa[-i:] + sb[:dv-i] for i in range(1, dv+1)} if len(v) == dv} ans = d-1 for dv in range(d, 10): if any(v not in A[ai][dv] for v in range(2**dv)): break ans = dv print(ans) D[ai] = ans # print(time.time() - t0)
train
APPS_structured
Mohit's girlfriend is playing a game with Nicky. The description of the game is as follows: - Initially on a table Player 1 will put N gem-stones. - Players will play alternatively, turn by turn. - At each move a player can take at most M gem-stones (at least 1 gem-stone must be taken) from the available gem-stones on the table.(Each gem-stone has same cost.) - Each players gem-stone are gathered in player's side. - The player that empties the table purchases food from it (using all his gem-stones; one gem-stone can buy one unit of food), and the other one puts all his gem-stones back on to the table. Again the game continues with the "loser" player starting. - The game continues until all the gem-stones are used to buy food. - The main objective of the game is to consume maximum units of food. Mohit's girlfriend is weak in mathematics and prediction so she asks help from Mohit, in return she shall kiss Mohit. Mohit task is to predict the maximum units of food her girlfriend can eat, if, she starts first. Being the best friend of Mohit, help him in predicting the answer. -----Input----- - Single line contains two space separated integers N and M. -----Output----- - The maximum units of food Mohit's girlfriend can eat. -----Constraints and Subtasks----- - 1 <= M <= N <= 100 Subtask 1: 10 points - 1 <= M <= N <= 5 Subtask 2: 20 points - 1 <= M <= N <= 10 Subtask 3: 30 points - 1 <= M <= N <= 50 Subtask 3: 40 points - Original Constraints. -----Example----- Input: 4 2 Output: 2
read = lambda: list(map(int, input().split())) read_s = lambda: list(map(str, input().split())) n, m = read() ans = 0 while True: if n > m: ans += m n -= 2*m else: break print(ans)
read = lambda: list(map(int, input().split())) read_s = lambda: list(map(str, input().split())) n, m = read() ans = 0 while True: if n > m: ans += m n -= 2*m else: break print(ans)
train
APPS_structured
# Task In the field, two beggars A and B found some gold at the same time. They all wanted the gold, and they decided to use simple rules to distribute gold:  They divided gold into n piles and be in line. The amount of each pile and the order of piles all are randomly. They took turns to take away a pile of gold from the far left or the far right. They always choose the bigger pile. That is to say, if the left is 1, the right is 2, then choose to take 2. If the both sides are equal, take the left pile.  Given an integer array golds, and assume that A always takes first. Please calculate the final amount of gold obtained by A and B. returns a two-element array [amount of A, amount of B]. # Example For golds = [4,2,9,5,2,7], the output should be [14,15].  The pile of most left is 4, The pile of most right is 7, A choose the largest one -- > take 7 The pile of most left is 4, The pile of most right is 2, B choose the largest one -- > take 4 The pile of most left is 2, The pile of most left is 2, A choose the most left one -- > take 2 The pile of most left is 9, The pile of most right is 2, B choose the largest one -- > take 9 The pile of most left is 5, The pile of most left is 2, A choose the largest one -- > take 5 Tehn, only 1 pile left, B -- > take 2 A: 7 + 2 + 5 = 14 B: 4 + 9 + 2 = 15  For golds = [10,1000,2,1], the output should be [12,1001].  A take 10 B take 1000 A take 2 B take 1 A: 10 + 2 = 12 B: 1000 + 1 = 1001 
def distribution_of(golds): a,b,i=0,0,0 golds_c=golds[:] while golds_c: m=golds_c.pop(0) if golds_c[0]>=golds_c[-1] else golds_c.pop() if i%2:b+=m else:a+=m i+=1 return [a,b]
def distribution_of(golds): a,b,i=0,0,0 golds_c=golds[:] while golds_c: m=golds_c.pop(0) if golds_c[0]>=golds_c[-1] else golds_c.pop() if i%2:b+=m else:a+=m i+=1 return [a,b]
train
APPS_structured
# Task Write a function deNico/de_nico() that accepts two parameters: - key/$key - string consists of unique letters and digits - message/$message - string with encoded message and decodes the message using the key. First create a numeric key basing on the provided key by assigning each letter position in which it is located after setting the letters from key in an alphabetical order. For example, for the key crazy we will get 23154 because of acryz (sorted letters from the key). Let's decode cseerntiofarmit on  using our crazy key.  1 2 3 4 5 --------- c s e e r n t i o f a r m i t o n  After using the key:  2 3 1 5 4 --------- s e c r e t i n f o r m a t i o n  # Notes - The message is never shorter than the key. - Don't forget to remove trailing whitespace after decoding the message # Examples Check the test cases for more examples. # Related Kata [Basic Nico - encode](https://www.codewars.com/kata/5968bb83c307f0bb86000015)
def de_nico(key,msg): num_key = ''.join([str(id) for i in key for id, item in enumerate(sorted(key), 1) if item == i]) cut_msg = [msg[i:i+len(num_key)] for i in range(0, len(msg), len(num_key))] d_msg = [''.join([item for i in num_key for id, item in enumerate(list(x), 1) if id == int(i)]) for x in cut_msg] return ''.join(d_msg).rstrip()
def de_nico(key,msg): num_key = ''.join([str(id) for i in key for id, item in enumerate(sorted(key), 1) if item == i]) cut_msg = [msg[i:i+len(num_key)] for i in range(0, len(msg), len(num_key))] d_msg = [''.join([item for i in num_key for id, item in enumerate(list(x), 1) if id == int(i)]) for x in cut_msg] return ''.join(d_msg).rstrip()
train
APPS_structured
Write a function that calculates the *least common multiple* of its arguments; each argument is assumed to be a non-negative integer. In the case that there are no arguments (or the provided array in compiled languages is empty), return 1. ~~~if:objc NOTE: The first (and only named) argument of the function n specifies the number of arguments in the variable-argument list. Do **not** take n into account when computing the LCM of the numbers. ~~~
from functools import reduce def lcm(*args): return reduce(lcms, args) if args else 1 def gcd(a,b): """Euclidean Algorithm""" return b if a == 0 else gcd(b % a, a) def lcms(a, b): return (a*b) // gcd(a,b)
from functools import reduce def lcm(*args): return reduce(lcms, args) if args else 1 def gcd(a,b): """Euclidean Algorithm""" return b if a == 0 else gcd(b % a, a) def lcms(a, b): return (a*b) // gcd(a,b)
train
APPS_structured
Given a string text, we are allowed to swap two of the characters in the string. Find the length of the longest substring with repeated characters. Example 1: Input: text = "ababa" Output: 3 Explanation: We can swap the first 'b' with the last 'a', or the last 'b' with the first 'a'. Then, the longest repeated character substring is "aaa", which its length is 3. Example 2: Input: text = "aaabaaa" Output: 6 Explanation: Swap 'b' with the last 'a' (or the first 'a'), and we get longest repeated character substring "aaaaaa", which its length is 6. Example 3: Input: text = "aaabbaaa" Output: 4 Example 4: Input: text = "aaaaa" Output: 5 Explanation: No need to swap, longest repeated character substring is "aaaaa", length is 5. Example 5: Input: text = "abcdef" Output: 1 Constraints: 1 <= text.length <= 20000 text consist of lowercase English characters only.
import itertools from collections import Counter class Solution: def maxRepOpt1(self, text: str) -> int: ref = [ [letter,len(list(s))] for letter,s in itertools.groupby(text)] count = Counter(text) res = max( [ min(count.get(i), k + 1) for i , k in ref] ) for i in range(1,len(ref) - 1): if ref[i-1][0] == ref[i+1][0] and ref[i][1] == 1 : res = max(res, min(ref[i-1][1] + ref[i+1][1] + 1, count.get(ref[i-1][0])) ) return res
import itertools from collections import Counter class Solution: def maxRepOpt1(self, text: str) -> int: ref = [ [letter,len(list(s))] for letter,s in itertools.groupby(text)] count = Counter(text) res = max( [ min(count.get(i), k + 1) for i , k in ref] ) for i in range(1,len(ref) - 1): if ref[i-1][0] == ref[i+1][0] and ref[i][1] == 1 : res = max(res, min(ref[i-1][1] + ref[i+1][1] + 1, count.get(ref[i-1][0])) ) return res
train
APPS_structured
Write a program to check whether a triangle is valid or not, when the three angles of the triangle are the inputs. A triangle is valid if the sum of all the three angles is equal to 180 degrees. -----Input----- The first line contains an integer T, the total number of testcases. Then T lines follow, each line contains three angles A, B and C, of the triangle separated by space. -----Output----- For each test case, display 'YES' if the triangle is valid, and 'NO', if it is not, in a new line. -----Constraints----- - 1 ≤ T ≤ 1000 - 1 ≤ A,B,C ≤ 180 -----Example----- Input 3 40 40 100 45 45 90 180 1 1 Output YES YES NO
N=int(input()) for i in range(N): a,b,c=list(map(int,input().split())) if(a+b+c==180): print('YES') else: print('NO')
N=int(input()) for i in range(N): a,b,c=list(map(int,input().split())) if(a+b+c==180): print('YES') else: print('NO')
train
APPS_structured
A number is simply made up of digits. The number 1256 is made up of the digits 1, 2, 5, and 6. For 1256 there are 24 distinct permutations of the digits: 1256, 1265, 1625, 1652, 1562, 1526, 2156, 2165, 2615, 2651, 2561, 2516, 5126, 5162, 5216, 5261, 5621, 5612, 6125, 6152, 6251, 6215, 6521, 6512. Your goal is to write a program that takes a number, n, and returns the average value of all distinct permutations of the digits in n. Your answer should be rounded to the nearest integer. For the example above the return value would be 3889. * n will never be negative A few examples: python permutation_average(2) return 2 permutation_average(25) >>> 25 + 52 = 77 >>> 77 / 2 = 38.5 return 39 * permutation_average(20) >>> 20 + 02 = 22 >>> 22 / 2 = 11 return 11 permutation_average(737) >>> 737 + 377 + 773 = 1887 >>> 1887 / 3 = 629 return 629  Note: Your program should be able to handle numbers up to 6 digits long ~~~if:python \* Python version 3 and above uses Banker Rounding so the expected values for those tests would be 3888 and 38 respectively ~~~ ~~~if-not:python \* ignore these marks, they're for Python only ~~~
from itertools import permutations from math import factorial def permutation_average(n): return round(sum(int(''.join(x)) for x in permutations(str(n))) / float(factorial(len(str(n)))))
from itertools import permutations from math import factorial def permutation_average(n): return round(sum(int(''.join(x)) for x in permutations(str(n))) / float(factorial(len(str(n)))))
train
APPS_structured
Given an 2D board, count how many battleships are in it. The battleships are represented with 'X's, empty slots are represented with '.'s. You may assume the following rules: You receive a valid board, made of only battleships or empty slots. Battleships can only be placed horizontally or vertically. In other words, they can only be made of the shape 1xN (1 row, N columns) or Nx1 (N rows, 1 column), where N can be of any size. At least one horizontal or vertical cell separates between two battleships - there are no adjacent battleships. Example: X..X ...X ...X In the above board there are 2 battleships. Invalid Example: ...X XXXX ...X This is an invalid board that you will not receive - as battleships will always have a cell separating between them. Follow up:Could you do it in one-pass, using only O(1) extra memory and without modifying the value of the board?
class Solution: def countBattleships(self, board): """ :type board: List[List[str]] :rtype: int """ ans = 0 for r, row in enumerate(board): for c, val in enumerate(row): if val == 'X': ans += 1 if r and board[r-1][c] == 'X': ans -= 1 elif c and board[r][c-1] == 'X': ans -= 1 return ans
class Solution: def countBattleships(self, board): """ :type board: List[List[str]] :rtype: int """ ans = 0 for r, row in enumerate(board): for c, val in enumerate(row): if val == 'X': ans += 1 if r and board[r-1][c] == 'X': ans -= 1 elif c and board[r][c-1] == 'X': ans -= 1 return ans
train
APPS_structured
Write a program to obtain a number $(N)$ from the user and display whether the number is a one digit number, 2 digit number, 3 digit number or more than 3 digit number -----Input:----- - First line will contain the number $N$, -----Output:----- Print "1" if N is a 1 digit number. Print "2" if N is a 2 digit number. Print "3" if N is a 3 digit number. Print "More than 3 digits" if N has more than 3 digits. -----Constraints----- - $0 \leq N \leq 1000000$ -----Sample Input:----- 9 -----Sample Output:----- 1
# cook your dish here s=input() if len(s)==1: print(1) if len(s)==2: print(2) if len(s)==3: print(3) elif len(s)>3: print( "More than 3 digits")
# cook your dish here s=input() if len(s)==1: print(1) if len(s)==2: print(2) if len(s)==3: print(3) elif len(s)>3: print( "More than 3 digits")
train
APPS_structured
Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order. You may assume no duplicates in the array. Example 1: Input: [1,3,5,6], 5 Output: 2 Example 2: Input: [1,3,5,6], 2 Output: 1 Example 3: Input: [1,3,5,6], 7 Output: 4 Example 4: Input: [1,3,5,6], 0 Output: 0
class Solution: def searchInsert(self, nums, target): """ :type nums: List[int] :type target: int :rtype: int """ i = 0 n = len(nums) if n == 0: return 0 if nums[0] >= target else 1 else: if nums[n-1] < target: return n else: while i < n: if nums[i] >= target: return i else: i += 1
class Solution: def searchInsert(self, nums, target): """ :type nums: List[int] :type target: int :rtype: int """ i = 0 n = len(nums) if n == 0: return 0 if nums[0] >= target else 1 else: if nums[n-1] < target: return n else: while i < n: if nums[i] >= target: return i else: i += 1
train
APPS_structured
=====Problem Statement===== The itertools module standardizes a core set of fast, memory efficient tools that are useful by themselves or in combination. Together, they form an iterator algebra making it possible to construct specialized tools succinctly and efficiently in pure Python. You are given a list of N lowercase English letters. For a given integer K, you can select any K indices (assume 1-based indexing) with a uniform probability from the list. Find the probability that at least one of the K indices selected will contain the letter: ''. =====Input Format===== The input consists of three lines. The first line contains the integer N, denoting the length of the list. The next line consists of N space-separated lowercase English letters, denoting the elements of the list. The third and the last line of input contains the integer K, denoting the number of indices to be selected. =====Output Format===== Output a single line consisting of the probability that at least one of the K indices selected contains the letter: 'a'. Note: The answer must be correct up to 3 decimal places. =====Constraints===== 1≤N≤10 1≤K≤N
#!/usr/bin/env python3 import string symbols = string.ascii_lowercase from itertools import combinations def __starting_point(): n = int(input().strip()) arr = list(map(str, input().strip().split(' '))) times = int(input().strip()) cmbts = list(combinations(sorted(arr), times)) print(("{:.4f}".format(len(list([a for a in cmbts if a[0] == 'a']))/(len(cmbts))))) __starting_point()
#!/usr/bin/env python3 import string symbols = string.ascii_lowercase from itertools import combinations def __starting_point(): n = int(input().strip()) arr = list(map(str, input().strip().split(' '))) times = int(input().strip()) cmbts = list(combinations(sorted(arr), times)) print(("{:.4f}".format(len(list([a for a in cmbts if a[0] == 'a']))/(len(cmbts))))) __starting_point()
train
APPS_structured
Given an integer array arr, remove a subarray (can be empty) from arr such that the remaining elements in arr are non-decreasing. A subarray is a contiguous subsequence of the array. Return the length of the shortest subarray to remove. Example 1: Input: arr = [1,2,3,10,4,2,3,5] Output: 3 Explanation: The shortest subarray we can remove is [10,4,2] of length 3. The remaining elements after that will be [1,2,3,3,5] which are sorted. Another correct solution is to remove the subarray [3,10,4]. Example 2: Input: arr = [5,4,3,2,1] Output: 4 Explanation: Since the array is strictly decreasing, we can only keep a single element. Therefore we need to remove a subarray of length 4, either [5,4,3,2] or [4,3,2,1]. Example 3: Input: arr = [1,2,3] Output: 0 Explanation: The array is already non-decreasing. We do not need to remove any elements. Example 4: Input: arr = [1] Output: 0 Constraints: 1 <= arr.length <= 10^5 0 <= arr[i] <= 10^9
class Solution: def findLengthOfShortestSubarray(self, arr: List[int]) -> int: l = [] for x in arr: if not l or x >= l[-1]: l.append(x) else: break r = [] for i in range(len(arr)-1, -1, -1): if not r or arr[i] <= r[-1]: r.append(arr[i]) else: break r.reverse() if len(l) == len(arr): return 0 sol = max(len(l), len(r)) i, j = 0, 0 # print(l, r) while i < len(l) and j < len(r): if l[i] <= r[j]: i += 1 else: while j < len(r) and l[i] > r[j]: j += 1 # print(i, j) sol = max(sol, i+len(r)-j) return len(arr) - sol
class Solution: def findLengthOfShortestSubarray(self, arr: List[int]) -> int: l = [] for x in arr: if not l or x >= l[-1]: l.append(x) else: break r = [] for i in range(len(arr)-1, -1, -1): if not r or arr[i] <= r[-1]: r.append(arr[i]) else: break r.reverse() if len(l) == len(arr): return 0 sol = max(len(l), len(r)) i, j = 0, 0 # print(l, r) while i < len(l) and j < len(r): if l[i] <= r[j]: i += 1 else: while j < len(r) and l[i] > r[j]: j += 1 # print(i, j) sol = max(sol, i+len(r)-j) return len(arr) - sol
train
APPS_structured
For this exercise you will create a global flatten method. The method takes in any number of arguments and flattens them into a single array. If any of the arguments passed in are an array then the individual objects within the array will be flattened so that they exist at the same level as the other arguments. Any nested arrays, no matter how deep, should be flattened into the single array result. The following are examples of how this function would be used and what the expected results would be: python flatten(1, [2, 3], 4, 5, [6, [7]]) # returns [1, 2, 3, 4, 5, 6, 7] flatten('a', ['b', 2], 3, None, [[4], ['c']]) # returns ['a', 'b', 2, 3, None, 4, 'c'] 
def flatten(*a): r, s = [], [iter(a)] while s: it = s.pop() for v in it: if isinstance(v, list): s.extend((it, iter(v))) break else: r.append(v) return r
def flatten(*a): r, s = [], [iter(a)] while s: it = s.pop() for v in it: if isinstance(v, list): s.extend((it, iter(v))) break else: r.append(v) return r
train
APPS_structured
There are N robots and M exits on a number line. The N + M coordinates of these are all integers and all distinct. For each i (1 \leq i \leq N), the coordinate of the i-th robot from the left is x_i. Also, for each j (1 \leq j \leq M), the coordinate of the j-th exit from the left is y_j. Snuke can repeatedly perform the following two kinds of operations in any order to move all the robots simultaneously: - Increment the coordinates of all the robots on the number line by 1. - Decrement the coordinates of all the robots on the number line by 1. Each robot will disappear from the number line when its position coincides with that of an exit, going through that exit. Snuke will continue performing operations until all the robots disappear. When all the robots disappear, how many combinations of exits can be used by the robots? Find the count modulo 10^9 + 7. Here, two combinations of exits are considered different when there is a robot that used different exits in those two combinations. -----Constraints----- - 1 \leq N, M \leq 10^5 - 1 \leq x_1 < x_2 < ... < x_N \leq 10^9 - 1 \leq y_1 < y_2 < ... < y_M \leq 10^9 - All given coordinates are integers. - All given coordinates are distinct. -----Input----- Input is given from Standard Input in the following format: N M x_1 x_2 ... x_N y_1 y_2 ... y_M -----Output----- Print the number of the combinations of exits that can be used by the robots when all the robots disappear, modulo 10^9 + 7. -----Sample Input----- 2 2 2 3 1 4 -----Sample Output----- 3 The i-th robot from the left will be called Robot i, and the j-th exit from the left will be called Exit j. There are three possible combinations of exits (the exit used by Robot 1, the exit used by Robot 2) as follows: - (Exit 1, Exit 1) - (Exit 1, Exit 2) - (Exit 2, Exit 2)
from bisect import bisect from collections import defaultdict class Bit: def __init__(self, n, MOD): self.size = n self.tree = [0] * (n + 1) self.depth = n.bit_length() self.mod = MOD def sum(self, i): s = 0 while i > 0: s += self.tree[i] i -= i & -i return s % self.mod def add(self, i, x): while i <= self.size: self.tree[i] = (self.tree[i] + x) % self.mod i += i & -i def debug_print(self): for i in range(1, self.size + 1): j = (i & -i).bit_length() print((' ' * j, self.tree[i])) def lower_bound(self, x): sum_ = 0 pos = 0 for i in range(self.depth, -1, -1): k = pos + (1 << i) if k <= self.size and sum_ + self.tree[k] < x: sum_ += self.tree[k] pos += 1 << i return pos + 1, sum_ n, m = list(map(int, input().split())) xxx = list(map(int, input().split())) yyy = list(map(int, input().split())) ab = defaultdict(set) coordinates = set() for x in xxx: if x < yyy[0] or yyy[-1] < x: continue i = bisect(yyy, x) a = x - yyy[i - 1] b = yyy[i] - x ab[a].add(b) coordinates.add(b) # Bitのindexは1から始まるように作っているが、"0"を取れるようにするため、全体を1ずらす cor_dict = {b: i for i, b in enumerate(sorted(coordinates), start=2)} cdg = cor_dict.get MOD = 10 ** 9 + 7 bit = Bit(len(coordinates) + 1, MOD) bit.add(1, 1) for a in sorted(ab): bbb = sorted(map(cdg, ab[a]), reverse=True) for b in bbb: bit.add(b, bit.sum(b - 1)) print((bit.sum(bit.size)))
from bisect import bisect from collections import defaultdict class Bit: def __init__(self, n, MOD): self.size = n self.tree = [0] * (n + 1) self.depth = n.bit_length() self.mod = MOD def sum(self, i): s = 0 while i > 0: s += self.tree[i] i -= i & -i return s % self.mod def add(self, i, x): while i <= self.size: self.tree[i] = (self.tree[i] + x) % self.mod i += i & -i def debug_print(self): for i in range(1, self.size + 1): j = (i & -i).bit_length() print((' ' * j, self.tree[i])) def lower_bound(self, x): sum_ = 0 pos = 0 for i in range(self.depth, -1, -1): k = pos + (1 << i) if k <= self.size and sum_ + self.tree[k] < x: sum_ += self.tree[k] pos += 1 << i return pos + 1, sum_ n, m = list(map(int, input().split())) xxx = list(map(int, input().split())) yyy = list(map(int, input().split())) ab = defaultdict(set) coordinates = set() for x in xxx: if x < yyy[0] or yyy[-1] < x: continue i = bisect(yyy, x) a = x - yyy[i - 1] b = yyy[i] - x ab[a].add(b) coordinates.add(b) # Bitのindexは1から始まるように作っているが、"0"を取れるようにするため、全体を1ずらす cor_dict = {b: i for i, b in enumerate(sorted(coordinates), start=2)} cdg = cor_dict.get MOD = 10 ** 9 + 7 bit = Bit(len(coordinates) + 1, MOD) bit.add(1, 1) for a in sorted(ab): bbb = sorted(map(cdg, ab[a]), reverse=True) for b in bbb: bit.add(b, bit.sum(b - 1)) print((bit.sum(bit.size)))
train
APPS_structured
Write a program to take two numbers as input and print their difference if the first number is greater than the second number otherwise$otherwise$ print their sum. -----Input:----- - First line will contain the first number (N1$N1$) - Second line will contain the second number (N2$N2$) -----Output:----- Output a single line containing the difference of 2 numbers (N1−N2)$(N1 - N2)$ if the first number is greater than the second number otherwise output their sum (N1+N2)$(N1 + N2)$. -----Constraints----- - −1000≤N1≤1000$-1000 \leq N1 \leq 1000$ - −1000≤N2≤1000$-1000 \leq N2 \leq 1000$ -----Sample Input:----- 82 28 -----Sample Output:----- 54
from sys import * def main(): nbre1 = int(stdin.readline().strip()) nbre2 = int(stdin.readline().strip()) if nbre1 > nbre2: difference = nbre1 - nbre2 stdout.write(str(difference)) else: somme = nbre1 + nbre2 stdout.write(str(somme)) def __starting_point(): main() __starting_point()
from sys import * def main(): nbre1 = int(stdin.readline().strip()) nbre2 = int(stdin.readline().strip()) if nbre1 > nbre2: difference = nbre1 - nbre2 stdout.write(str(difference)) else: somme = nbre1 + nbre2 stdout.write(str(somme)) def __starting_point(): main() __starting_point()
train
APPS_structured
Now you have to write a function that takes an argument and returns the square of it.
def square(n): squares = int(n **2) return squares
def square(n): squares = int(n **2) return squares
train
APPS_structured
Today, Chef decided to cook some delicious meals from the ingredients in his kitchen. There are $N$ ingredients, represented by strings $S_1, S_2, \ldots, S_N$. Chef took all the ingredients, put them into a cauldron and mixed them up. In the cauldron, the letters of the strings representing the ingredients completely mixed, so each letter appears in the cauldron as many times as it appeared in all the strings in total; now, any number of times, Chef can take one letter out of the cauldron (if this letter appears in the cauldron multiple times, it can be taken out that many times) and use it in a meal. A complete meal is the string "codechef". Help Chef find the maximum number of complete meals he can make! -----Input----- - The first line of the input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows. - The first line of each test case contains a single integer $N$. - $N$ lines follow. For each $i$ ($1 \le i \le N$), the $i$-th of these lines contains a single string $S_i$. -----Output----- For each test case, print a single line containing one integer — the maximum number of complete meals Chef can create. -----Constraints----- - $1 \le T \le 100$ - $1 \le N \le 100$ - $|S_1| + |S_2| + \ldots + |S_N| \le 1,000$ - each string contains only lowercase English letters -----Example Input----- 3 6 cplusplus oscar deck fee hat near 5 code hacker chef chaby dumbofe 5 codechef chefcode fehcedoc cceeohfd codechef -----Example Output----- 1 2 5 -----Explanation----- Example case 1: After mixing, the cauldron contains the letter 'c' 3 times, the letter 'e' 4 times, and each of the letters 'o', 'd', 'h' and 'f' once. Clearly, this is only enough for one "codechef" meal. Example case 2: After mixing, the cauldron contains the letter 'c' 4 times, 'o' 2 times, 'd' 2 times, 'e' 4 times, 'h' 3 times and 'f' 2 times, which is enough to make 2 meals.
# cook your dish here for _ in range(int(input())): N = int(input()) s = '' for i in range(N): s += input() c = [] for i in list('codehf'): c.append(s.count(i)) c[0] /= 2 c[3] /= 2 print(int(min(c)))
# cook your dish here for _ in range(int(input())): N = int(input()) s = '' for i in range(N): s += input() c = [] for i in list('codehf'): c.append(s.count(i)) c[0] /= 2 c[3] /= 2 print(int(min(c)))
train
APPS_structured
# Right in the Center _This is inspired by one of Nick Parlante's exercises on the [CodingBat](https://codingbat.com/java) online code practice tool._ Given a sequence of characters, does "abc" appear in the CENTER of the sequence? The sequence of characters could contain more than one "abc". To define CENTER, the number of characters in the sequence to the left and right of the "abc" (which is in the middle) must differ by at most one. If it is in the CENTER, return True. Otherwise, return False. Write a function as the solution for this problem. This kata looks simple, but it might not be easy. ## Example is_in_middle("AAabcBB") -> True is_in_middle("AabcBB") -> True is_in_middle("AabcBBB") -> False
def in_centre(s,i): return s[i] == "a" and s[i+1] == "b" and s[i+2] == "c" def is_in_middle(s): if "abc" not in s or len(s) < 3: return False l = len(s) if l % 2 == 1: i = (l+1)//2-2; return in_centre(s,i) else: i1 = l//2 -2; i2 = l//2 -1; return in_centre(s,i1) or in_centre(s,i2)
def in_centre(s,i): return s[i] == "a" and s[i+1] == "b" and s[i+2] == "c" def is_in_middle(s): if "abc" not in s or len(s) < 3: return False l = len(s) if l % 2 == 1: i = (l+1)//2-2; return in_centre(s,i) else: i1 = l//2 -2; i2 = l//2 -1; return in_centre(s,i1) or in_centre(s,i2)
train
APPS_structured
Watchmen are in a danger and Doctor Manhattan together with his friend Daniel Dreiberg should warn them as soon as possible. There are n watchmen on a plane, the i-th watchman is located at point (x_{i}, y_{i}). They need to arrange a plan, but there are some difficulties on their way. As you know, Doctor Manhattan considers the distance between watchmen i and j to be |x_{i} - x_{j}| + |y_{i} - y_{j}|. Daniel, as an ordinary person, calculates the distance using the formula $\sqrt{(x_{i} - x_{j})^{2} +(y_{i} - y_{j})^{2}}$. The success of the operation relies on the number of pairs (i, j) (1 ≤ i < j ≤ n), such that the distance between watchman i and watchmen j calculated by Doctor Manhattan is equal to the distance between them calculated by Daniel. You were asked to compute the number of such pairs. -----Input----- The first line of the input contains the single integer n (1 ≤ n ≤ 200 000) — the number of watchmen. Each of the following n lines contains two integers x_{i} and y_{i} (|x_{i}|, |y_{i}| ≤ 10^9). Some positions may coincide. -----Output----- Print the number of pairs of watchmen such that the distance between them calculated by Doctor Manhattan is equal to the distance calculated by Daniel. -----Examples----- Input 3 1 1 7 5 1 5 Output 2 Input 6 0 0 0 1 0 2 -1 1 0 1 1 1 Output 11 -----Note----- In the first sample, the distance between watchman 1 and watchman 2 is equal to |1 - 7| + |1 - 5| = 10 for Doctor Manhattan and $\sqrt{(1 - 7)^{2} +(1 - 5)^{2}} = 2 \cdot \sqrt{13}$ for Daniel. For pairs (1, 1), (1, 5) and (7, 5), (1, 5) Doctor Manhattan and Daniel will calculate the same distances.
from collections import defaultdict, Counter n = int(input()) w = [] for i in range(n): w.append(tuple(map(int, input().split()))) dx = Counter() dy = Counter() for x, y in w: dx[x] += 1 dy[y] += 1 count = sum((v * (v-1) / 2) for v in list(dx.values())) + \ sum((v * (v-1) / 2) for v in list(dy.values())) dc = Counter(w) count -= sum((c * (c-1) / 2) for c in list(dc.values()) if c > 1) print(int(count))
from collections import defaultdict, Counter n = int(input()) w = [] for i in range(n): w.append(tuple(map(int, input().split()))) dx = Counter() dy = Counter() for x, y in w: dx[x] += 1 dy[y] += 1 count = sum((v * (v-1) / 2) for v in list(dx.values())) + \ sum((v * (v-1) / 2) for v in list(dy.values())) dc = Counter(w) count -= sum((c * (c-1) / 2) for c in list(dc.values()) if c > 1) print(int(count))
train
APPS_structured
We have jobs: difficulty[i] is the difficulty of the ith job, and profit[i] is the profit of the ith job.  Now we have some workers. worker[i] is the ability of the ith worker, which means that this worker can only complete a job with difficulty at most worker[i].  Every worker can be assigned at most one job, but one job can be completed multiple times. For example, if 3 people attempt the same job that pays $1, then the total profit will be$3.  If a worker cannot complete any job, his profit is $0. What is the most profit we can make? Example 1: Input: difficulty = [2,4,6,8,10], profit = [10,20,30,40,50], worker = [4,5,6,7] Output: 100 Explanation: Workers are assigned jobs of difficulty [4,4,6,6] and they get profit of [20,20,30,30] seperately. Notes: 1 <= difficulty.length = profit.length <= 10000 1 <= worker.length <= 10000 difficulty[i], profit[i], worker[i] are in range [1, 10^5] from bisect import bisect_right class Solution: def maxProfitAssignment(self, difficulty: List[int], profit: List[int], worker: List[int]) -> int: dp = [(d, p) for d, p in zip(difficulty, profit)] dp.sort() G = [] C = [] for x, y in dp: if not G or G[-1] < x: G.append(x) C.append(y) continue if G[-1] == x: C[-1] = y for y in range(1, len(C)): if C[y-1] > C[y]: C[y] = C[y-1] ans = 0 for w in worker: idx = bisect_right(G, w)-1 if idx >= 0: ans += C[idx] return ans from bisect import bisect_right class Solution: def maxProfitAssignment(self, difficulty: List[int], profit: List[int], worker: List[int]) -> int: dp = [(d, p) for d, p in zip(difficulty, profit)] dp.sort() G = [] C = [] for x, y in dp: if not G or G[-1] < x: G.append(x) C.append(y) continue if G[-1] == x: C[-1] = y for y in range(1, len(C)): if C[y-1] > C[y]: C[y] = C[y-1] ans = 0 for w in worker: idx = bisect_right(G, w)-1 if idx >= 0: ans += C[idx] return ans train APPS_structured Mr. Pr and Ms. Ad are at$a$and$b$respectively on an infinite number line. Mr. Pr wants to meet Ms. Ad. Mr. Pr can choose to move$c$or$d$units in 1 second. If Mr. Pr moves$c$units then Ms. Ad will move$d$units and vice versa. (Both of them always moved in positive x-direction) You have to determine if Mr. Pr can meet with Ms. Ad after some integral amount of time, given that Mr. Pr chooses optimally. Note that meeting after a fractional amount of time does not count. -----Input:----- - First line will contain$T$, number of testcases. Then the testcases follow. - Each testcase contains four space separated integers,$a$,$b$,$c$, and$d$. -----Output:----- - For each test case, output a single line containing "YES" if Mr. Pr meets with Ms. Ad, otherwise "NO". -----Constraints----- -$1 \leq T \leq 10^5$-$1 \leq a,b,c,d \leq 10^9$-----Sample Input:----- 2 3 4 1 2 10 20 3 7 -----Sample Output:----- YES NO -----Explanation:----- In the first test case, Mr. Pr will move 2 units in the first second and Ms. Ad moves 1 unit simultaneously and they meet. In the second test case, it is impossible to meet (fractional time is not allowed). T=int(input()) while T>0: T-=1 A,B,C,D=map(int,input().split()) res1=max(C,D) res2=min(C,D) val1=B-A val2=res2-res1 val1=abs(val1) val2=abs(val2) if val2!=0: if val1%val2==0: print("YES") else: print("NO") elif val1==0 and val2==0: print("YES") else: print("NO") T=int(input()) while T>0: T-=1 A,B,C,D=map(int,input().split()) res1=max(C,D) res2=min(C,D) val1=B-A val2=res2-res1 val1=abs(val1) val2=abs(val2) if val2!=0: if val1%val2==0: print("YES") else: print("NO") elif val1==0 and val2==0: print("YES") else: print("NO") train APPS_structured You are standing on top of an amazing Himalayan mountain. The view is absolutely breathtaking! you want to take a picture on your phone, but... your memory is full again! ok, time to sort through your shuffled photos and make some space... Given a gallery of photos, write a function to sort through your pictures. You get a random hard disk drive full of pics, you must return an array with the 5 most recent ones PLUS the next one (same year and number following the one of the last). You will always get at least a photo and all pics will be in the format YYYY.imgN Examples: python sort_photos["2016.img1","2016.img2","2015.img3","2016.img4","2013.img5"]) ==["2013.img5","2015.img3","2016.img1","2016.img2","2016.img4","2016.img5"] sort_photos["2016.img1"]) ==["2016.img1","2016.img2"]  def key(pic): parts = pic.split('.') return parts[0], int(parts[1][3:]) def sort_photos(pics): pics.sort(key=key) pics = pics[-5:] last_key = key(pics[-1]) pics.append(last_key[0] + '.img' + str(last_key[1] + 1)) return pics def key(pic): parts = pic.split('.') return parts[0], int(parts[1][3:]) def sort_photos(pics): pics.sort(key=key) pics = pics[-5:] last_key = key(pics[-1]) pics.append(last_key[0] + '.img' + str(last_key[1] + 1)) return pics train APPS_structured Bob recently read about bitwise operations used in computers: AND, OR and XOR. He have studied their properties and invented a new game. Initially, Bob chooses integer m, bit depth of the game, which means that all numbers in the game will consist of m bits. Then he asks Peter to choose some m-bit number. After that, Bob computes the values of n variables. Each variable is assigned either a constant m-bit number or result of bitwise operation. Operands of the operation may be either variables defined before, or the number, chosen by Peter. After that, Peter's score equals to the sum of all variable values. Bob wants to know, what number Peter needs to choose to get the minimum possible score, and what number he needs to choose to get the maximum possible score. In both cases, if there are several ways to get the same score, find the minimum number, which he can choose. -----Input----- The first line contains two integers n and m, the number of variables and bit depth, respectively (1 ≤ n ≤ 5000; 1 ≤ m ≤ 1000). The following n lines contain descriptions of the variables. Each line describes exactly one variable. Description has the following format: name of a new variable, space, sign ":=", space, followed by one of: Binary number of exactly m bits. The first operand, space, bitwise operation ("AND", "OR" or "XOR"), space, the second operand. Each operand is either the name of variable defined before or symbol '?', indicating the number chosen by Peter. Variable names are strings consisting of lowercase Latin letters with length at most 10. All variable names are different. -----Output----- In the first line output the minimum number that should be chosen by Peter, to make the sum of all variable values minimum possible, in the second line output the minimum number that should be chosen by Peter, to make the sum of all variable values maximum possible. Both numbers should be printed as m-bit binary numbers. -----Examples----- Input 3 3 a := 101 b := 011 c := ? XOR b Output 011 100 Input 5 1 a := 1 bb := 0 cx := ? OR a d := ? XOR ? e := d AND bb Output 0 0 -----Note----- In the first sample if Peter chooses a number 011_2, then a = 101_2, b = 011_2, c = 000_2, the sum of their values is 8. If he chooses the number 100_2, then a = 101_2, b = 011_2, c = 111_2, the sum of their values is 15. For the second test, the minimum and maximum sum of variables a, bb, cx, d and e is 2, and this sum doesn't depend on the number chosen by Peter, so the minimum Peter can choose is 0. def sumBin(a, b, varMap): lhs = varMap[a] rhs = varMap[b] return bin(int(lhs, 2) + int(rhs, 2))[2:] def andBin(a, b, varMap): lhs = varMap[a] rhs = varMap[b] return bin(int(lhs, 2) & int(rhs, 2))[2:] def orBin(a, b, varMap): lhs = varMap[a] rhs = varMap[b] return bin(int(lhs, 2) | int(rhs, 2))[2:] def xorBin(a, b, varMap): lhs = varMap[a] rhs = varMap[b] return bin(int(lhs, 2) ^ int(rhs, 2))[2:] mapOper = {'AND': andBin, 'OR': orBin, 'XOR' : xorBin} n, m = list(map(int, input().split())) minMap = {"?": "0", "": "0"} maxMap = {"?": "1"*m, "": "0"} minSum = "0" maxSum = "0" for _ in range(n): name, _, expr = input().split(' ', 2) if len(expr.split(' ')) == 1: minMap[name] = expr maxMap[name] = expr else: lhs, oper, rhs = expr.split() minMap[name] = mapOper[oper](lhs, rhs, minMap).zfill(m) maxMap[name] = mapOper[oper](lhs, rhs, maxMap).zfill(m) minSum = sumBin("", name, minMap) maxSum = sumBin("", name, maxMap) def countOnes(i, varMap): ones = 0 for name, num in list(varMap.items()): if name != "?" and name != "": ones += num[i] == "1" return ones minRes = "" maxRes = "" for i in range(m): zeroOnes = countOnes(i, minMap) oneOnes = countOnes(i, maxMap) if zeroOnes > oneOnes: maxRes += "0" minRes += "1" elif zeroOnes < oneOnes: maxRes += "1" minRes += "0" else: maxRes += "0" minRes += "0" print (minRes) print (maxRes) def sumBin(a, b, varMap): lhs = varMap[a] rhs = varMap[b] return bin(int(lhs, 2) + int(rhs, 2))[2:] def andBin(a, b, varMap): lhs = varMap[a] rhs = varMap[b] return bin(int(lhs, 2) & int(rhs, 2))[2:] def orBin(a, b, varMap): lhs = varMap[a] rhs = varMap[b] return bin(int(lhs, 2) | int(rhs, 2))[2:] def xorBin(a, b, varMap): lhs = varMap[a] rhs = varMap[b] return bin(int(lhs, 2) ^ int(rhs, 2))[2:] mapOper = {'AND': andBin, 'OR': orBin, 'XOR' : xorBin} n, m = list(map(int, input().split())) minMap = {"?": "0", "": "0"} maxMap = {"?": "1"*m, "": "0"} minSum = "0" maxSum = "0" for _ in range(n): name, _, expr = input().split(' ', 2) if len(expr.split(' ')) == 1: minMap[name] = expr maxMap[name] = expr else: lhs, oper, rhs = expr.split() minMap[name] = mapOper[oper](lhs, rhs, minMap).zfill(m) maxMap[name] = mapOper[oper](lhs, rhs, maxMap).zfill(m) minSum = sumBin("", name, minMap) maxSum = sumBin("", name, maxMap) def countOnes(i, varMap): ones = 0 for name, num in list(varMap.items()): if name != "?" and name != "": ones += num[i] == "1" return ones minRes = "" maxRes = "" for i in range(m): zeroOnes = countOnes(i, minMap) oneOnes = countOnes(i, maxMap) if zeroOnes > oneOnes: maxRes += "0" minRes += "1" elif zeroOnes < oneOnes: maxRes += "1" minRes += "0" else: maxRes += "0" minRes += "0" print (minRes) print (maxRes) train APPS_structured Create a class Vector that has simple (3D) vector operators. In your class, you should support the following operations, given Vector a and Vector b: python a + b # returns a new Vector that is the resultant of adding them a - b # same, but with subtraction a == b # returns true if they have the same magnitude and direction a.cross(b) # returns a new Vector that is the cross product of a and b a.dot(b) # returns a number that is the dot product of a and b a.to_tuple() # returns a tuple representation of the vector. str(a) # returns a string representation of the vector in the form "" a.magnitude # returns a number that is the magnitude (geometric length) of vector a. a.x # gets x component a.y # gets y component a.z # gets z component Vector([a,b,c]) # creates a new Vector from the supplied 3D array. Vector(a,b,c) # same as above  The test cases will not mutate the produced Vector objects, so don't worry about that. import math import operator class Vector: def __init__(self, *args): self.x, self.y, self.z = self.args = tuple(args[0] if len(args) == 1 else args) self.magnitude = math.sqrt(sum(i ** 2 for i in self.args)) def __str__(self): return '<{}>'.format(', '.join(map(str, self.args))) def __eq__(self, other): return self.args == other.args def __add__(self, other): return Vector(*map(operator.add, self.args, other.args)) def __sub__(self, other): return Vector(*map(operator.sub, self.args, other.args)) def dot(self, other): return sum(map(operator.mul, self.args, other.args)) def to_tuple(self): return self.args def cross(self, other): return Vector( self.y * other.z - self.z * other.y, self.z * other.x - self.x * other.z, self.x * other.y - self.y * other.x, ) import math import operator class Vector: def __init__(self, *args): self.x, self.y, self.z = self.args = tuple(args[0] if len(args) == 1 else args) self.magnitude = math.sqrt(sum(i ** 2 for i in self.args)) def __str__(self): return '<{}>'.format(', '.join(map(str, self.args))) def __eq__(self, other): return self.args == other.args def __add__(self, other): return Vector(*map(operator.add, self.args, other.args)) def __sub__(self, other): return Vector(*map(operator.sub, self.args, other.args)) def dot(self, other): return sum(map(operator.mul, self.args, other.args)) def to_tuple(self): return self.args def cross(self, other): return Vector( self.y * other.z - self.z * other.y, self.z * other.x - self.x * other.z, self.x * other.y - self.y * other.x, ) train APPS_structured # Introduction and Warm-up (Highly recommended) # [Playing With Lists/Arrays Series](https://www.codewars.com/collections/playing-with-lists-slash-arrays) ___ # Task **_Given_** an **_array of integers_** , **_Find the minimum sum_** which is obtained *from summing each Two integers product* . ___ # Notes * **_Array/list_** *will contain* **_positives only_** . * **_Array/list_** *will always has* **_even size_** ___ # Input >> Output Examples  minSum({5,4,2,3}) ==> return (22)  ## **_Explanation_**: * **_The minimum sum_** *obtained from summing each two integers product* ,  5*2 + 3*4 = 22 ___  minSum({12,6,10,26,3,24}) ==> return (342)  ## **_Explanation_**: * **_The minimum sum_** *obtained from summing each two integers product* ,  26*3 + 24*6 + 12*10 = 342 ___  minSum({9,2,8,7,5,4,0,6}) ==> return (74)  ## **_Explanation_**: * **_The minimum sum_** *obtained from summing each two integers product* ,  9*0 + 8*2 +7*4 +6*5 = 74 ___ ___ ___ ___ # [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 min_sum(arr): arr = sorted(arr) n = 0 while len(arr)>0: n += arr.pop(0)*arr.pop() return n def min_sum(arr): arr = sorted(arr) n = 0 while len(arr)>0: n += arr.pop(0)*arr.pop() return n train APPS_structured #Detail [Countdown](https://en.wikipedia.org/wiki/Countdown_(game_show) is a British game show with number and word puzzles. The letters round consists of the contestant picking 9 shuffled letters - either picking from the vowel pile or the consonant pile. The contestants are given 30 seconds to try to come up with the longest English word they can think of with the available letters - letters can not be used more than once unless there is another of the same character. #Task Given an uppercase 9 letter string, letters, find the longest word that can be made with some or all of the letters. The preloaded array words (or $words in Ruby) contains a bunch of uppercase words that you will have to loop through. Only return the longest word; if there is more than one, return the words of the same lengths in alphabetical order. If there are no words that can be made from the letters given, return None/nil/null. ##Examples  letters = "ZZZZZZZZZ" longest word = None letters = "POVMERKIA", longest word = ["VAMPIRE"] letters = "DVAVPALEM" longest word = ["VAMPED", "VALVED", "PALMED"] 
def longest_word(letters): try: word_list = [w for w in words if all(w.count(c) <= letters.count(c) for c in w)] largest = sorted([w for w in word_list if len(w) == len(max(word_list, key=len))]) return largest if largest else None except: return None
def longest_word(letters): try: word_list = [w for w in words if all(w.count(c) <= letters.count(c) for c in w)] largest = sorted([w for w in word_list if len(w) == len(max(word_list, key=len))]) return largest if largest else None except: return None
train
APPS_structured
In this Kata, you will implement the [Luhn Algorithm](http://en.wikipedia.org/wiki/Luhn_algorithm), which is used to help validate credit card numbers. Given a positive integer of up to 16 digits, return true if it is a valid credit card number, and false if it is not. Here is the algorithm: * Double every other digit, scanning **from right to left**, starting from the second digit (from the right). Another way to think about it is: if there are an **even** number of digits, double every other digit starting with the **first**; if there are an **odd** number of digits, double every other digit starting with the **second**:  1714 ==> [1*, 7, 1*, 4] ==> [2, 7, 2, 4] 12345 ==> [1, 2*, 3, 4*, 5] ==> [1, 4, 3, 8, 5] 891 ==> [8, 9*, 1] ==> [8, 18, 1]  * If a resulting number is greater than 9, replace it with the sum of its own digits (which is the same as subtracting 9 from it):  [8, 18*, 1] ==> [8, (1+8), 1] ==> [8, 9, 1] or: [8, 18*, 1] ==> [8, (18-9), 1] ==> [8, 9, 1]  * Sum all of the final digits:  [8, 9, 1] ==> 8 + 9 + 1 = 18  * Finally, take that sum and divide it by 10. If the remainder equals zero, the original credit card number is valid.  18 (modulus) 10 ==> 8 , which is not equal to 0, so this is not a valid credit card number  if:fsharp,csharp For F# and C# users: The input will be a string of spaces and digits 0..9 
import numpy as np def validate(cc_number): # split integer into array of digits arr = np.array([int(i) for i in str(cc_number)]) # double every second digit from the right arr[-2::-2] *= 2 # substract 9 from digits greater than 9 arr[arr>9] -= 9 # sum up all the digits and check the modulus 10 return np.sum(arr) % 10 == 0
import numpy as np def validate(cc_number): # split integer into array of digits arr = np.array([int(i) for i in str(cc_number)]) # double every second digit from the right arr[-2::-2] *= 2 # substract 9 from digits greater than 9 arr[arr>9] -= 9 # sum up all the digits and check the modulus 10 return np.sum(arr) % 10 == 0
train
APPS_structured
# Longest Palindromic Substring (Linear) A palindrome is a word, phrase, or sequence that reads the same backward as forward, e.g., 'madam' or 'racecar'. Even the letter 'x' is considered a palindrome. For this Kata, you are given a string s. Write a function that returns the longest _contiguous_ palindromic substring in s (it could be the entire string). In the event that there are multiple longest palindromic substrings, return the first to occur. I'm not trying to trick you here: - You can assume that all inputs are valid strings. - Only the letters a-z will be used, all lowercase (your solution should, in theory, extend to more than just the letters a-z though). **NOTE:** Quadratic asymptotic complexity _(O(N^2))_ or above will __NOT__ work here. ----- ## Examples ### Basic Tests  Input: "babad" Output: "bab" (Note: "bab" occurs before "aba")   Input: "abababa" Output: "abababa"   Input: "cbbd" Output: "bb"  ### Edge Cases  Input: "ab" Output: "a"   Input: "" Output: ""  ----- ## Testing Along with the example tests given: - There are **500** tests using strings of length in range [1 - 1,000] - There are **50** tests using strings of length in range [1,000 - 10,000] - There are **5** tests using strings of length in range [10,000 - 100,000] All test cases can be passed within 10 seconds, but non-linear solutions will time out every time. _Linear performance is essential_. ## Good Luck! ----- This problem was inspired by [this](https://leetcode.com/problems/longest-palindromic-substring/) challenge on LeetCode. Except this is the performance version :^)
''' Write a function that returns the longest contiguous palindromic substring in s. In the event that there are multiple longest palindromic substrings, return the first to occur. ''' # TODO: Complete in linear time xDD def longest_palindrome(s): if is_palindrome(s): return s max_pal = '' for i in range(len(s)): temp = check(i, i, s) if len(max_pal) < len(temp): max_pal = temp return max_pal def check(li, ri, s): if li > 0 and ri < len(s): if is_palindrome(s[li - 1: ri + 2]): return check(li - 1, ri + 1, s) elif is_palindrome(s[li: ri + 2]): return check(li, ri + 1, s) elif is_palindrome(s[li - 1: ri + 1]): return check(li - 1, ri, s) return s[li: ri + 1] def is_palindrome(s): return s == s[::-1]
''' Write a function that returns the longest contiguous palindromic substring in s. In the event that there are multiple longest palindromic substrings, return the first to occur. ''' # TODO: Complete in linear time xDD def longest_palindrome(s): if is_palindrome(s): return s max_pal = '' for i in range(len(s)): temp = check(i, i, s) if len(max_pal) < len(temp): max_pal = temp return max_pal def check(li, ri, s): if li > 0 and ri < len(s): if is_palindrome(s[li - 1: ri + 2]): return check(li - 1, ri + 1, s) elif is_palindrome(s[li: ri + 2]): return check(li, ri + 1, s) elif is_palindrome(s[li - 1: ri + 1]): return check(li - 1, ri, s) return s[li: ri + 1] def is_palindrome(s): return s == s[::-1]
train
APPS_structured
Jem is famous for his laziness at school. He always leaves things to last minute. Now Jem has N problems in the assignment of "Advanced topics in algorithm" class to solved. The assignment is due tomorrow and as you may guess he hasn't touch any of the problems. Fortunately he got a plan as always. The first step will be buying a pack of Red Bull and then to work as hard as he can. Here is how he is going to spend the remaining time: Jem will not take a break until he finishes at least half of the remaining problems. Formally, if N is even then he will take he first break after finishing N / 2 problems. If N is odd then the break will be after he done (N + 1) / 2 problems. Each of his break will last for B minutes. Initially, he takes M minutes in solving a problem, after each break he will take twice more time in solving a problem, i.e. 2 * M minutes per problem after the first break. Jem will start working soon and ask you to help him calculate how much time it will take until he finish the last problem! -----Input----- The first line contains a single integer T represents the number of test cases in the input. Each line in the next T line contains three integers N, B and M represents a test case. -----Output----- For each test case output a single line containing an integer represent how much time Jem will need (in minutes). -----Constraints----- - 1 ≤ T ≤ 100 - 1 ≤ N, B, M ≤ 108 -----Example----- Input: 2 9 1 2 123456 123456 123456 Output: 45 131351258112 -----Explanation----- In the first test case, Jem will proceed as below: - Initially, Jem has 9 problems to solve. since it is an odd number, Jem will finish the first (9 + 1) / 2 = 5 problems with speed of 2 minutes/problem. - After that, Jem takes 1 minute break. - Now he has 4 problems to solve, which is an even number, so Jem will solve the next 4 / 2 = 2 problems. his speed after the first break has now became 4 minutes/problem. - Again, he takes a 1 minute break. - he has now 2 problems left so he do one more problem in 8 minutes. - He takes 1 minute break. - he solves the last problem in 16 minutes. So, Jem will need time = 5 × 2 + 1 + 2 × 4 + 1 + 8 + 1 + 16 = 45
# cook your code here t= int(input()) while (t>0): t=t-1 T=0 N,B,M = list(map(int,input().split())) while(N!=0): T=T+ int((N+1)/2) *M + B M=2*M N= int(N/2) print(T-B)
# cook your code here t= int(input()) while (t>0): t=t-1 T=0 N,B,M = list(map(int,input().split())) while(N!=0): T=T+ int((N+1)/2) *M + B M=2*M N= int(N/2) print(T-B)
train
APPS_structured
Given an integer n, generate all structurally unique BST's (binary search trees) that store values 1 ... n. Example: Input: 3 Output: [   [1,null,3,2],   [3,2,null,1],   [3,1,null,null,2],   [2,1,3],   [1,null,2,null,3] ] Explanation: The above output corresponds to the 5 unique BST's shown below: 1 3 3 2 1 \ / / / \ \ 3 2 1 1 3 2 / / \ \ 2 1 2 3
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def generateTrees(self, n): """ :type n: int :rtype: List[TreeNode] """ if n <= 0: return [] mem = {} return self.genTrees(mem, 1, n) def genTrees(self, mem, start, end): cached = mem.get((start, end)) if cached != None: return cached if start > end: return [None] if start == end: return [TreeNode(start)] retVal = [] for i in range(start, end + 1): left = self.genTrees(mem, start, i - 1) right = self.genTrees(mem, i + 1, end) for lnode in left: for rnode in right: root = TreeNode(i) root.left = lnode root.right = rnode retVal.append(root) mem[(start, end)] = retVal return retVal
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def generateTrees(self, n): """ :type n: int :rtype: List[TreeNode] """ if n <= 0: return [] mem = {} return self.genTrees(mem, 1, n) def genTrees(self, mem, start, end): cached = mem.get((start, end)) if cached != None: return cached if start > end: return [None] if start == end: return [TreeNode(start)] retVal = [] for i in range(start, end + 1): left = self.genTrees(mem, start, i - 1) right = self.genTrees(mem, i + 1, end) for lnode in left: for rnode in right: root = TreeNode(i) root.left = lnode root.right = rnode retVal.append(root) mem[(start, end)] = retVal return retVal
train
APPS_structured
Similar setting of the [previous](https://www.codewars.com/kata/progressive-spiral-number-position/), this time you are called to identify in which "branch" of the spiral a given number will end up. Considering a square of numbers disposed as the 25 items in [the previous kata](https://www.codewars.com/kata/progressive-spiral-number-position/), the branch are numbered as it follows:  17 16 15 14 13 1 1 1 1 0 18 05 04 03 12 2 1 1 0 0 19 06 01 02 11 => 2 2 0 0 0 20 07 08 09 10 2 2 3 3 0 21 22 23 24 25 2 3 3 3 3  Meaning that, for example, numbers in the 10-13 range will be in branch 0, numbers in the range 14-17 are inside branch 1, all those nice numbers in the 18-21 can call branch 2 their house and finally the 21-25 team all falls under the 3 branch. Your function must return the number of the index of each number [1 being a special case you might consider equivalent to being in the first branch, 0], as per examples: python branch(1) == 0 #kind of special case here branch(5) == 1 branch(25) == 3 branch(30) == 0 branch(50) == 0  It might help A LOT to both solve the [previous kata](https://www.codewars.com/kata/progressive-spiral-number-position/) and to visualize the diagonals of the square. Be ready for big numbers and, as usual, inspired by [AoC](http://adventofcode.com/2017/day/3). Finally, when ready, go to compute [the distance](https://www.codewars.com/kata/progressive-spiral-number-distance/) of the series.
k, li = 1, [0] for i in range(1, 1000000): li.append(k) k += 8 * i def branch(n): a,b = next([i,li[i-1]+1] for i,j in enumerate(li) if j>=n) step = a*2-2 for i in range(4): if b<=n<b+step : return i b += step return 0
k, li = 1, [0] for i in range(1, 1000000): li.append(k) k += 8 * i def branch(n): a,b = next([i,li[i-1]+1] for i,j in enumerate(li) if j>=n) step = a*2-2 for i in range(4): if b<=n<b+step : return i b += step return 0
train
APPS_structured
Do you know that The Chef has a special interest in palindromes? Yes he does! Almost all of the dishes in his restaurant is named by a palindrome strings. The problem is that a name of a dish should not be too long, so The Chef has only limited choices when naming a new dish. For the given positive integer N, your task is to calculate the number of palindrome strings of length not exceeding N, that contain only lowercase letters of English alphabet (letters from 'a' to 'z', inclusive). Recall that a palindrome is a string that reads the same left to right as right to left (as in "radar"). For example: - For N = 1, we have 26 different palindromes of length not exceeding N: "a", "b", ..., "z". - For N = 2 we have 52 different palindromes of length not exceeding N: "a", "b", ..., "z", "aa", "bb", ..., "zz". - For N = 3 we have 728 different palindromes of length not exceeding N: "a", "b", ..., "z", "aa", "bb", ..., "zz", "aaa", "aba", ..., "aza", "bab", "bbb", ..., "bzb", ..., "zaz", "zbz", ..., "zzz". Since the answer can be quite large you should output it modulo 1000000007 (109 + 7). Yes, we know, most of you already hate this modulo, but there is nothing we can do with it :) -----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 a single integer N. -----Output----- For each test case, output a single line containing the answer for the corresponding test case. -----Constrains----- - 1 ≤ T ≤ 1000 - 1 ≤ N ≤ 109 -----Example----- Input: 5 1 2 3 4 100 Output: 26 52 728 1404 508533804 -----Explanation----- The first three examples are explained in the problem statement above.
mod=1000000007 for _ in range(int(input())): n=int(input()) if n==1: print(26) elif n==2: print(52) else: k=-(-n//2) if n%2==0: ans=26*(1+26*(pow(26,k-1,mod)-1)*pow(26-1,mod-2,mod))+26*(1+26*(pow(26,k-1,mod)-1)*pow(26-1,mod-2,mod)) else: ans=26*(1+26*(pow(26,k-1,mod)-1)*pow(26-1,mod-2,mod))+26*(1+26*(pow(26,k-2,mod)-1)*pow(26-1,mod-2,mod)) print(ans%mod)
mod=1000000007 for _ in range(int(input())): n=int(input()) if n==1: print(26) elif n==2: print(52) else: k=-(-n//2) if n%2==0: ans=26*(1+26*(pow(26,k-1,mod)-1)*pow(26-1,mod-2,mod))+26*(1+26*(pow(26,k-1,mod)-1)*pow(26-1,mod-2,mod)) else: ans=26*(1+26*(pow(26,k-1,mod)-1)*pow(26-1,mod-2,mod))+26*(1+26*(pow(26,k-2,mod)-1)*pow(26-1,mod-2,mod)) print(ans%mod)
train
APPS_structured
We define the "unfairness" of a list/array as the *minimal* difference between max(x1,x2,...xk) and min(x1,x2,...xk), for all possible combinations of k elements you can take from the list/array; both minimum and maximum of an empty list/array are considered to be 0. **More info and constraints:** * lists/arrays can contain values repeated more than once, plus there are usually more combinations that generate the required minimum; * the list/array's length can be any value from 0 to 10^(6); * the value of k will range from 0 to the length of the list/array, * the minimum unfairness of an array/list with less than 2 elements is 0. For example: python min_unfairness([30,100,1000,150,60,250,10,120,20],3)==20 #from max(30,10,20)-min(30,10,20)==20, minimum unfairness in this sample min_unfairness([30,100,1000,150,60,250,10,120,20],5)==90 #from max(30,100,60,10,20)-min(30,100,60,10,20)==90, minimum unfairness in this sample min_unfairness([1,1,1,1,1,1,1,1,1,2,2,2,2,2,2],10)==1 #from max(1,1,1,1,1,1,1,1,1,2)-min(1,1,1,1,1,1,1,1,1,2)==1, minimum unfairness in this sample min_unfairness([1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1],10)==0 #from max(1,1,1,1,1,1,1,1,1,1)-min(1,1,1,1,1,1,1,1,1,1)==0, minimum unfairness in this sample min_unfairness([1,1,-1],2)==0 #from max(1,1)-min(1,1)==0, minimum unfairness in this sample  **Note:** shamelessly taken from [here](https://www.hackerrank.com/challenges/angry-children), where it was created and debatably categorized and ranked.
min_unfairness=lambda a,k:a.sort()or k>0<len(a)and min(b-a for a,b in zip(a,a[k-1:]))
min_unfairness=lambda a,k:a.sort()or k>0<len(a)and min(b-a for a,b in zip(a,a[k-1:]))
train
APPS_structured
Write the following function: python def area_of_polygon_inside_circle(circle_radius, number_of_sides):  It should calculate the area of a regular polygon of numberOfSides, number-of-sides, or number_of_sides sides inside a circle of radius circleRadius, circle-radius, or circle_radius which passes through all the vertices of the polygon (such circle is called [**circumscribed circle** or **circumcircle**](https://en.wikipedia.org/wiki/Circumscribed_circle)). The answer should be a number rounded to 3 decimal places. Input :: Output Examples python area_of_polygon_inside_circle(3, 3) # returns 11.691 area_of_polygon_inside_circle(5.8, 7) # returns 92.053 area_of_polygon_inside_circle(4, 5) # returns 38.042 
import math def area_of_polygon_inside_circle(circle_radius, number_of_sides): r = circle_radius s = number_of_sides a = (s * (r ** 2) * math.sin(2*math.pi/s))/2 return round(a, 3)
import math def area_of_polygon_inside_circle(circle_radius, number_of_sides): r = circle_radius s = number_of_sides a = (s * (r ** 2) * math.sin(2*math.pi/s))/2 return round(a, 3)
train
APPS_structured
You are given set of n points in 5-dimensional space. The points are labeled from 1 to n. No two points coincide. We will call point a bad if there are different points b and c, not equal to a, from the given set such that angle between vectors $\vec{ab}$ and $\vec{ac}$ is acute (i.e. strictly less than $90^{\circ}$). Otherwise, the point is called good. The angle between vectors $\vec{x}$ and $\vec{y}$ in 5-dimensional space is defined as $\operatorname{arccos}(\frac{\vec{x} \cdot \vec{y}}{|\vec{x}||\vec{y}|})$, where $\vec{x} \cdot \vec{y} = x_{1} y_{1} + x_{2} y_{2} + x_{3} y_{3} + x_{4} y_{4} + x_{5} y_{5}$ is the scalar product and $|\vec{x}|= \sqrt{\vec{x} \cdot \vec{x}}$ is length of $\vec{x}$. Given the list of points, print the indices of the good points in ascending order. -----Input----- The first line of input contains a single integer n (1 ≤ n ≤ 10^3) — the number of points. The next n lines of input contain five integers a_{i}, b_{i}, c_{i}, d_{i}, e_{i} (|a_{i}|, |b_{i}|, |c_{i}|, |d_{i}|, |e_{i}| ≤ 10^3)  — the coordinates of the i-th point. All points are distinct. -----Output----- First, print a single integer k — the number of good points. Then, print k integers, each on their own line — the indices of the good points in ascending order. -----Examples----- Input 6 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 1 Output 1 1 Input 3 0 0 1 2 0 0 0 9 2 0 0 0 5 9 0 Output 0 -----Note----- In the first sample, the first point forms exactly a $90^{\circ}$ angle with all other pairs of points, so it is good. In the second sample, along the cd plane, we can see the points look as follows: [Image] We can see that all angles here are acute, so no points are good.
from math import acos,sqrt,pi def norm(x): if x==0: return 0 else: return sqrt(scalar(x,x)) def scalar(x,y): return sum([x[i]*y[i] for i in range(5)]) def vector(p,q): return ([ (q[i]-p[i]) for i in range(5) ]) number=0 good_points=[] n=int(input()) liste=[] for _ in range(n): x=list(map(int,input().split(" "))) liste.append(x) if n>11: print(0) else: for i in range(n): bool=True for j in range(n): if j!=i: for k in range(n): if k!=j and k!=i: x=vector(liste[i],liste[j]) y=vector(liste[i],liste[k]) angle=acos(scalar(x,y)/norm(x)/norm(y)) if angle<pi/2: bool=False if bool: good_points.append(i+1) number+=1 if number>0: answer=str(number)+' ' good_points.sort() for element in good_points: answer+='\n'+str(element) print(answer) else: print(0)
from math import acos,sqrt,pi def norm(x): if x==0: return 0 else: return sqrt(scalar(x,x)) def scalar(x,y): return sum([x[i]*y[i] for i in range(5)]) def vector(p,q): return ([ (q[i]-p[i]) for i in range(5) ]) number=0 good_points=[] n=int(input()) liste=[] for _ in range(n): x=list(map(int,input().split(" "))) liste.append(x) if n>11: print(0) else: for i in range(n): bool=True for j in range(n): if j!=i: for k in range(n): if k!=j and k!=i: x=vector(liste[i],liste[j]) y=vector(liste[i],liste[k]) angle=acos(scalar(x,y)/norm(x)/norm(y)) if angle<pi/2: bool=False if bool: good_points.append(i+1) number+=1 if number>0: answer=str(number)+' ' good_points.sort() for element in good_points: answer+='\n'+str(element) print(answer) else: print(0)
train
APPS_structured
Write a function that accepts two square matrices (N x N two dimensional arrays), and return the sum of the two. Both matrices being passed into the function will be of size N x N (square), containing only integers. How to sum two matrices: Take each cell [n][m] from the first matrix, and add it with the same [n][m] cell from the second matrix. This will be cell [n][m] of the solution matrix. Visualization:  |1 2 3| |2 2 1| |1+2 2+2 3+1| |3 4 4| |3 2 1| + |3 2 3| = |3+3 2+2 1+3| = |6 4 4| |1 1 1| |1 1 3| |1+1 1+1 1+3| |2 2 4|  ## Example
import numpy as np def matrix_addition(a, b): S = np.array(a) + np.array(b) return S.tolist()
import numpy as np def matrix_addition(a, b): S = np.array(a) + np.array(b) return S.tolist()
train
APPS_structured
AtCoDeer the deer found N rectangle lying on the table, each with height 1. If we consider the surface of the desk as a two-dimensional plane, the i-th rectangle i(1≤i≤N) covers the vertical range of [i-1,i] and the horizontal range of [l_i,r_i], as shown in the following figure: AtCoDeer will move these rectangles horizontally so that all the rectangles are connected. For each rectangle, the cost to move it horizontally by a distance of x, is x. Find the minimum cost to achieve connectivity. It can be proved that this value is always an integer under the constraints of the problem. -----Constraints----- - All input values are integers. - 1≤N≤10^5 - 1≤l_i<r_i≤10^9 -----Partial Score----- - 300 points will be awarded for passing the test set satisfying 1≤N≤400 and 1≤l_i<r_i≤400. -----Input----- The input is given from Standard Input in the following format: N l_1 r_1 l_2 r_2 : l_N r_N -----Output----- Print the minimum cost to achieve connectivity. -----Sample Input----- 3 1 3 5 7 1 3 -----Sample Output----- 2 The second rectangle should be moved to the left by a distance of 2.
# seishin.py N = int(input()) P = [list(map(int, input().split())) for i in range(N)] INF = 10**18 from heapq import heappush, heappop l0, r0 = P[0] L = [-l0+1] R = [l0-1] s = t = 0 def debug(L, s, t, R): L0 = L[:] Q1 = []; Q2 = [] while L0: Q1.append(-s-heappop(L0)) R0 = R[:] while R0: Q2.append(t+heappop(R0)) print(("debug:", *Q1[::-1]+Q2)) #print(L, s, t, R) res = 0 for i in range(N-1): l0, r0 = P[i] l1, r1 = P[i+1] #print(">", l1, r1) s += (r1 - l1); t += (r0 - l0) if -s-L[0] <= l1-1 <= t+R[0]: #print(0) heappush(L, -l1+1-s) heappush(R, l1-1-t) # res += 0 elif l1-1 < -s-L[0]: #print(1) heappush(L, -l1+1-s) heappush(L, -l1+1-s) p = -heappop(L)-s #d = (-L[0]-s) - p heappush(R, p-t) #print(d) #res += d res += (p - (l1-1)) elif t+R[0] < l1-1: #print(2) heappush(R, l1-1-t) heappush(R, l1-1-t) p = heappop(R) + t #d = R[0]+t - p heappush(L, -p-s) #print(d) res += (l1-1 - p) #print(L, s, t, R, -s-L[0], R[0]+t, res) #debug(L, s, t, R) print(res)
# seishin.py N = int(input()) P = [list(map(int, input().split())) for i in range(N)] INF = 10**18 from heapq import heappush, heappop l0, r0 = P[0] L = [-l0+1] R = [l0-1] s = t = 0 def debug(L, s, t, R): L0 = L[:] Q1 = []; Q2 = [] while L0: Q1.append(-s-heappop(L0)) R0 = R[:] while R0: Q2.append(t+heappop(R0)) print(("debug:", *Q1[::-1]+Q2)) #print(L, s, t, R) res = 0 for i in range(N-1): l0, r0 = P[i] l1, r1 = P[i+1] #print(">", l1, r1) s += (r1 - l1); t += (r0 - l0) if -s-L[0] <= l1-1 <= t+R[0]: #print(0) heappush(L, -l1+1-s) heappush(R, l1-1-t) # res += 0 elif l1-1 < -s-L[0]: #print(1) heappush(L, -l1+1-s) heappush(L, -l1+1-s) p = -heappop(L)-s #d = (-L[0]-s) - p heappush(R, p-t) #print(d) #res += d res += (p - (l1-1)) elif t+R[0] < l1-1: #print(2) heappush(R, l1-1-t) heappush(R, l1-1-t) p = heappop(R) + t #d = R[0]+t - p heappush(L, -p-s) #print(d) res += (l1-1 - p) #print(L, s, t, R, -s-L[0], R[0]+t, res) #debug(L, s, t, R) print(res)
train
APPS_structured
We have a tree with N vertices, whose i-th edge connects Vertex u_i and Vertex v_i. Vertex i has an integer a_i written on it. For every integer k from 1 through N, solve the following problem: - We will make a sequence by lining up the integers written on the vertices along the shortest path from Vertex 1 to Vertex k, in the order they appear. Find the length of the longest increasing subsequence of this sequence. Here, the longest increasing subsequence of a sequence A of length L is the subsequence A_{i_1} , A_{i_2} , ... , A_{i_M} with the greatest possible value of M such that 1 \leq i_1 < i_2 < ... < i_M \leq L and A_{i_1} < A_{i_2} < ... < A_{i_M}. -----Constraints----- - 2 \leq N \leq 2 \times 10^5 - 1 \leq a_i \leq 10^9 - 1 \leq u_i , v_i \leq N - u_i \neq v_i - The given graph is a tree. - All values in input are integers. -----Input----- Input is given from Standard Input in the following format: N a_1 a_2 ... a_N u_1 v_1 u_2 v_2 : u_{N-1} v_{N-1} -----Output----- Print N lines. The k-th line, print the length of the longest increasing subsequence of the sequence obtained from the shortest path from Vertex 1 to Vertex k. -----Sample Input----- 10 1 2 5 3 4 6 7 3 2 4 1 2 2 3 3 4 4 5 3 6 6 7 1 8 8 9 9 10 -----Sample Output----- 1 2 3 3 4 4 5 2 2 3 For example, the sequence A obtained from the shortest path from Vertex 1 to Vertex 5 is 1,2,5,3,4. Its longest increasing subsequence is A_1, A_2, A_4, A_5, with the length of 4.
import math import bisect n = int(input()) alist = [0]+list(map(int,input().split())) uv_list = [] for i in range(n-1): u,v = list(map(int,input().split())) if u > v: u, v = v, u uv_list.append([u,v]) tree = [[] for _ in range(n+1)] for i in range(n-1): uv = uv_list[i] tree[uv[0]].append(uv[1]) tree[uv[1]].append(uv[0]) queue = [1] used = [0]*(n+1) ans = [0]*(n+1) dp = [] stack = [] while queue != []: cur = queue[-1] if used[cur] == 0: if cur == 1: dp.append(alist[cur]) stack.append([len(dp)-1,None]) else: if alist[cur] > dp[-1]: dp.append(alist[cur]) stack.append([len(dp)-1,None]) else: offset = bisect.bisect_left(dp,alist[cur]) stack.append([offset,dp[offset]]) dp[offset] = alist[cur] ans[cur] = len(dp) if tree[cur] != [] and used[cur] == 0: for child in tree[cur]: if used[child] == 0: queue.append(child) else: queue.pop() #reverse back = stack.pop() if back[1] == None: dp.pop() else: dp[back[0]] = back[1] used[cur] = 1 for i in range(n): print((ans[i+1]))
import math import bisect n = int(input()) alist = [0]+list(map(int,input().split())) uv_list = [] for i in range(n-1): u,v = list(map(int,input().split())) if u > v: u, v = v, u uv_list.append([u,v]) tree = [[] for _ in range(n+1)] for i in range(n-1): uv = uv_list[i] tree[uv[0]].append(uv[1]) tree[uv[1]].append(uv[0]) queue = [1] used = [0]*(n+1) ans = [0]*(n+1) dp = [] stack = [] while queue != []: cur = queue[-1] if used[cur] == 0: if cur == 1: dp.append(alist[cur]) stack.append([len(dp)-1,None]) else: if alist[cur] > dp[-1]: dp.append(alist[cur]) stack.append([len(dp)-1,None]) else: offset = bisect.bisect_left(dp,alist[cur]) stack.append([offset,dp[offset]]) dp[offset] = alist[cur] ans[cur] = len(dp) if tree[cur] != [] and used[cur] == 0: for child in tree[cur]: if used[child] == 0: queue.append(child) else: queue.pop() #reverse back = stack.pop() if back[1] == None: dp.pop() else: dp[back[0]] = back[1] used[cur] = 1 for i in range(n): print((ans[i+1]))
train
APPS_structured
=====Function Descriptions===== collections.deque() A deque is a double-ended queue. It can be used to add or remove elements from both ends. Deques support thread safe, memory efficient appends and pops from either side of the deque with approximately the same O(1) performance in either direction. Example Code >>> from collections import deque >>> d = deque() >>> d.append(1) >>> print d deque([1]) >>> d.appendleft(2) >>> print d deque([2, 1]) >>> d.clear() >>> print d deque([]) >>> d.extend('1') >>> print d deque(['1']) >>> d.extendleft('234') >>> print d deque(['4', '3', '2', '1']) >>> d.count('1') 1 >>> d.pop() '1' >>> print d deque(['4', '3', '2']) >>> d.popleft() '4' >>> print d deque(['3', '2']) >>> d.extend('7896') >>> print d deque(['3', '2', '7', '8', '9', '6']) >>> d.remove('2') >>> print d deque(['3', '7', '8', '9', '6']) >>> d.reverse() >>> print d deque(['6', '9', '8', '7', '3']) >>> d.rotate(3) >>> print d deque(['8', '7', '3', '6', '9']) =====Problem Statement===== Perform append, pop, popleft and appendleft methods on an empty deque d. =====Input Format===== The first line contains an integer N, the number of operations. The next N lines contains the space separated names of methods and their values. =====Constraints===== 0<N≤100 =====Output Format===== Print the space separated elements of deque d.
#!/usr/bin/env python3 from collections import deque def __starting_point(): num = int(input().strip()) deq = deque() for _ in range(num): args = input().strip().split() if args[0] == 'append': deq.append(args[1]) elif args[0] == 'appendleft': deq.appendleft(args[1]) elif args[0] == 'pop': deq.pop() elif args[0] == 'popleft': deq.popleft() out = [] for el in deq: out.append(el) print(" ".join(map(str, out))) __starting_point()
#!/usr/bin/env python3 from collections import deque def __starting_point(): num = int(input().strip()) deq = deque() for _ in range(num): args = input().strip().split() if args[0] == 'append': deq.append(args[1]) elif args[0] == 'appendleft': deq.appendleft(args[1]) elif args[0] == 'pop': deq.pop() elif args[0] == 'popleft': deq.popleft() out = [] for el in deq: out.append(el) print(" ".join(map(str, out))) __starting_point()
train
APPS_structured
Given a string S and a string T, find the minimum window in S which will contain all the characters in T in complexity O(n). Example: Input: S = "ADOBECODEBANC", T = "ABC" Output: "BANC" Note: If there is no such window in S that covers all characters in T, return the empty string "". If there is such window, you are guaranteed that there will always be only one unique minimum window in S.
class Solution: def minWindow(self, s, t): """ :type s: str :type t: str :rtype: str """ # assume t doesn't have duplicated chars left=-1 right = 0 result = "" totalMatch = 0 d = {} for c in t: d[c] = d.get(c, 0) + 1 for right in range(len(s)): c = s[right] if c in d: d[c]-=1 if d[c] >=0: # good match totalMatch +=1 if left == -1: left = right #find a sustring if totalMatch == len(t): if result == "" or len(result) > right - left: result = s[left: right+1] d[s[left]]+=1 totalMatch -=1 while left<right: left +=1 if s[left] in d: if d[s[left]] <0: # skip over matched letter d[s[left]] +=1 else: break elif c == s[left]: d[c]+=1 while left < right: left +=1 # skip over matched letter if s[left] in d: if d[s[left]] <0: d[s[left]] +=1 else: break return result
class Solution: def minWindow(self, s, t): """ :type s: str :type t: str :rtype: str """ # assume t doesn't have duplicated chars left=-1 right = 0 result = "" totalMatch = 0 d = {} for c in t: d[c] = d.get(c, 0) + 1 for right in range(len(s)): c = s[right] if c in d: d[c]-=1 if d[c] >=0: # good match totalMatch +=1 if left == -1: left = right #find a sustring if totalMatch == len(t): if result == "" or len(result) > right - left: result = s[left: right+1] d[s[left]]+=1 totalMatch -=1 while left<right: left +=1 if s[left] in d: if d[s[left]] <0: # skip over matched letter d[s[left]] +=1 else: break elif c == s[left]: d[c]+=1 while left < right: left +=1 # skip over matched letter if s[left] in d: if d[s[left]] <0: d[s[left]] +=1 else: break return result
train
APPS_structured
In a given 2D binary array A, there are two islands.  (An island is a 4-directionally connected group of 1s not connected to any other 1s.) Now, we may change 0s to 1s so as to connect the two islands together to form 1 island. Return the smallest number of 0s that must be flipped.  (It is guaranteed that the answer is at least 1.) Example 1: Input: A = [[0,1],[1,0]] Output: 1 Example 2: Input: A = [[0,1,0],[0,0,0],[0,0,1]] Output: 2 Example 3: Input: A = [[1,1,1,1,1],[1,0,0,0,1],[1,0,1,0,1],[1,0,0,0,1],[1,1,1,1,1]] Output: 1 Constraints: 2 <= A.length == A[0].length <= 100 A[i][j] == 0 or A[i][j] == 1
class Solution: def shortestBridge(self, A: List[List[int]]) -> int: N, M = len(A), len(A[0]) def labelIsland(i, j): stack = [(i,j)] visited = {(i,j)} while stack: x, y = stack.pop() A[x][y] = 2 for nx, ny in [(x-1,y), (x+1,y), (x,y-1), (x,y+1)]: if 0 <= nx < N and 0 <= ny < M and (nx,ny) not in visited: if A[nx][ny] == 1: visited.add((nx,ny)) stack.append((nx, ny)) return visited def bfs(source) -> int: queue = collections.deque([(0, x[0], x[1]) for x in source]) visited = source ans = math.inf while queue: dist, x, y = queue.popleft() for nx, ny in [(x-1,y), (x+1,y), (x,y-1), (x,y+1)]: if 0 <= nx < N and 0 <= ny < M and (nx,ny) not in visited: if A[nx][ny] == 1: return dist else: visited.add((nx,ny)) queue.append((dist+1, nx, ny)) return ans ans = math.inf for i in range(N): for j in range(M): if A[i][j] == 1: source = labelIsland(i,j) return bfs(source)
class Solution: def shortestBridge(self, A: List[List[int]]) -> int: N, M = len(A), len(A[0]) def labelIsland(i, j): stack = [(i,j)] visited = {(i,j)} while stack: x, y = stack.pop() A[x][y] = 2 for nx, ny in [(x-1,y), (x+1,y), (x,y-1), (x,y+1)]: if 0 <= nx < N and 0 <= ny < M and (nx,ny) not in visited: if A[nx][ny] == 1: visited.add((nx,ny)) stack.append((nx, ny)) return visited def bfs(source) -> int: queue = collections.deque([(0, x[0], x[1]) for x in source]) visited = source ans = math.inf while queue: dist, x, y = queue.popleft() for nx, ny in [(x-1,y), (x+1,y), (x,y-1), (x,y+1)]: if 0 <= nx < N and 0 <= ny < M and (nx,ny) not in visited: if A[nx][ny] == 1: return dist else: visited.add((nx,ny)) queue.append((dist+1, nx, ny)) return ans ans = math.inf for i in range(N): for j in range(M): if A[i][j] == 1: source = labelIsland(i,j) return bfs(source)
train
APPS_structured
Given an array which consists of non-negative integers and an integer m, you can split the array into m non-empty continuous subarrays. Write an algorithm to minimize the largest sum among these m subarrays. Note: If n is the length of array, assume the following constraints are satisfied: 1 ≤ n ≤ 1000 1 ≤ m ≤ min(50, n) Examples: Input: nums = [7,2,5,10,8] m = 2 Output: 18 Explanation: There are four ways to split nums into two subarrays. The best way is to split it into [7,2,5] and [10,8], where the largest sum among the two subarrays is only 18.
class Solution: def splitArray(self, nums, m): """ :type nums: List[int] :type m: int :rtype: int """ accum = [0] N = len(nums) mmm = max(nums) if m >= N: return mmm res = 0 for i in nums: res += i accum.append(res) lower, upper = mmm , sum(nums) while lower < upper: mid = (lower + upper) // 2 if not self.isSplitable(accum, m, mid): lower = mid + 1 else: upper = mid # print(lower, upper) return upper def isSplitable(self, accum, m, maxx): start = 0 N = len(accum) end = 0 count = 0 while end < N and count < m: if accum[end] - accum[start] > maxx: # print('start: ', start, 'end:', end, 'sum', accum[end - 1] - accum[start]) start = end - 1 count += 1 end += 1 #print (count, end) if accum[-1] - accum[start] > maxx: #收尾 count += 2 else: count += 1 # print('start: ', start, 'end:', end, 'sum', accum[end - 1] - accum[start]) # print (end, count) if end != N or count > m: return False return True
class Solution: def splitArray(self, nums, m): """ :type nums: List[int] :type m: int :rtype: int """ accum = [0] N = len(nums) mmm = max(nums) if m >= N: return mmm res = 0 for i in nums: res += i accum.append(res) lower, upper = mmm , sum(nums) while lower < upper: mid = (lower + upper) // 2 if not self.isSplitable(accum, m, mid): lower = mid + 1 else: upper = mid # print(lower, upper) return upper def isSplitable(self, accum, m, maxx): start = 0 N = len(accum) end = 0 count = 0 while end < N and count < m: if accum[end] - accum[start] > maxx: # print('start: ', start, 'end:', end, 'sum', accum[end - 1] - accum[start]) start = end - 1 count += 1 end += 1 #print (count, end) if accum[-1] - accum[start] > maxx: #收尾 count += 2 else: count += 1 # print('start: ', start, 'end:', end, 'sum', accum[end - 1] - accum[start]) # print (end, count) if end != N or count > m: return False return True
train
APPS_structured
Chef has just started Programming, he is in first year of Engineering. Chef is reading about Relational Operators. Relational Operators are operators which check relatioship between two values. Given two numerical values A and B you need to help chef in finding the relationship between them that is, - First one is greater than second or, - First one is less than second or, - First and second one are equal. -----Input----- First line contains an integer T, which denotes the number of testcases. Each of the T lines contain two integers A and B. -----Output----- For each line of input produce one line of output. This line contains any one of the relational operators '<' , '>' , '='. -----Constraints----- - 1 ≤ T ≤ 10000 - 1 ≤ A, B ≤ 1000000001 -----Example----- Input: 3 10 20 20 10 10 10 Output: < > = -----Explanation----- Example case 1. In this example 1 as 10 is lesser than 20.
N=int(input()) for i in range(N): a,b=list(map(int,input().split())) if(a<b): print('<') elif(a>b): print('>') else: print('=')
N=int(input()) for i in range(N): a,b=list(map(int,input().split())) if(a<b): print('<') elif(a>b): print('>') else: print('=')
train
APPS_structured
Given a string S of lowercase letters, a duplicate removal consists of choosing two adjacent and equal letters, and removing them. We repeatedly make duplicate removals on S until we no longer can. Return the final string after all such duplicate removals have been made.  It is guaranteed the answer is unique. Example 1: Input: "abbaca" Output: "ca" Explanation: For example, in "abbaca" we could remove "bb" since the letters are adjacent and equal, and this is the only possible move.  The result of this move is that the string is "aaca", of which only "aa" is possible, so the final string is "ca". Note: 1 <= S.length <= 20000 S consists only of English lowercase letters.
class Solution: def removeDuplicates(self, S: str) -> str: ## stack application stack = [] for i in S: if not stack: stack.append(i) elif i == stack[-1]: stack.pop() else: stack.append(i) return ''.join(stack)
class Solution: def removeDuplicates(self, S: str) -> str: ## stack application stack = [] for i in S: if not stack: stack.append(i) elif i == stack[-1]: stack.pop() else: stack.append(i) return ''.join(stack)
train
APPS_structured
Assume that you started to store items in progressively expanding square location, like this for the first 9 numbers:  05 04 03 06 01 02 07 08 09  And like this for the expanding to include up to the first 25 numbers:  17 16 15 14 13 18 05 04 03 12 19 06 01 02 11 20 07 08 09 10 21 22 23 24 25  You might easily notice that the first - and innermost - layer containes only one number (01), the second one - immediately around it - contains 8 numbers (number in the 02-09 range) and so on. Your task is to create a function that given a number n simply returns the number of layers required to store up to n (included). python layers(1) == 1 layers(5) == 2 layers(25) == 3 layers(30) == 4 layers(50) == 5  **Fair warning:** you will always and only get positive integers, but be ready for bigger numbers in the tests! If you had fun with this, also try some follow up kata: [progressive spiral number branch](https://www.codewars.com/kata/progressive-spiral-number-branch/) and [progressive spiral number distance](https://www.codewars.com/kata/progressive-spiral-number-distance/). *[Base idea taken from [here](http://adventofcode.com/2017/day/3)]*
def layers(n): return int(((n - 1)**0.5 + 1) // 2) + 1
def layers(n): return int(((n - 1)**0.5 + 1) // 2) + 1
train
APPS_structured
Given two arrays nums1 and nums2. Return the maximum dot product between non-empty subsequences of nums1 and nums2 with the same length. A subsequence of a array is a new array which is formed from the original array by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (ie, [2,3,5] is a subsequence of [1,2,3,4,5] while [1,5,3] is not). Example 1: Input: nums1 = [2,1,-2,5], nums2 = [3,0,-6] Output: 18 Explanation: Take subsequence [2,-2] from nums1 and subsequence [3,-6] from nums2. Their dot product is (2*3 + (-2)*(-6)) = 18. Example 2: Input: nums1 = [3,-2], nums2 = [2,-6,7] Output: 21 Explanation: Take subsequence [3] from nums1 and subsequence [7] from nums2. Their dot product is (3*7) = 21. Example 3: Input: nums1 = [-1,-1], nums2 = [1,1] Output: -1 Explanation: Take subsequence [-1] from nums1 and subsequence [1] from nums2. Their dot product is -1. Constraints: 1 <= nums1.length, nums2.length <= 500 -1000 <= nums1[i], nums2[i] <= 1000
class Solution: def maxDotProduct(self, nums1, nums2): if all(x >= 0 for x in nums1) and all(y <= 0 for y in nums2): return min(nums1) * max(nums2) if all(x <= 0 for x in nums1) and all(y >= 0 for y in nums2): return max(nums1) * min(nums2) a, b = len(nums1), len(nums2) dp = [[0 for _ in range(b)] for _ in range(a)] for i in range(a): for j in range(b): dp[i][j] = nums1[i] * nums2[j] if i: dp[i][j] = max(dp[i][j], dp[i-1][j]) if j: dp[i][j] = max(dp[i][j], dp[i][j-1]) if i and j: dp[i][j] = max(dp[i][j], nums1[i] * nums2[j] + dp[i-1][j-1]) return dp[a-1][b-1]
class Solution: def maxDotProduct(self, nums1, nums2): if all(x >= 0 for x in nums1) and all(y <= 0 for y in nums2): return min(nums1) * max(nums2) if all(x <= 0 for x in nums1) and all(y >= 0 for y in nums2): return max(nums1) * min(nums2) a, b = len(nums1), len(nums2) dp = [[0 for _ in range(b)] for _ in range(a)] for i in range(a): for j in range(b): dp[i][j] = nums1[i] * nums2[j] if i: dp[i][j] = max(dp[i][j], dp[i-1][j]) if j: dp[i][j] = max(dp[i][j], dp[i][j-1]) if i and j: dp[i][j] = max(dp[i][j], nums1[i] * nums2[j] + dp[i-1][j-1]) return dp[a-1][b-1]
train
APPS_structured
The chef is trying to solve some pattern problems, Chef wants your help to code it. Chef has one number K to form a new pattern. Help the chef to code this pattern problem. -----Input:----- - First-line will contain $T$, the number of test cases. Then the test cases follow. - Each test case contains a single line of input, one integer $K$. -----Output:----- For each test case, output as the pattern. -----Constraints----- - $1 \leq T \leq 100$ - $1 \leq K \leq 100$ -----Sample Input:----- 3 2 3 4 -----Sample Output:----- 0 *1 **2 0 *1 **2 ***3 0 *1 **2 ***3 ****4 -----EXPLANATION:----- No need, else pattern can be decode easily.
# cook your dish here for _ in range(int(input())): n=int(input()) print("0") for i in range(1,n+1): for j in range(i): print("*",end="") print(i)
# cook your dish here for _ in range(int(input())): n=int(input()) print("0") for i in range(1,n+1): for j in range(i): print("*",end="") print(i)
train
APPS_structured
In this Kata, you will be given an integer n and your task will be to return the largest integer that is <= n and has the highest digit sum. For example:  solve(100) = 99. Digit Sum for 99 = 9 + 9 = 18. No other number <= 100 has a higher digit sum. solve(10) = 9 solve(48) = 48. Note that 39 is also an option, but 48 is larger.  Input range is 0 < n < 1e11 More examples in the test cases. Good luck!
def solve(n): b = [int(str(n)[0]) - 1] + [9 for x in str(n)[1:]] digsum = sum(b) if digsum <= sum([int(x) for x in str(n)]): return n for i in range(len(str(n))-1, -1, -1): a = [int(x) for x in str(n)[:i]] + [int(str(n)[i]) - 1] + [9 for x in str(n)[i+1:]] print((i,a)) if sum(a) == digsum: break return int("".join([str(x) for x in a]))
def solve(n): b = [int(str(n)[0]) - 1] + [9 for x in str(n)[1:]] digsum = sum(b) if digsum <= sum([int(x) for x in str(n)]): return n for i in range(len(str(n))-1, -1, -1): a = [int(x) for x in str(n)[:i]] + [int(str(n)[i]) - 1] + [9 for x in str(n)[i+1:]] print((i,a)) if sum(a) == digsum: break return int("".join([str(x) for x in a]))
train
APPS_structured
The chef was playing with numbers and he found that natural number N can be obtained by sum various unique natural numbers, For challenging himself chef wrote one problem statement, which he decided to solve in future. Problem statement: N can be obtained as the sum of Kth power of integers in multiple ways, find total number ways? After that Cheffina came and read what chef wrote in the problem statement, for having some fun Cheffina made some changes in the problem statement as. New problem statement: N can be obtained as the sum of Kth power of unique +ve integers in multiple ways, find total number ways? But, the chef is now confused, how to solve a new problem statement, help the chef to solve this new problem statement. -----Input:----- - First-line will contain $T$, the number of test cases. Then the test cases follow. - Each test case contains a single line of input, two integers $N, K$. -----Output:----- For each test case, output in a single line answer to the problem statement. -----Constraints----- - $1 \leq T \leq 10$ - $1 \leq N \leq 1000$ - $1 \leq K \leq 6$ -----Sample Input:----- 2 4 1 38 2 -----Sample Output:----- 2 1 -----EXPLANATION:----- For 1) 4 can be obtained by as [ 4^1 ], [1^1, 3^1], [2^1, 2^1]. (here ^ stands for power) But here [2^1, 2^1] is not the valid way because it is not made up of unique +ve integers. For 2) 38 can be obtained in the way which is [2^2, 3^2, 5^2] = 4 + 9 + 25
for _ in range(int(input())): x,n = map(int,input().split()) reach = [0]*(x+1) reach[0] = 1 i=1 while i**n<=x: j = 1 while j+i**n<=x: j+=1 j-=1 while j>=0: if reach[j]>0: reach[j+i**n]+=reach[j] j-=1 i+=1 #print(reach) print(reach[-1])
for _ in range(int(input())): x,n = map(int,input().split()) reach = [0]*(x+1) reach[0] = 1 i=1 while i**n<=x: j = 1 while j+i**n<=x: j+=1 j-=1 while j>=0: if reach[j]>0: reach[j+i**n]+=reach[j] j-=1 i+=1 #print(reach) print(reach[-1])
train
APPS_structured
Write a program that will calculate the number of trailing zeros in a factorial of a given number. N! = 1 * 2 * 3 * ... * N Be careful 1000! has 2568 digits... For more info, see: http://mathworld.wolfram.com/Factorial.html ## Examples python zeros(6) = 1 # 6! = 1 * 2 * 3 * 4 * 5 * 6 = 720 --> 1 trailing zero zeros(12) = 2 # 12! = 479001600 --> 2 trailing zeros  *Hint: You're not meant to calculate the factorial. Find another way to find the number of zeros.*
def zeros(n): # Initialize result count = 0 # Keep dividing n by # powers of 5 and # update Count i=5 while (n/i>=1): count += int(n/i) i *= 5 return int(count)
def zeros(n): # Initialize result count = 0 # Keep dividing n by # powers of 5 and # update Count i=5 while (n/i>=1): count += int(n/i) i *= 5 return int(count)
train
APPS_structured
Bit Vectors/Bitmaps A bitmap is one way of efficiently representing sets of unique integers using single bits. To see how this works, we can represent a set of unique integers between 0 and < 20 using a vector/array of 20 bits:  var set = [3, 14, 2, 11, 16, 4, 6];  var bitmap = [0, 0, 1, 1, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 0];  As you can see, with a bitmap, the length of the vector represents the range of unique values in the set (in this case 0-20), and the 0/1 represents whether or not the current index is equal to a value in the set. Task: Your task is to write a function toBits that will take in a set of uniqe integers and output a bit vector/bitmap (an array in javascript) using 1s and 0s to represent present and non-present values. Input: The function will be passed a set of unique integers in string form, in a random order, separated by line breaks. Each integer can be expected to have a unique value >= 0 and < 5000. The input will look like this: let exampleInput = '3\n14\n5\n19\n18\n1\n8\n11\n2...' Output: The function will be expected to output a 5000 bit vector (array) of bits, either 0 or 1, for example: let exampleOutput = [0, 1, 1, 1, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0,...] More in-depth bitmap kata coming very soon, happy coding! To learn more about bitmapping and to see the inspiration for making these kata, checkout the book Programming Pearls by Jon Bently. It's a powerful resource for any programmer!
def to_bits(string): input=sorted([int(x) for x in string.split("\n")]) bitmap=[0]*5000 for i in input: bitmap[i]=1 return bitmap
def to_bits(string): input=sorted([int(x) for x in string.split("\n")]) bitmap=[0]*5000 for i in input: bitmap[i]=1 return bitmap
train
APPS_structured
"QAQ" is a word to denote an expression of crying. Imagine "Q" as eyes with tears and "A" as a mouth. Now Diamond has given Bort a string consisting of only uppercase English letters of length n. There is a great number of "QAQ" in the string (Diamond is so cute!). $8$ illustration by 猫屋 https://twitter.com/nekoyaliu Bort wants to know how many subsequences "QAQ" are in the string Diamond has given. Note that the letters "QAQ" don't have to be consecutive, but the order of letters should be exact. -----Input----- The only line contains a string of length n (1 ≤ n ≤ 100). It's guaranteed that the string only contains uppercase English letters. -----Output----- Print a single integer — the number of subsequences "QAQ" in the string. -----Examples----- Input QAQAQYSYIOIWIN Output 4 Input QAQQQZZYNOIWIN Output 3 -----Note----- In the first example there are 4 subsequences "QAQ": "QAQAQYSYIOIWIN", "QAQAQYSYIOIWIN", "QAQAQYSYIOIWIN", "QAQAQYSYIOIWIN".
# IAWT s = input() ans = 0 for i in range(len(s)): for j in range(i+1, len(s)): for k in range(j+1, len(s)): if s[i] == 'Q' and s[j] == 'A' and s[k] == 'Q': ans += 1 print(ans)
# IAWT s = input() ans = 0 for i in range(len(s)): for j in range(i+1, len(s)): for k in range(j+1, len(s)): if s[i] == 'Q' and s[j] == 'A' and s[k] == 'Q': ans += 1 print(ans)
train
APPS_structured
The function is not returning the correct values. Can you figure out why? python get_planet_name(3) # should return 'Earth' 
def get_planet_name(id): # a dictionary also can work as a switch case switcher = { 1:"Mercury", 2:"Venus", 3:"Earth", 4:"Mars", 5:"Jupiter", 6:"Saturn", 7:"Uranus", 8:"Neptune" } return switcher.get(id)
def get_planet_name(id): # a dictionary also can work as a switch case switcher = { 1:"Mercury", 2:"Venus", 3:"Earth", 4:"Mars", 5:"Jupiter", 6:"Saturn", 7:"Uranus", 8:"Neptune" } return switcher.get(id)
train
APPS_structured
## Task Implement a function which finds the numbers less than 2, and the indices of numbers greater than 1 in the given sequence, and returns them as a pair of sequences. Return a nested array or a tuple depending on the language: * The first sequence being only the 1s and 0s from the original sequence. * The second sequence being the indexes of the elements greater than 1 in the original sequence. ## Examples python [ 0, 1, 2, 1, 5, 6, 2, 1, 1, 0 ] => ( [ 0, 1, 1, 1, 1, 0 ], [ 2, 4, 5, 6 ] )  Please upvote and enjoy!
def binary_cleaner(seq): return [x for x in seq if x in [0, 1]], [i for i, x in enumerate(seq) if x > 1]
def binary_cleaner(seq): return [x for x in seq if x in [0, 1]], [i for i, x in enumerate(seq) if x > 1]
train
APPS_structured
Slime and his $n$ friends are at a party. Slime has designed a game for his friends to play. At the beginning of the game, the $i$-th player has $a_i$ biscuits. At each second, Slime will choose a biscuit randomly uniformly among all $a_1 + a_2 + \ldots + a_n$ biscuits, and the owner of this biscuit will give it to a random uniform player among $n-1$ players except himself. The game stops when one person will have all the biscuits. As the host of the party, Slime wants to know the expected value of the time that the game will last, to hold the next activity on time. For convenience, as the answer can be represented as a rational number $\frac{p}{q}$ for coprime $p$ and $q$, you need to find the value of $(p \cdot q^{-1})\mod 998\,244\,353$. You can prove that $q\mod 998\,244\,353 \neq 0$. -----Input----- The first line contains one integer $n\ (2\le n\le 100\,000)$: the number of people playing the game. The second line contains $n$ non-negative integers $a_1,a_2,\dots,a_n\ (1\le a_1+a_2+\dots+a_n\le 300\,000)$, where $a_i$ represents the number of biscuits the $i$-th person own at the beginning. -----Output----- Print one integer: the expected value of the time that the game will last, modulo $998\,244\,353$. -----Examples----- Input 2 1 1 Output 1 Input 2 1 2 Output 3 Input 5 0 0 0 0 35 Output 0 Input 5 8 4 2 0 1 Output 801604029 -----Note----- For the first example, in the first second, the probability that player $1$ will give the player $2$ a biscuit is $\frac{1}{2}$, and the probability that player $2$ will give the player $1$ a biscuit is $\frac{1}{2}$. But anyway, the game will stop after exactly $1$ second because only one player will occupy all biscuits after $1$ second, so the answer is $1$.
MOD = 998244353 n = int(input()) a = list(map(int, input().split())) tot = sum(a) def inv(x): return pow(x, MOD - 2, MOD) l = [0, pow(n, tot, MOD) - 1] for i in range(1, tot): aC = i cC = (n - 1) * (tot - i) curr = (aC + cC) * l[-1] curr -= tot * (n - 1) curr -= aC * l[-2] curr *= inv(cC) curr %= MOD l.append(curr) out = 0 for v in a: out += l[tot - v] out %= MOD zero = l[tot] out -= (n - 1) * zero out *= inv(n) print(out % MOD)
MOD = 998244353 n = int(input()) a = list(map(int, input().split())) tot = sum(a) def inv(x): return pow(x, MOD - 2, MOD) l = [0, pow(n, tot, MOD) - 1] for i in range(1, tot): aC = i cC = (n - 1) * (tot - i) curr = (aC + cC) * l[-1] curr -= tot * (n - 1) curr -= aC * l[-2] curr *= inv(cC) curr %= MOD l.append(curr) out = 0 for v in a: out += l[tot - v] out %= MOD zero = l[tot] out -= (n - 1) * zero out *= inv(n) print(out % MOD)
train
APPS_structured
Given an array of integers as strings and numbers, return the sum of the array values as if all were numbers. Return your answer as a number.
def sum_mix(arr): sum = 0 for i in range(len(arr)): if isinstance(arr[i], str): sum += int(arr[i]) else: sum += arr[i] return sum
def sum_mix(arr): sum = 0 for i in range(len(arr)): if isinstance(arr[i], str): sum += int(arr[i]) else: sum += arr[i] return sum
train
APPS_structured
Indraneel's student has given him data from two sets of experiments that the student has performed. Indraneel wants to establish a correlation between the two sets of data. Each data set is a sequence of $N$ numbers. The two data sets do not match number for number, but Indraneel believes that this is because data has been shifted due to inexact tuning of the equipment. For example, consider the following two sequences:  3 8 4 23 9 11 28 2 3 22 26 8 16 12  Indraneel observes that if we consider the subsequences $3,4,23,9$ and $2,3,22,8$ and examine their successive differences we get $1,19,-14$. He considers these two subsequences to be "identical". He would like to find the longest such pair of subsequences so that the successive differences are identical. Your task is to help him do this. -----Input:----- The first line of the input will contain a single integer $N$ indicating the number of data points in each of Indraneel's student's data sets. This is followed by two lines, each containing $N$ integers. -----Output:----- The output consists of three lines. The first line of output contains a single integer indicating the length of the longest pair of subsequences (one from each sequence) that has identical successive differences. This is followed by two lines each containing the corresponding subsequences. If there is more than one answer, it suffices to print one. -----Constraints:----- - $1 \leq N \leq 150$. - $0 \leq$ Each data point $\leq 1000$ -----Sample Input----- 7 3 8 4 23 9 11 28 2 3 22 26 8 16 12 -----Sample Output----- 4 3 4 23 9 2 3 22 8
# cook your dish here ans = [] mxlen = 0 def lcs(a,b,d,mxlen): L = [0]*(n+1) for i in range(n+1): L[i] = [0]*(n+1) #print("#",L,a,b) for i in range(1,n+1): for j in range(1,n+1): if a[i-1] == b[j-1]: L[i][j] = L[i-1][j-1] + 1 else: L[i][j] = max(L[i-1][j],L[i][j-1]) #print(L) if L[n][n] > mxlen: mxlen = L[n][n] i,j = n,n t = [] while i>0 and j>0: if a[i-1] == b[j-1]: t.insert(0,a[i-1]) i -= 1 j -= 1 elif L[i-1][j] > L[i][j-1]: i -= 1 else: j -= 1 #print(t) ans.append({d:t}) try: n = int(input()) a = [int(w) for w in input().split()] b = [int(w) for w in input().split()] minb = min(b) b = [(i-minb-1) for i in b] for i in range(-1000,1001): bb = b.copy() bb = [(j+i) for j in bb] lcs(a,bb,i,mxlen) ans = sorted(ans, key=lambda i: len(list(i.values())[0]),reverse = True) t = ans[0] d = list(t.keys())[0] t = t[d] print(len(t)) print(*t) t = [(i-d+minb+1) for i in t] print(*t) except: pass
# cook your dish here ans = [] mxlen = 0 def lcs(a,b,d,mxlen): L = [0]*(n+1) for i in range(n+1): L[i] = [0]*(n+1) #print("#",L,a,b) for i in range(1,n+1): for j in range(1,n+1): if a[i-1] == b[j-1]: L[i][j] = L[i-1][j-1] + 1 else: L[i][j] = max(L[i-1][j],L[i][j-1]) #print(L) if L[n][n] > mxlen: mxlen = L[n][n] i,j = n,n t = [] while i>0 and j>0: if a[i-1] == b[j-1]: t.insert(0,a[i-1]) i -= 1 j -= 1 elif L[i-1][j] > L[i][j-1]: i -= 1 else: j -= 1 #print(t) ans.append({d:t}) try: n = int(input()) a = [int(w) for w in input().split()] b = [int(w) for w in input().split()] minb = min(b) b = [(i-minb-1) for i in b] for i in range(-1000,1001): bb = b.copy() bb = [(j+i) for j in bb] lcs(a,bb,i,mxlen) ans = sorted(ans, key=lambda i: len(list(i.values())[0]),reverse = True) t = ans[0] d = list(t.keys())[0] t = t[d] print(len(t)) print(*t) t = [(i-d+minb+1) for i in t] print(*t) except: pass
train
APPS_structured
Everyone knows passphrases. One can choose passphrases from poems, songs, movies names and so on but frequently they can be guessed due to common cultural references. You can get your passphrases stronger by different means. One is the following: choose a text in capital letters including or not digits and non alphabetic characters, 1. shift each letter by a given number but the transformed letter must be a letter (circular shift), 2. replace each digit by its complement to 9, 3. keep such as non alphabetic and non digit characters, 4. downcase each letter in odd position, upcase each letter in even position (the first character is in position 0), 5. reverse the whole result. #Example: your text: "BORN IN 2015!", shift 1 1 + 2 + 3 -> "CPSO JO 7984!" 4 "CpSo jO 7984!" 5 "!4897 Oj oSpC" With longer passphrases it's better to have a small and easy program. Would you write it? https://en.wikipedia.org/wiki/Passphrase
from string import ascii_uppercase as letters, digits def play_pass(s, n): return "".join(c.lower() if i & 1 else c for i, c in enumerate(s.upper().translate( str.maketrans(letters + digits, letters[n:] + letters[:n] + digits[::-1]) )))[::-1]
from string import ascii_uppercase as letters, digits def play_pass(s, n): return "".join(c.lower() if i & 1 else c for i, c in enumerate(s.upper().translate( str.maketrans(letters + digits, letters[n:] + letters[:n] + digits[::-1]) )))[::-1]
train
APPS_structured
# Write this function ![](http://i.imgur.com/mlbRlEm.png) for i from 1 to n, do i % m and return the sum f(n=10, m=5) // returns 20 (1+2+3+4+0 + 1+2+3+4+0) *You'll need to get a little clever with performance, since n can be a very large number*
def f(n, m): times = n // m extra = n % m sum_mini_series = (m - 1) * (m - 1 + 1) // 2 sum_extra = (extra) * (extra + 1) // 2 return sum_mini_series * times + sum_extra
def f(n, m): times = n // m extra = n % m sum_mini_series = (m - 1) * (m - 1 + 1) // 2 sum_extra = (extra) * (extra + 1) // 2 return sum_mini_series * times + sum_extra
train
APPS_structured
Given a square matrix of size N×N, calculate the absolute difference between the sums of its diagonals. -----Input----- The first line contains a single integer N. The next N lines denote the matrix's rows, with each line containing N space-separated integers describing the columns. -----Output----- Print the absolute difference between the two sums of the matrix's diagonals as a single integer. -----Constraints----- 1<=N<=10 -----Example----- Input: 3 11 2 4 4 5 6 10 8 -12 Output: 15 -----Explanation----- The primary diagonal is: 11 5 -12 Sum across the primary diagonal: 11 + 5 - 12 = 4 The secondary diagonal is: 4 5 10 Sum across the secondary diagonal: 4 + 5 + 10 = 19 Difference: |4 - 19| = 15
def diagonal_difference(matrix): l = sum(matrix[i][i] for i in range(N)) r = sum(matrix[i][N-i-1] for i in range(N)) return abs(l - r) matrix = [] N = eval(input()) for _ in range(N): matrix.append(list(map(int, input().split()))) print(diagonal_difference(matrix))
def diagonal_difference(matrix): l = sum(matrix[i][i] for i in range(N)) r = sum(matrix[i][N-i-1] for i in range(N)) return abs(l - r) matrix = [] N = eval(input()) for _ in range(N): matrix.append(list(map(int, input().split()))) print(diagonal_difference(matrix))
train
APPS_structured
In this kata, you will make a function that converts between camelCase, snake_case, and kebab-case. You must write a function that changes to a given case. It must be able to handle all three case types: python py> change_case("snakeCase", "snake") "snake_case" py> change_case("some-lisp-name", "camel") "someLispName" py> change_case("map_to_all", "kebab") "map-to-all" py> change_case("doHTMLRequest", "kebab") "do-h-t-m-l-request" py> change_case("invalid-inPut_bad", "kebab") None py> change_case("valid-input", "huh???") None py> change_case("", "camel") ""  Your function must deal with invalid input as shown, though it will only be passed strings. Furthermore, all valid identifiers will be lowercase except when necessary, in other words on word boundaries in camelCase. _**(Any translations would be greatly appreciated!)**_
def change_case(identifier, targetCase): # kebab make dashes after all capital, snake underscore after capital # camel makes kebab to caps #account for if isBad(identifier): return None if targetCase == 'snake': return snake(identifier) elif targetCase == 'camel': return camel(identifier) elif targetCase == 'kebab': return kebab(identifier) return None def snake(myString): newString = myString for i in range (0, len(myString)): if ord(myString[i]) >= ord('A') and ord(myString[i]) <= ord('Z'): #means it is caps pos = newString.index(myString[i:]) newString = newString[:pos] + '_' + newString[pos].lower() + newString [pos + 1:] elif myString[i] == '-': pos = newString.index(myString[i:]) #newSting = newString = newString[:pos] + '_' + newString[pos + 1:] return newString.lower() def kebab(myString): newString = myString for i in range (0, len(myString)): if ord(myString[i]) > ord('A') -1 and ord(myString[i]) < ord('Z') +1: #means it is caps pos = newString.index(myString[i:]) newString = newString[:pos] + '-' + newString[pos].lower() + newString [pos + 1:] if myString[i] == '_': pos = newString.index(myString[i:]) #newSting = newString = newString[:pos] + '-' + newString[pos + 1:] #means it is underscore return newString.lower() def camel(myString): #why doesnt this work if len(myString) ==0: return myString myString = myString.replace('-', '_') newString = myString.split('_') for i in range (0, len(newString)): if i != 0: newString[i] = newString[i][0].upper() + newString[i][1:] return "".join(newString) # def isBad(myString): if '_' in myString and '-' in myString: return True if '--' in myString or '__' in myString: return True if not myString.lower() == myString and '_' in myString: return True if not myString.lower() == myString and '-' in myString: return True return False
def change_case(identifier, targetCase): # kebab make dashes after all capital, snake underscore after capital # camel makes kebab to caps #account for if isBad(identifier): return None if targetCase == 'snake': return snake(identifier) elif targetCase == 'camel': return camel(identifier) elif targetCase == 'kebab': return kebab(identifier) return None def snake(myString): newString = myString for i in range (0, len(myString)): if ord(myString[i]) >= ord('A') and ord(myString[i]) <= ord('Z'): #means it is caps pos = newString.index(myString[i:]) newString = newString[:pos] + '_' + newString[pos].lower() + newString [pos + 1:] elif myString[i] == '-': pos = newString.index(myString[i:]) #newSting = newString = newString[:pos] + '_' + newString[pos + 1:] return newString.lower() def kebab(myString): newString = myString for i in range (0, len(myString)): if ord(myString[i]) > ord('A') -1 and ord(myString[i]) < ord('Z') +1: #means it is caps pos = newString.index(myString[i:]) newString = newString[:pos] + '-' + newString[pos].lower() + newString [pos + 1:] if myString[i] == '_': pos = newString.index(myString[i:]) #newSting = newString = newString[:pos] + '-' + newString[pos + 1:] #means it is underscore return newString.lower() def camel(myString): #why doesnt this work if len(myString) ==0: return myString myString = myString.replace('-', '_') newString = myString.split('_') for i in range (0, len(newString)): if i != 0: newString[i] = newString[i][0].upper() + newString[i][1:] return "".join(newString) # def isBad(myString): if '_' in myString and '-' in myString: return True if '--' in myString or '__' in myString: return True if not myString.lower() == myString and '_' in myString: return True if not myString.lower() == myString and '-' in myString: return True return False
train
APPS_structured
You're about to go on a trip around the world! On this trip you're bringing your trusted backpack, that anything fits into. The bad news is that the airline has informed you, that your luggage cannot exceed a certain amount of weight. To make sure you're bringing your most valuable items on this journey you've decided to give all your items a score that represents how valuable this item is to you. It's your job to pack you bag so that you get the most value out of the items that you decide to bring. Your input will consist of two arrays, one for the scores and one for the weights. You input will always be valid lists of equal length, so you don't have to worry about verifying your input. You'll also be given a maximum weight. This is the weight that your backpack cannot exceed. For instance, given these inputs: scores = [15, 10, 9, 5] weights = [1, 5, 3, 4] capacity = 8 The maximum score will be 29. This number comes from bringing items 1, 3 and 4. Note: Your solution will have to be efficient as the running time of your algorithm will be put to a test.
def pack_bagpack(scores, weights, capacity): dp=[[0,[]] for i in range(capacity+1)] for j in range(1,len(scores)+1): r = [[0,[]] for i in range(capacity+1)] for i in range(1,capacity+1): c,p = weights[j-1], scores[j-1] if c<=i and p+dp[i-c][0]>dp[i][0]: r[i]=[p+dp[i-c][0], dp[i-c][1]+[j-1]] else: r[i]=dp[i] dp = r return dp[-1][0]
def pack_bagpack(scores, weights, capacity): dp=[[0,[]] for i in range(capacity+1)] for j in range(1,len(scores)+1): r = [[0,[]] for i in range(capacity+1)] for i in range(1,capacity+1): c,p = weights[j-1], scores[j-1] if c<=i and p+dp[i-c][0]>dp[i][0]: r[i]=[p+dp[i-c][0], dp[i-c][1]+[j-1]] else: r[i]=dp[i] dp = r return dp[-1][0]
train
APPS_structured
Complete the method which returns the number which is most frequent in the given input array. If there is a tie for most frequent number, return the largest number among them. Note: no empty arrays will be given. ## Examples  [12, 10, 8, 12, 7, 6, 4, 10, 12] --> 12 [12, 10, 8, 12, 7, 6, 4, 10, 12, 10] --> 12 [12, 10, 8, 8, 3, 3, 3, 3, 2, 4, 10, 12, 10] --> 3 
from collections import Counter def highest_rank(arr): return max(Counter(arr).items(), key=lambda x: [x[1], x[0]])[0]
from collections import Counter def highest_rank(arr): return max(Counter(arr).items(), key=lambda x: [x[1], x[0]])[0]
train
APPS_structured
=====Function Descriptions===== HTML Hypertext Markup Language is a standard markup language used for creating World Wide Web pages. Parsing Parsing is the process of syntactic analysis of a string of symbols. It involves resolving a string into its component parts and describing their syntactic roles. HTMLParser An HTMLParser instance is fed HTML data and calls handler methods when start tags, end tags, text, comments, and other markup elements are encountered. Example (based on the original Python documentation): Code from HTMLParser import HTMLParser # create a subclass and override the handler methods class MyHTMLParser(HTMLParser): def handle_starttag(self, tag, attrs): print "Found a start tag :", tag def handle_endtag(self, tag): print "Found an end tag :", tag def handle_startendtag(self, tag, attrs): print "Found an empty tag :", tag # instantiate the parser and fed it some HTML parser = MyHTMLParser() parser.feed("<html><head><title>HTML Parser - I</title></head>" +"<body><h1>HackerRank</h1><br /></body></html>") Output Found a start tag : html Found a start tag : head Found a start tag : title Found an end tag : title Found an end tag : head Found a start tag : body Found a start tag : h1 Found an end tag : h1 Found an empty tag : br Found an end tag : body Found an end tag : html .handle_starttag(tag, attrs) This method is called to handle the start tag of an element. (For example: <div class='marks'>) The tag argument is the name of the tag converted to lowercase. The attrs argument is a list of (name, value) pairs containing the attributes found inside the tag’s <> brackets. .handle_endtag(tag) This method is called to handle the end tag of an element. (For example: </div>) The tag argument is the name of the tag converted to lowercase. .handle_startendtag(tag,attrs) This method is called to handle the empty tag of an element. (For example: <br />) The tag argument is the name of the tag converted to lowercase. The attrs argument is a list of (name, value) pairs containing the attributes found inside the tag’s <> brackets. =====Problem Statement===== You are given an HTML code snippet of N lines. Your task is to print start tags, end tags and empty tags separately. Format your results in the following way: Start : Tag1 End : Tag1 Start : Tag2 -> Attribute2[0] > Attribute_value2[0] -> Attribute2[1] > Attribute_value2[1] -> Attribute2[2] > Attribute_value2[2] Start : Tag3 -> Attribute3[0] > None Empty : Tag4 -> Attribute4[0] > Attribute_value4[0] End : Tag3 End : Tag2 Here, the -> symbol indicates that the tag contains an attribute. It is immediately followed by the name of the attribute and the attribute value. The > symbol acts as a separator of the attribute and the attribute value. If an HTML tag has no attribute then simply print the name of the tag. If an attribute has no attribute value then simply print the name of the attribute value as None. Note: Do not detect any HTML tag, attribute or attribute value inside the HTML comment tags (<!-- Comments -->).Comments can be multiline as well. =====Input Format===== The first line contains integer N, the number of lines in a HTML code snippet. The next N lines contain HTML code. =====Constraints===== 0<N<100 =====Output Format===== Print the HTML tags, attributes and attribute values in order of their occurrence from top to bottom in the given snippet. Use proper formatting as explained in the problem statement.
import re from html.parser import HTMLParser class MyHTMLParser(HTMLParser): def handle_starttag(self, tag, attrs): print("Start".ljust(6) + ":", tag) for at in attrs: print("-> {} > {}".format(at[0], at[1])) def handle_endtag(self, tag): print("End".ljust(6) + ":", tag) def handle_startendtag(self, tag, attrs): print("Empty".ljust(6) + ":", tag) for at in attrs: print("-> {} > {}".format(at[0], at[1])) def __starting_point(): parser = MyHTMLParser() n = int(input().strip()) for _ in range(n): line = input() parser.feed(line) __starting_point()
import re from html.parser import HTMLParser class MyHTMLParser(HTMLParser): def handle_starttag(self, tag, attrs): print("Start".ljust(6) + ":", tag) for at in attrs: print("-> {} > {}".format(at[0], at[1])) def handle_endtag(self, tag): print("End".ljust(6) + ":", tag) def handle_startendtag(self, tag, attrs): print("Empty".ljust(6) + ":", tag) for at in attrs: print("-> {} > {}".format(at[0], at[1])) def __starting_point(): parser = MyHTMLParser() n = int(input().strip()) for _ in range(n): line = input() parser.feed(line) __starting_point()
train
APPS_structured
Given a binary tree, find the leftmost value in the last row of the tree. Example 1: Input: 2 / \ 1 3 Output: 1 Example 2: Input: 1 / \ 2 3 / / \ 4 5 6 / 7 Output: 7 Note: You may assume the tree (i.e., the given root node) is not NULL.
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def findBottomLeftValue(self, root): """ :type root: TreeNode :rtype: int """ q = [root] while any(q): res = q[0] q = [kid for node in q for kid in (node.left, node.right) if kid] return res.val
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def findBottomLeftValue(self, root): """ :type root: TreeNode :rtype: int """ q = [root] while any(q): res = q[0] q = [kid for node in q for kid in (node.left, node.right) if kid] return res.val
train
APPS_structured

# Lila: A Unified Benchmark for Mathematical Reasoning

### Citation Information

Cite this dataset and the source datasets (see sources.bib).

@INPROCEEDINGS{Mishra2022Lila,
author = {
Swaroop Mishra
and Matthew Finlayson
and Pan Lu
and Leonard Tang
and Sean Welleck
and Chitta Baral
and Tanmay Rajpurohit
and Oyvind Tafjord
and Ashish Sabharwal
and Peter Clark
and Ashwin Kalyan},
title = {Lila: A Unified Benchmark for Mathematical Reasoning},
booktitle = {Proceedings of the 2022 Conference on Empirical Methods in Natural Language Processing (EMNLP)},
year = {2022}
}